<commit_before>#include "doorman.h"
#include <wiringPi.h>

#include <string>
#include <cstdio>
#include <cmath>
#include <fstream>
#include <iostream>
#include <cstdlib>

using namespace std;

string command_read("read");
string command_readHuman("read-human");
string command_write("write");

#define COUNT 500000

int content[COUNT];

char newline = '\n';

int do_read(char *file, bool human) {
  cerr << "Listening... ";

  for (int i = 0; i < COUNT; i++) {
    content[i] = doorman::read();
    doorman::sleep();
  }

  cerr << "Done" << newline;

  ostream *output;

  if (file != 0) {
    output = new ofstream(file);
  } else {
    output = &cout;
  }

  cerr << "Writing... ";

  if (human) {
    int count = 0;
    int current, previous = -1;

    for (int i = 0; i < COUNT; i++) {
      current = content[i];

      if (current == previous) {
        count++;
      } else {
        if (previous != -1) {
          count = (int) round(count / 20.f);

          if (count > 20) {
            *output << newline;
          } else {
            for (int j = 0; j < count; j++) {
              *output << previous;
            }
          }
       }

        previous = current;
        count = 1;
      }
    }
  } else {
    for (int i = 0; i < COUNT; i++) {
      *output << content[i];
    }
  }

  cerr << "Done" << newline;

  return 0;
}

int do_write(char *channel_str, char *sound_str) {
  static int delay = 200;
  int channel = atoi(channel_str);
  int sound = atoi(sound_str);
  static int channel_map[] = {0b1111,0b0011,0b1011,0b0000,0b1000,0b0100,0b1100,0b0101,0b1101,0b0001,0b1001,0b0010,0b1010,0b0110,0b1110,0b0111};
  if(channel > channel_map.size() && channel > 0){
    cerr << "Channel not existing" << newline
    return 1
  }
  int channel_bit = channel_map[channel - 1];

  static int sound_map[] = {0b11110111,0b11111011,0b11111101};
  if(sound > sound_map.size() && sound > 0){
    cerr << "Channel not existing" << newline
    return 1
  }
  int sound_bit = sound_map[sound - 1];

  for(int i = 0; i < 10; i++){
    for(int j = 3; j >= 0; j--){
       doorman::write(1);
       delayMicroseconds(delay);
       doorman::write(0);
       delayMicroseconds(delay);
       doorman::write(channel_bit & (1 << j));
       delayMicroseconds(delay);
    }
    for(int j=7; j >= 0; j--){
       doorman::write(1);
       delayMicroseconds(delay);
       doorman::write(0);
       delayMicroseconds(delay);
       doorman::write(sound_bit & (1 << j));
       delayMicroseconds(delay);
    }
    doorman::write(1);
    delayMicroseconds(delay);
    doorman::write(0);
    delayMicroseconds(delay*30);
  }
return 0;
}

int main(int argc, char ** argv) {
  if (argc < 2) {
    fprintf(stderr, "Invalid number of arguments: %d, at least 2 \nUsage: %s <mode>\n", argc - 1, argv[0]);
    return 1;
  }

  char *command = argv[2];
  char *file = (argc == 3) ? argv[3] : 0;

  doorman::setup();

  if (command_read == argv[1]) {
    return do_read(file, false);
  } else if (command_readHuman == argv[1]) {
    return do_read(file, true);
  } else if (command_write == argv[1] && argc == 4) {
    return do_write(argv[2], argv[3]);
  } else {
    fprintf(stderr, "Invalid mode \"%s\", valid modes are \"read\", \"read-human\" and \"write <channel> <sound>\"\n", argv[1]);
  }
}
<commit_msg>Fix for if statement<commit_after>#include "doorman.h"
#include <wiringPi.h>

#include <string>
#include <cstdio>
#include <cmath>
#include <fstream>
#include <iostream>
#include <cstdlib>

using namespace std;

string command_read("read");
string command_readHuman("read-human");
string command_write("write");

#define COUNT 500000

int content[COUNT];

char newline = '\n';

int do_read(char *file, bool human) {
  cerr << "Listening... ";

  for (int i = 0; i < COUNT; i++) {
    content[i] = doorman::read();
    doorman::sleep();
  }

  cerr << "Done" << newline;

  ostream *output;

  if (file != 0) {
    output = new ofstream(file);
  } else {
    output = &cout;
  }

  cerr << "Writing... ";

  if (human) {
    int count = 0;
    int current, previous = -1;

    for (int i = 0; i < COUNT; i++) {
      current = content[i];

      if (current == previous) {
        count++;
      } else {
        if (previous != -1) {
          count = (int) round(count / 20.f);

          if (count > 20) {
            *output << newline;
          } else {
            for (int j = 0; j < count; j++) {
              *output << previous;
            }
          }
       }

        previous = current;
        count = 1;
      }
    }
  } else {
    for (int i = 0; i < COUNT; i++) {
      *output << content[i];
    }
  }

  cerr << "Done" << newline;

  return 0;
}

int do_write(char *channel_str, char *sound_str) {
  static int delay = 200;
  int channel = atoi(channel_str);
  int sound = atoi(sound_str);
  static int channel_map[] = {0b1111,0b0011,0b1011,0b0000,0b1000,0b0100,0b1100,0b0101,0b1101,0b0001,0b1001,0b0010,0b1010,0b0110,0b1110,0b0111};
  if(channel > channel_map.size() || channel < 1){
    cerr << "Channel not existing" << newline
    return 1
  }
  int channel_bit = channel_map[channel - 1];

  static int sound_map[] = {0b11110111,0b11111011,0b11111101};
  if(sound > sound_map.size() || channel < 1){
    cerr << "Channel not existing" << newline
    return 1
  }
  int sound_bit = sound_map[sound - 1];

  for(int i = 0; i < 10; i++){
    for(int j = 3; j >= 0; j--){
       doorman::write(1);
       delayMicroseconds(delay);
       doorman::write(0);
       delayMicroseconds(delay);
       doorman::write(channel_bit & (1 << j));
       delayMicroseconds(delay);
    }
    for(int j=7; j >= 0; j--){
       doorman::write(1);
       delayMicroseconds(delay);
       doorman::write(0);
       delayMicroseconds(delay);
       doorman::write(sound_bit & (1 << j));
       delayMicroseconds(delay);
    }
    doorman::write(1);
    delayMicroseconds(delay);
    doorman::write(0);
    delayMicroseconds(delay*30);
  }
return 0;
}

int main(int argc, char ** argv) {
  if (argc < 2) {
    fprintf(stderr, "Invalid number of arguments: %d, at least 2 \nUsage: %s <mode>\n", argc - 1, argv[0]);
    return 1;
  }

  char *command = argv[2];
  char *file = (argc == 3) ? argv[3] : 0;

  doorman::setup();

  if (command_read == argv[1]) {
    return do_read(file, false);
  } else if (command_readHuman == argv[1]) {
    return do_read(file, true);
  } else if (command_write == argv[1] && argc == 4) {
    return do_write(argv[2], argv[3]);
  } else {
    fprintf(stderr, "Invalid mode \"%s\", valid modes are \"read\", \"read-human\" and \"write <channel> <sound>\"\n", argv[1]);
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/translate/translate_infobar_delegate2.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/translate/translate_infobar_view.h"
#include "chrome/browser/translate/translate_manager2.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

// static
TranslateInfoBarDelegate2* TranslateInfoBarDelegate2::CreateInstance(
    Type type,
    TranslateErrors::Type error,
    TabContents* tab_contents,
    const std::string& original_language,
    const std::string& target_language) {
  if (!TranslateManager2::IsSupportedLanguage(original_language) ||
      !TranslateManager2::IsSupportedLanguage(target_language)) {
    return NULL;
  }
  return new TranslateInfoBarDelegate2(type, error, tab_contents,
                                       original_language, target_language);
}

TranslateInfoBarDelegate2::TranslateInfoBarDelegate2(
    Type type,
    TranslateErrors::Type error,
    TabContents* tab_contents,
    const std::string& original_language,
    const std::string& target_language)
    : InfoBarDelegate(tab_contents),
      type_(type),
      background_animation_(NONE),
      tab_contents_(tab_contents),
      original_language_index_(-1),
      target_language_index_(-1),
      error_(error),
      infobar_view_(NULL),
      prefs_(tab_contents_->profile()->GetPrefs()) {
  DCHECK((type_ != TRANSLATION_ERROR && error == TranslateErrors::NONE) ||
         (type_ == TRANSLATION_ERROR && error != TranslateErrors::NONE));

  std::vector<std::string> language_codes;
  TranslateManager2::GetSupportedLanguages(&language_codes);

  languages_.reserve(language_codes.size());
  for (std::vector<std::string>::const_iterator iter = language_codes.begin();
       iter != language_codes.end(); ++iter) {
    std::string language_code = *iter;

    if (language_code == original_language)
      original_language_index_ = iter - language_codes.begin();
    else if (language_code == target_language)
      target_language_index_ = iter - language_codes.begin();

    string16 language_name = GetLanguageDisplayableName(language_code);
    // Insert the language in languages_ in alphabetical order.
    std::vector<LanguageNamePair>::iterator iter2;
    for (iter2 = languages_.begin(); iter2 != languages_.end(); ++iter2) {
      if (language_name.compare(iter2->second) < 0)
        break;
    }
    languages_.insert(iter2, LanguageNamePair(language_code, language_name));
  }
  DCHECK(original_language_index_ != -1);
  DCHECK(target_language_index_ != -1);
}

int TranslateInfoBarDelegate2::GetLanguageCount() const {
  return static_cast<int>(languages_.size());
}

const std::string& TranslateInfoBarDelegate2::GetLanguageCodeAt(
    int index) const {
  DCHECK(index >=0 && index < GetLanguageCount());
  return languages_[index].first;
}

const string16& TranslateInfoBarDelegate2::GetLanguageDisplayableNameAt(
    int index) const {
  DCHECK(index >=0 && index < GetLanguageCount());
  return languages_[index].second;
}

const std::string& TranslateInfoBarDelegate2::GetOriginalLanguageCode() const {
  return GetLanguageCodeAt(original_language_index());
}

const std::string& TranslateInfoBarDelegate2::GetTargetLanguageCode() const {
  return GetLanguageCodeAt(target_language_index());
}

void TranslateInfoBarDelegate2::SetOriginalLanguage(int language_index) {
  DCHECK(language_index < static_cast<int>(languages_.size()));
  original_language_index_ = language_index;
  if (infobar_view_)
    infobar_view_->OriginalLanguageChanged();
  if (type_ == AFTER_TRANSLATE)
    Translate();
}

void TranslateInfoBarDelegate2::SetTargetLanguage(int language_index) {
  DCHECK(language_index < static_cast<int>(languages_.size()));
  target_language_index_ = language_index;
  if (infobar_view_)
    infobar_view_->TargetLanguageChanged();
  if (type_ == AFTER_TRANSLATE)
    Translate();
}

bool TranslateInfoBarDelegate2::IsError() {
  return type_ == TRANSLATION_ERROR;
}

void TranslateInfoBarDelegate2::Translate() {
  Singleton<TranslateManager2>::get()->TranslatePage(
      tab_contents_,
      GetLanguageCodeAt(original_language_index()),
      GetLanguageCodeAt(target_language_index()));
}

void TranslateInfoBarDelegate2::RevertTranslation() {
  Singleton<TranslateManager2>::get()->RevertTranslation(tab_contents_);
  tab_contents_->RemoveInfoBar(this);
}

void TranslateInfoBarDelegate2::TranslationDeclined() {
  // Remember that the user declined the translation so as to prevent showing a
  // translate infobar for that page again.  (TranslateManager initiates
  // translations when getting a LANGUAGE_DETERMINED from the page, which
  // happens when a load stops. That could happen multiple times, including
  // after the user already declined the translation.)
  tab_contents_->language_state().set_translation_declined(true);
}

void TranslateInfoBarDelegate2::InfoBarDismissed() {
  if (type_ != BEFORE_TRANSLATE)
    return;

  // The user closed the infobar without clicking the translate button.
  TranslationDeclined();
  UMA_HISTOGRAM_COUNTS("Translate.DeclineTranslateCloseInfobar", 1);
}

SkBitmap* TranslateInfoBarDelegate2::GetIcon() const {
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_TRANSLATE);
}

InfoBarDelegate::Type TranslateInfoBarDelegate2::GetInfoBarType() {
  return InfoBarDelegate::PAGE_ACTION_TYPE;
}

bool TranslateInfoBarDelegate2::IsLanguageBlacklisted() {
  const std::string& original_lang =
      GetLanguageCodeAt(original_language_index());
  return prefs_.IsLanguageBlacklisted(original_lang);
}

void TranslateInfoBarDelegate2::ToggleLanguageBlacklist() {
  const std::string& original_lang =
      GetLanguageCodeAt(original_language_index());
  if (prefs_.IsLanguageBlacklisted(original_lang)) {
    prefs_.RemoveLanguageFromBlacklist(original_lang);
  } else {
    prefs_.BlacklistLanguage(original_lang);
    tab_contents_->RemoveInfoBar(this);
  }
}

bool TranslateInfoBarDelegate2::IsSiteBlacklisted() {
  std::string host = GetPageHost();
  return !host.empty() && prefs_.IsSiteBlacklisted(host);
}

void TranslateInfoBarDelegate2::ToggleSiteBlacklist() {
  std::string host = GetPageHost();
  if (host.empty())
    return;

  if (prefs_.IsSiteBlacklisted(host)) {
    prefs_.RemoveSiteFromBlacklist(host);
  } else {
    prefs_.BlacklistSite(host);
    tab_contents_->RemoveInfoBar(this);
  }
}

bool TranslateInfoBarDelegate2::ShouldAlwaysTranslate() {
  return prefs_.IsLanguagePairWhitelisted(GetOriginalLanguageCode(),
                                          GetTargetLanguageCode());
}

void TranslateInfoBarDelegate2::ToggleAlwaysTranslate() {
  std::string original_lang = GetOriginalLanguageCode();
  std::string target_lang = GetTargetLanguageCode();
  if (prefs_.IsLanguagePairWhitelisted(original_lang, target_lang))
    prefs_.RemoveLanguagePairFromWhitelist(original_lang, target_lang);
  else
    prefs_.WhitelistLanguagePair(original_lang, target_lang);
}

string16 TranslateInfoBarDelegate2::GetMessageInfoBarText() {
  switch (type_) {
    case TRANSLATING:
      return l10n_util::GetStringFUTF16(
          IDS_TRANSLATE_INFOBAR_TRANSLATING_TO,
          GetLanguageDisplayableNameAt(target_language_index_));
    case TRANSLATION_ERROR:
      switch (error_) {
        case TranslateErrors::NETWORK:
          return l10n_util::GetStringUTF16(
              IDS_TRANSLATE_INFOBAR_ERROR_CANT_CONNECT);
        case TranslateErrors::INITIALIZATION_ERROR:
        case TranslateErrors::TRANSLATION_ERROR:
          return l10n_util::GetStringUTF16(
              IDS_TRANSLATE_INFOBAR_ERROR_CANT_TRANSLATE);
        default:
          NOTREACHED();
          return string16();
      }
    default:
      NOTREACHED();
      return string16();
  }
}

string16 TranslateInfoBarDelegate2::GetMessageInfoBarButtonText() {
  switch (type_) {
    case TRANSLATING:
      return string16();
    case TRANSLATION_ERROR:
      return l10n_util::GetStringUTF16(IDS_TRANSLATE_INFOBAR_RETRY);
    default:
      NOTREACHED();
      return string16();
  }
}

void TranslateInfoBarDelegate2::MessageInfoBarButtonPressed() {
  DCHECK(type_ == TRANSLATION_ERROR);
  Singleton<TranslateManager2>::get()->TranslatePage(
      tab_contents_,
      GetLanguageCodeAt(original_language_index()),
      GetLanguageCodeAt(target_language_index()));
}

void TranslateInfoBarDelegate2::UpdateBackgroundAnimation(
    TranslateInfoBarDelegate2* previous_infobar) {
  if (!previous_infobar || previous_infobar->IsError() == IsError()) {
    background_animation_ = NONE;
    return;
  }
  background_animation_ = IsError() ? NORMAL_TO_ERROR : ERROR_TO_NORMAL;
}

std::string TranslateInfoBarDelegate2::GetPageHost() {
  NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();
  return entry ? entry->url().HostNoBrackets() : std::string();
}

// static
string16 TranslateInfoBarDelegate2::GetLanguageDisplayableName(
    const std::string& language_code) {
  return l10n_util::GetDisplayNameForLocale(
      language_code, g_browser_process->GetApplicationLocale(), true);
}

// static
void TranslateInfoBarDelegate2::GetAfterTranslateStrings(
    std::vector<string16>* strings, bool* swap_languages) {
  DCHECK(strings);
  DCHECK(swap_languages);

  std::vector<size_t> offsets;
  string16 text =
      l10n_util::GetStringFUTF16(IDS_TRANSLATE_INFOBAR_AFTER_MESSAGE,
                                 string16(), string16(), &offsets);
  DCHECK(offsets.size() == 2U);

  if (offsets[0] > offsets[1]) {
    // Target language comes before source.
    int tmp = offsets[0];
    offsets[0] = offsets[0];
    offsets[1] = tmp;
    *swap_languages = true;
  } else {
    *swap_languages = false;
  }

  strings->push_back(text.substr(0, offsets[0]));
  strings->push_back(text.substr(offsets[0], offsets[1]));
  strings->push_back(text.substr(offsets[1]));
}

#if !defined(OS_WIN) && !defined(OS_CHROMEOS)
// Necessary so we link OK on Mac and Linux while the new translate infobars
// are being ported to these platforms.
InfoBar* TranslateInfoBarDelegate2::CreateInfoBar() {
  return NULL;
}
#endif
<commit_msg>Coverity: fix wrong assignment in swap in TranslateInfoBarDelegate2::GetAfterTranslateStrings.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <algorithm>

#include "chrome/browser/translate/translate_infobar_delegate2.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/translate/translate_infobar_view.h"
#include "chrome/browser/translate/translate_manager2.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

// static
TranslateInfoBarDelegate2* TranslateInfoBarDelegate2::CreateInstance(
    Type type,
    TranslateErrors::Type error,
    TabContents* tab_contents,
    const std::string& original_language,
    const std::string& target_language) {
  if (!TranslateManager2::IsSupportedLanguage(original_language) ||
      !TranslateManager2::IsSupportedLanguage(target_language)) {
    return NULL;
  }
  return new TranslateInfoBarDelegate2(type, error, tab_contents,
                                       original_language, target_language);
}

TranslateInfoBarDelegate2::TranslateInfoBarDelegate2(
    Type type,
    TranslateErrors::Type error,
    TabContents* tab_contents,
    const std::string& original_language,
    const std::string& target_language)
    : InfoBarDelegate(tab_contents),
      type_(type),
      background_animation_(NONE),
      tab_contents_(tab_contents),
      original_language_index_(-1),
      target_language_index_(-1),
      error_(error),
      infobar_view_(NULL),
      prefs_(tab_contents_->profile()->GetPrefs()) {
  DCHECK((type_ != TRANSLATION_ERROR && error == TranslateErrors::NONE) ||
         (type_ == TRANSLATION_ERROR && error != TranslateErrors::NONE));

  std::vector<std::string> language_codes;
  TranslateManager2::GetSupportedLanguages(&language_codes);

  languages_.reserve(language_codes.size());
  for (std::vector<std::string>::const_iterator iter = language_codes.begin();
       iter != language_codes.end(); ++iter) {
    std::string language_code = *iter;

    if (language_code == original_language)
      original_language_index_ = iter - language_codes.begin();
    else if (language_code == target_language)
      target_language_index_ = iter - language_codes.begin();

    string16 language_name = GetLanguageDisplayableName(language_code);
    // Insert the language in languages_ in alphabetical order.
    std::vector<LanguageNamePair>::iterator iter2;
    for (iter2 = languages_.begin(); iter2 != languages_.end(); ++iter2) {
      if (language_name.compare(iter2->second) < 0)
        break;
    }
    languages_.insert(iter2, LanguageNamePair(language_code, language_name));
  }
  DCHECK(original_language_index_ != -1);
  DCHECK(target_language_index_ != -1);
}

int TranslateInfoBarDelegate2::GetLanguageCount() const {
  return static_cast<int>(languages_.size());
}

const std::string& TranslateInfoBarDelegate2::GetLanguageCodeAt(
    int index) const {
  DCHECK(index >=0 && index < GetLanguageCount());
  return languages_[index].first;
}

const string16& TranslateInfoBarDelegate2::GetLanguageDisplayableNameAt(
    int index) const {
  DCHECK(index >=0 && index < GetLanguageCount());
  return languages_[index].second;
}

const std::string& TranslateInfoBarDelegate2::GetOriginalLanguageCode() const {
  return GetLanguageCodeAt(original_language_index());
}

const std::string& TranslateInfoBarDelegate2::GetTargetLanguageCode() const {
  return GetLanguageCodeAt(target_language_index());
}

void TranslateInfoBarDelegate2::SetOriginalLanguage(int language_index) {
  DCHECK(language_index < static_cast<int>(languages_.size()));
  original_language_index_ = language_index;
  if (infobar_view_)
    infobar_view_->OriginalLanguageChanged();
  if (type_ == AFTER_TRANSLATE)
    Translate();
}

void TranslateInfoBarDelegate2::SetTargetLanguage(int language_index) {
  DCHECK(language_index < static_cast<int>(languages_.size()));
  target_language_index_ = language_index;
  if (infobar_view_)
    infobar_view_->TargetLanguageChanged();
  if (type_ == AFTER_TRANSLATE)
    Translate();
}

bool TranslateInfoBarDelegate2::IsError() {
  return type_ == TRANSLATION_ERROR;
}

void TranslateInfoBarDelegate2::Translate() {
  Singleton<TranslateManager2>::get()->TranslatePage(
      tab_contents_,
      GetLanguageCodeAt(original_language_index()),
      GetLanguageCodeAt(target_language_index()));
}

void TranslateInfoBarDelegate2::RevertTranslation() {
  Singleton<TranslateManager2>::get()->RevertTranslation(tab_contents_);
  tab_contents_->RemoveInfoBar(this);
}

void TranslateInfoBarDelegate2::TranslationDeclined() {
  // Remember that the user declined the translation so as to prevent showing a
  // translate infobar for that page again.  (TranslateManager initiates
  // translations when getting a LANGUAGE_DETERMINED from the page, which
  // happens when a load stops. That could happen multiple times, including
  // after the user already declined the translation.)
  tab_contents_->language_state().set_translation_declined(true);
}

void TranslateInfoBarDelegate2::InfoBarDismissed() {
  if (type_ != BEFORE_TRANSLATE)
    return;

  // The user closed the infobar without clicking the translate button.
  TranslationDeclined();
  UMA_HISTOGRAM_COUNTS("Translate.DeclineTranslateCloseInfobar", 1);
}

SkBitmap* TranslateInfoBarDelegate2::GetIcon() const {
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_TRANSLATE);
}

InfoBarDelegate::Type TranslateInfoBarDelegate2::GetInfoBarType() {
  return InfoBarDelegate::PAGE_ACTION_TYPE;
}

bool TranslateInfoBarDelegate2::IsLanguageBlacklisted() {
  const std::string& original_lang =
      GetLanguageCodeAt(original_language_index());
  return prefs_.IsLanguageBlacklisted(original_lang);
}

void TranslateInfoBarDelegate2::ToggleLanguageBlacklist() {
  const std::string& original_lang =
      GetLanguageCodeAt(original_language_index());
  if (prefs_.IsLanguageBlacklisted(original_lang)) {
    prefs_.RemoveLanguageFromBlacklist(original_lang);
  } else {
    prefs_.BlacklistLanguage(original_lang);
    tab_contents_->RemoveInfoBar(this);
  }
}

bool TranslateInfoBarDelegate2::IsSiteBlacklisted() {
  std::string host = GetPageHost();
  return !host.empty() && prefs_.IsSiteBlacklisted(host);
}

void TranslateInfoBarDelegate2::ToggleSiteBlacklist() {
  std::string host = GetPageHost();
  if (host.empty())
    return;

  if (prefs_.IsSiteBlacklisted(host)) {
    prefs_.RemoveSiteFromBlacklist(host);
  } else {
    prefs_.BlacklistSite(host);
    tab_contents_->RemoveInfoBar(this);
  }
}

bool TranslateInfoBarDelegate2::ShouldAlwaysTranslate() {
  return prefs_.IsLanguagePairWhitelisted(GetOriginalLanguageCode(),
                                          GetTargetLanguageCode());
}

void TranslateInfoBarDelegate2::ToggleAlwaysTranslate() {
  std::string original_lang = GetOriginalLanguageCode();
  std::string target_lang = GetTargetLanguageCode();
  if (prefs_.IsLanguagePairWhitelisted(original_lang, target_lang))
    prefs_.RemoveLanguagePairFromWhitelist(original_lang, target_lang);
  else
    prefs_.WhitelistLanguagePair(original_lang, target_lang);
}

string16 TranslateInfoBarDelegate2::GetMessageInfoBarText() {
  switch (type_) {
    case TRANSLATING:
      return l10n_util::GetStringFUTF16(
          IDS_TRANSLATE_INFOBAR_TRANSLATING_TO,
          GetLanguageDisplayableNameAt(target_language_index_));
    case TRANSLATION_ERROR:
      switch (error_) {
        case TranslateErrors::NETWORK:
          return l10n_util::GetStringUTF16(
              IDS_TRANSLATE_INFOBAR_ERROR_CANT_CONNECT);
        case TranslateErrors::INITIALIZATION_ERROR:
        case TranslateErrors::TRANSLATION_ERROR:
          return l10n_util::GetStringUTF16(
              IDS_TRANSLATE_INFOBAR_ERROR_CANT_TRANSLATE);
        default:
          NOTREACHED();
          return string16();
      }
    default:
      NOTREACHED();
      return string16();
  }
}

string16 TranslateInfoBarDelegate2::GetMessageInfoBarButtonText() {
  switch (type_) {
    case TRANSLATING:
      return string16();
    case TRANSLATION_ERROR:
      return l10n_util::GetStringUTF16(IDS_TRANSLATE_INFOBAR_RETRY);
    default:
      NOTREACHED();
      return string16();
  }
}

void TranslateInfoBarDelegate2::MessageInfoBarButtonPressed() {
  DCHECK(type_ == TRANSLATION_ERROR);
  Singleton<TranslateManager2>::get()->TranslatePage(
      tab_contents_,
      GetLanguageCodeAt(original_language_index()),
      GetLanguageCodeAt(target_language_index()));
}

void TranslateInfoBarDelegate2::UpdateBackgroundAnimation(
    TranslateInfoBarDelegate2* previous_infobar) {
  if (!previous_infobar || previous_infobar->IsError() == IsError()) {
    background_animation_ = NONE;
    return;
  }
  background_animation_ = IsError() ? NORMAL_TO_ERROR : ERROR_TO_NORMAL;
}

std::string TranslateInfoBarDelegate2::GetPageHost() {
  NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();
  return entry ? entry->url().HostNoBrackets() : std::string();
}

// static
string16 TranslateInfoBarDelegate2::GetLanguageDisplayableName(
    const std::string& language_code) {
  return l10n_util::GetDisplayNameForLocale(
      language_code, g_browser_process->GetApplicationLocale(), true);
}

// static
void TranslateInfoBarDelegate2::GetAfterTranslateStrings(
    std::vector<string16>* strings, bool* swap_languages) {
  DCHECK(strings);
  DCHECK(swap_languages);

  std::vector<size_t> offsets;
  string16 text =
      l10n_util::GetStringFUTF16(IDS_TRANSLATE_INFOBAR_AFTER_MESSAGE,
                                 string16(), string16(), &offsets);
  DCHECK(offsets.size() == 2U);

  if (offsets[0] > offsets[1]) {
    // Target language comes before source.
    std::swap(offsets[0], offsets[1]);
    *swap_languages = true;
  } else {
    *swap_languages = false;
  }

  strings->push_back(text.substr(0, offsets[0]));
  strings->push_back(text.substr(offsets[0], offsets[1]));
  strings->push_back(text.substr(offsets[1]));
}

#if !defined(OS_WIN) && !defined(OS_CHROMEOS)
// Necessary so we link OK on Mac and Linux while the new translate infobars
// are being ported to these platforms.
InfoBar* TranslateInfoBarDelegate2::CreateInfoBar() {
  return NULL;
}
#endif
<|endoftext|>


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

#include <mesos/quota/quota.hpp>

#include <process/metrics/metrics.hpp>

#include <stout/strings.hpp>

#include "master/allocator/mesos/hierarchical.hpp"
#include "master/allocator/mesos/metrics.hpp"

using std::string;
using std::vector;

using process::metrics::Gauge;

namespace mesos {
namespace internal {
namespace master {
namespace allocator {
namespace internal {

Metrics::Metrics(const HierarchicalAllocatorProcess& _allocator)
  : allocator(_allocator.self()),
    event_queue_dispatches(
        "allocator/mesos/event_queue_dispatches",
        process::defer(
            allocator, &HierarchicalAllocatorProcess::_event_queue_dispatches)),
    event_queue_dispatches_(
        "allocator/event_queue_dispatches",
        process::defer(
            allocator, &HierarchicalAllocatorProcess::_event_queue_dispatches)),
    allocation_runs("allocator/mesos/allocation_runs"),
    allocation_run("allocator/mesos/allocation_run", Hours(1))
{
  process::metrics::add(event_queue_dispatches);
  process::metrics::add(event_queue_dispatches_);
  process::metrics::add(allocation_runs);
  process::metrics::add(allocation_run);

  // Create and install gauges for the total and allocated
  // amount of standard scalar resources.
  //
  // TODO(bbannier) Add support for more than just scalar resources.
  // TODO(bbannier) Simplify this once MESOS-3214 is fixed.
  // TODO(dhamon): Set these up dynamically when adding a slave based on the
  // resources the slave exposes.
  string resources[] = {"cpus", "mem", "disk"};

  foreach (const string& resource, resources) {
    Gauge total(
        "allocator/mesos/resources/" + resource + "/total",
        defer(allocator,
              &HierarchicalAllocatorProcess::_resources_total,
              resource));

    Gauge offered_or_allocated(
        "allocator/mesos/resources/" + resource + "/offered_or_allocated",
        defer(allocator,
              &HierarchicalAllocatorProcess::_resources_offered_or_allocated,
              resource));

    resources_total.push_back(total);
    resources_offered_or_allocated.push_back(offered_or_allocated);

    process::metrics::add(total);
    process::metrics::add(offered_or_allocated);
  }
}

Metrics::~Metrics()
{
  process::metrics::remove(event_queue_dispatches);
  process::metrics::remove(event_queue_dispatches_);
  process::metrics::remove(allocation_runs);
  process::metrics::remove(allocation_run);

  foreach (const Gauge& gauge, resources_total) {
    process::metrics::remove(gauge);
  }

  foreach (const Gauge& gauge, resources_offered_or_allocated) {
    process::metrics::remove(gauge);
  }

  foreachkey(const string& role, quota_allocated) {
    foreachvalue(const Gauge& gauge, quota_allocated[role]) {
      process::metrics::remove(gauge);
    }
  }

  foreachkey(const string& role, quota_guarantee) {
    foreachvalue(const Gauge& gauge, quota_guarantee[role]) {
      process::metrics::remove(gauge);
    }
  }
}

void Metrics::setQuota(const string& role, const Quota& quota)
{
  CHECK(!quota_allocated.contains(role));

  hashmap<string, Gauge> allocated;
  hashmap<string, Gauge> guarantees;

  foreach (const Resource& resource, quota.info.guarantee()) {
    CHECK_EQ(Value::SCALAR, resource.type());
    double value = resource.scalar().value();

    Gauge guarantee = Gauge(
        "allocator/mesos/quota"
        "/roles/" + role +
        "/resources/" + resource.name() +
        "/guarantee",
        process::defer([value]() { return value; }));

    Gauge offered_or_allocated(
        "allocator/mesos/quota"
        "/roles/" + role +
        "/resources/" + resource.name() +
        "/offered_or_allocated",
        defer(allocator,
              &HierarchicalAllocatorProcess::_quota_allocated,
              role,
              resource.name()));

    guarantees.put(resource.name(), guarantee);
    allocated.put(resource.name(), offered_or_allocated);

    process::metrics::add(guarantee);
    process::metrics::add(offered_or_allocated);
  }

  quota_allocated[role] = allocated;
  quota_guarantee[role] = guarantees;
}

void Metrics::removeQuota(const string& role)
{
  CHECK(quota_allocated.contains(role));

  foreachvalue (const Gauge& gauge, quota_allocated[role]) {
    process::metrics::remove(gauge);
  }

  quota_allocated.erase(role);
}

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

#include <mesos/quota/quota.hpp>

#include <process/metrics/metrics.hpp>

#include <stout/strings.hpp>

#include "master/allocator/mesos/hierarchical.hpp"
#include "master/allocator/mesos/metrics.hpp"

using std::string;
using std::vector;

using process::metrics::Gauge;

namespace mesos {
namespace internal {
namespace master {
namespace allocator {
namespace internal {

Metrics::Metrics(const HierarchicalAllocatorProcess& _allocator)
  : allocator(_allocator.self()),
    event_queue_dispatches(
        "allocator/mesos/event_queue_dispatches",
        process::defer(
            allocator, &HierarchicalAllocatorProcess::_event_queue_dispatches)),
    event_queue_dispatches_(
        "allocator/event_queue_dispatches",
        process::defer(
            allocator, &HierarchicalAllocatorProcess::_event_queue_dispatches)),
    allocation_runs("allocator/mesos/allocation_runs"),
    allocation_run("allocator/mesos/allocation_run", Hours(1))
{
  process::metrics::add(event_queue_dispatches);
  process::metrics::add(event_queue_dispatches_);
  process::metrics::add(allocation_runs);
  process::metrics::add(allocation_run);

  // Create and install gauges for the total and allocated
  // amount of standard scalar resources.
  //
  // TODO(bbannier) Add support for more than just scalar resources.
  // TODO(bbannier) Simplify this once MESOS-3214 is fixed.
  // TODO(dhamon): Set these up dynamically when adding a slave based on the
  // resources the slave exposes.
  string resources[] = {"cpus", "mem", "disk"};

  foreach (const string& resource, resources) {
    Gauge total(
        "allocator/mesos/resources/" + resource + "/total",
        defer(allocator,
              &HierarchicalAllocatorProcess::_resources_total,
              resource));

    Gauge offered_or_allocated(
        "allocator/mesos/resources/" + resource + "/offered_or_allocated",
        defer(allocator,
              &HierarchicalAllocatorProcess::_resources_offered_or_allocated,
              resource));

    resources_total.push_back(total);
    resources_offered_or_allocated.push_back(offered_or_allocated);

    process::metrics::add(total);
    process::metrics::add(offered_or_allocated);
  }
}

Metrics::~Metrics()
{
  process::metrics::remove(event_queue_dispatches);
  process::metrics::remove(event_queue_dispatches_);
  process::metrics::remove(allocation_runs);
  process::metrics::remove(allocation_run);

  foreach (const Gauge& gauge, resources_total) {
    process::metrics::remove(gauge);
  }

  foreach (const Gauge& gauge, resources_offered_or_allocated) {
    process::metrics::remove(gauge);
  }

  foreachkey (const string& role, quota_allocated) {
    foreachvalue (const Gauge& gauge, quota_allocated[role]) {
      process::metrics::remove(gauge);
    }
  }

  foreachkey (const string& role, quota_guarantee) {
    foreachvalue (const Gauge& gauge, quota_guarantee[role]) {
      process::metrics::remove(gauge);
    }
  }
}

void Metrics::setQuota(const string& role, const Quota& quota)
{
  CHECK(!quota_allocated.contains(role));

  hashmap<string, Gauge> allocated;
  hashmap<string, Gauge> guarantees;

  foreach (const Resource& resource, quota.info.guarantee()) {
    CHECK_EQ(Value::SCALAR, resource.type());
    double value = resource.scalar().value();

    Gauge guarantee = Gauge(
        "allocator/mesos/quota"
        "/roles/" + role +
        "/resources/" + resource.name() +
        "/guarantee",
        process::defer([value]() { return value; }));

    Gauge offered_or_allocated(
        "allocator/mesos/quota"
        "/roles/" + role +
        "/resources/" + resource.name() +
        "/offered_or_allocated",
        defer(allocator,
              &HierarchicalAllocatorProcess::_quota_allocated,
              role,
              resource.name()));

    guarantees.put(resource.name(), guarantee);
    allocated.put(resource.name(), offered_or_allocated);

    process::metrics::add(guarantee);
    process::metrics::add(offered_or_allocated);
  }

  quota_allocated[role] = allocated;
  quota_guarantee[role] = guarantees;
}

void Metrics::removeQuota(const string& role)
{
  CHECK(quota_allocated.contains(role));

  foreachvalue (const Gauge& gauge, quota_allocated[role]) {
    process::metrics::remove(gauge);
  }

  quota_allocated.erase(role);
}

} // namespace internal {
} // namespace allocator {
} // namespace master {
} // namespace internal {
} // namespace mesos {
<|endoftext|>


<commit_before>/*++
Copyright (c) 2006 Microsoft Corporation

Module Name:

    smtlib_frontend.cpp

Abstract:

    Frontend for reading Smtlib input files

Author:

    Nikolaj Bjorner (nbjorner) 2006-11-3.

Revision History:

    Leonardo de Moura: new SMT 2.0 front-end, removed support for .smtc files and smtcmd_solver object.

--*/
#include<iostream>
#include<time.h>
#include<signal.h>
#include"smtlib_solver.h"
#include"timeout.h"
#include"smt2parser.h"
#include"dl_cmds.h"
#include"dbg_cmds.h"
#include"polynomial_cmds.h"
#include"subpaving_cmds.h"
#include"smt_strategic_solver.h"
#include"smt_solver.h"

extern bool g_display_statistics;
extern void display_config();
static clock_t             g_start_time;
static smtlib::solver*     g_solver      = 0;
static cmd_context *       g_cmd_context = 0;

static void display_statistics() {
    clock_t end_time = clock();
    if ((g_solver || g_cmd_context) && g_display_statistics) {
        std::cout.flush();
        std::cerr.flush();
        if (g_solver) {
            g_solver->display_statistics();
            memory::display_max_usage(std::cout);
            std::cout << "time:               " << ((static_cast<double>(end_time) - static_cast<double>(g_start_time)) / CLOCKS_PER_SEC) << " secs\n";
        }
        else if (g_cmd_context) {
            g_cmd_context->set_regular_stream("stdout");
            g_cmd_context->display_statistics(true, ((static_cast<double>(end_time) - static_cast<double>(g_start_time)) / CLOCKS_PER_SEC));
        }
    }
}

static void on_timeout() {
    #pragma omp critical (g_display_stats)
    {
        display_statistics();
        exit(0);
    }
}

static void on_ctrl_c(int) {
    signal (SIGINT, SIG_DFL);
    #pragma omp critical (g_display_stats)
    {
        display_statistics();
    }
    raise(SIGINT);
}

unsigned read_smtlib_file(char const * benchmark_file) {
    g_start_time = clock();
    register_on_timeout_proc(on_timeout);
    signal(SIGINT, on_ctrl_c);
    smtlib::solver solver;
    g_solver = &solver;

    bool ok = true;

    ok = solver.solve_smt(benchmark_file);
    if (!ok) {
        if (benchmark_file) {
            std::cerr << "ERROR: solving '" << benchmark_file << "'.\n";
        }
        else {
            std::cerr << "ERROR: solving input stream.\n";
        }
    }

    #pragma omp critical (g_display_stats)
    {
        display_statistics();
        register_on_timeout_proc(0);
        g_solver = 0;
    }
    return solver.get_error_code();
}

unsigned read_smtlib2_commands(char const * file_name) {
    g_start_time = clock();
    register_on_timeout_proc(on_timeout);
    signal(SIGINT, on_ctrl_c);
    cmd_context ctx;

    ctx.set_solver_factory(mk_smt_strategic_solver_factory());
    ctx.set_interpolating_solver_factory(mk_smt_solver_factory());

    install_dl_cmds(ctx);
    install_dbg_cmds(ctx);
    install_polynomial_cmds(ctx);
    install_subpaving_cmds(ctx);

    g_cmd_context = &ctx;
    signal(SIGINT, on_ctrl_c);

    bool result = true;
    if (file_name) {
        std::ifstream in(file_name);
        if (in.bad() || in.fail()) {
            std::cerr << "(error \"failed to open file '" << file_name << "'\")" << std::endl;
            exit(ERR_OPEN_FILE);
        }
        result = parse_smt2_commands(ctx, in);
        in.close();
    }
    else {
        result = parse_smt2_commands(ctx, std::cin, true);
    }

    #pragma omp critical (g_display_stats)
    {
        display_statistics();
        g_cmd_context = 0;
    }
    return result ? 0 : 1;
}

<commit_msg>undid previous fix<commit_after>/*++
Copyright (c) 2006 Microsoft Corporation

Module Name:

    smtlib_frontend.cpp

Abstract:

    Frontend for reading Smtlib input files

Author:

    Nikolaj Bjorner (nbjorner) 2006-11-3.

Revision History:

    Leonardo de Moura: new SMT 2.0 front-end, removed support for .smtc files and smtcmd_solver object.

--*/
#include<iostream>
#include<time.h>
#include<signal.h>
#include"smtlib_solver.h"
#include"timeout.h"
#include"smt2parser.h"
#include"dl_cmds.h"
#include"dbg_cmds.h"
#include"polynomial_cmds.h"
#include"subpaving_cmds.h"
#include"smt_strategic_solver.h"
#include"smt_solver.h"

extern bool g_display_statistics;
extern void display_config();
static clock_t             g_start_time;
static smtlib::solver*     g_solver      = 0;
static cmd_context *       g_cmd_context = 0;

static void display_statistics() {
    clock_t end_time = clock();
    if ((g_solver || g_cmd_context) && g_display_statistics) {
        std::cout.flush();
        std::cerr.flush();
        if (g_solver) {
            g_solver->display_statistics();
            memory::display_max_usage(std::cout);
            std::cout << "time:               " << ((static_cast<double>(end_time) - static_cast<double>(g_start_time)) / CLOCKS_PER_SEC) << " secs\n";
        }
        else if (g_cmd_context) {
            g_cmd_context->set_regular_stream("stdout");
            g_cmd_context->display_statistics(true, ((static_cast<double>(end_time) - static_cast<double>(g_start_time)) / CLOCKS_PER_SEC));
        }
    }
}

static void on_timeout() {
    #pragma omp critical (g_display_stats)
    {
        display_statistics();
        exit(0);
    }
}

static void on_ctrl_c(int) {
    signal (SIGINT, SIG_DFL);
    #pragma omp critical (g_display_stats)
    {
        display_statistics();
    }
    raise(SIGINT);
}

unsigned read_smtlib_file(char const * benchmark_file) {
    g_start_time = clock();
    register_on_timeout_proc(on_timeout);
    signal(SIGINT, on_ctrl_c);
    smtlib::solver solver;
    g_solver = &solver;

    bool ok = true;

    ok = solver.solve_smt(benchmark_file);
    if (!ok) {
        if (benchmark_file) {
            std::cerr << "ERROR: solving '" << benchmark_file << "'.\n";
        }
        else {
            std::cerr << "ERROR: solving input stream.\n";
        }
    }

    #pragma omp critical (g_display_stats)
    {
        display_statistics();
        register_on_timeout_proc(0);
        g_solver = 0;
    }
    return solver.get_error_code();
}

unsigned read_smtlib2_commands(char const * file_name) {
    g_start_time = clock();
    register_on_timeout_proc(on_timeout);
    signal(SIGINT, on_ctrl_c);
    cmd_context ctx;

    ctx.set_solver_factory(mk_smt_strategic_solver_factory());
    ctx.set_interpolating_solver_factory(mk_smt_solver_factory());

    install_dl_cmds(ctx);
    install_dbg_cmds(ctx);
    install_polynomial_cmds(ctx);
    install_subpaving_cmds(ctx);

    g_cmd_context = &ctx;
    signal(SIGINT, on_ctrl_c);

    bool result = true;
    if (file_name) {
        std::ifstream in(file_name);
        if (in.bad() || in.fail()) {
            std::cerr << "(error \"failed to open file '" << file_name << "'\")" << std::endl;
            exit(ERR_OPEN_FILE);
        }
        result = parse_smt2_commands(ctx, in);
    }
    else {
        result = parse_smt2_commands(ctx, std::cin, true);
    }

    #pragma omp critical (g_display_stats)
    {
        display_statistics();
        g_cmd_context = 0;
    }
    return result ? 0 : 1;
}

<|endoftext|>


<commit_before>/*
The MIT License(MIT)

Copyright(c) 2015 Armen Amirkhanian

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

// FuBeam (*Fu*damental Beam)
// Author: Armen Amirkhanian

// Calculates the deflection of a beam on an elastic foundation with possible separation.

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <exception>
#include <cmath>

int main(){
	std::string temp_diff, beam_thick, beam_leng, Em, rho, cote, kvalue;
	std::string num_points, file_name;
	double dT, h, L, E, UW, alpha, k;

	std::cout << "Enter temperature differential (deg F): ";
	std::cin >> temp_diff;
	std::cout << temp_diff << " deg F\n";
	std::cout << "Enter beam thickness (in): ";
	std::cin >> beam_thick;
	std::cout << beam_thick << " in\n";
	std::cout << "Enter beam length (in): ";
	std::cin >> beam_leng;
	std::cout << beam_leng << " in\n";
	std::cout << "Enter beam modulus of elasticity (psi): ";
	std::cin >> Em;
	std::cout << Em << " psi\n";
	std::cout << "Enter beam unit weight (lbs/ft3): ";
	std::cin >> rho;
	std::cout << rho << " lbs/ft3\n";
	std::cout << "Enter the beam coeff. of thermal expansion (1/F x10-5): ";
	std::cin >> cote;
	std::cout << cote << "E-05 /F\n";
	std::cout << "Enter subgrad k-value (pci): ";
	std::cin >> kvalue;
	std::cout << kvalue << " pci\n";
	std::cout << "How many points to generate for plot? ";
	std::cin >> num_points;
	std::cout << num_points << " points will be generated.\n";
	std::cout << "Enter file name for output of points: ";
	std::cin >> file_name;
	std::cout << "Data points will be outputted to " << file_name;

	try{
		dT = stod(temp_diff);
		h = stod(beam_thick);
		L = stod(beam_leng);
		E = stod(Em);
		UW = stod(rho);
		alpha = stod(cote);
		k = stod(kvalue);
	}
	catch (const std::invalid_argument ia){
		std::cout << "\nOne of the values entered is incorrect.\nGeneral Error: INVALID ARGUMENT\nSpecific Error: " << ia.what() << "\nTHIS ERROR IS IRRECOVERABLE. PROGRAM TERMINATING...\n";
		exit(EXIT_FAILURE);
	}
	catch (...){
		std::cout << "\nGENERAL EXCEPTION THROWN. UNRECOVERABLE. PROGRAM TERMINATING...\n";
		exit(EXIT_FAILURE);
	}

	std::ofstream output_file;
	// The underscore for the hardfail option is a bit puzzling. There is no data from MSDN about it.
	output_file.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::_Hardfail);
	try{
		output_file.open(file_name);
	}
	catch (std::ofstream::failure e){
		std::cout << "Failure reading creating file. Please make sure the file name does not conflict with an existing name. Also make sure you have write access to the location you are outputting data to.";
		exit(EXIT_FAILURE);
	}
}<commit_msg>First MWE. F4 calculation factor needs to be looked up and coded in.<commit_after>/*
The MIT License(MIT)

Copyright(c) 2015 Armen Amirkhanian

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

// FuBeam (*Fu*damental Beam)
// Author: Armen Amirkhanian

// Calculates the deflection of a beam on an elastic foundation with possible separation.

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <exception>
#include <cmath>

// Deflection due to uniform load and Winkler foundation
double uni_defl(double beta, double UW, double L, double C2, double C3, double C4, double C11, double E, double I, double x){
	// Ra, Ma, and thetaA boundary conditions go to zero for loading conditions
	// The entire equation for uniform load deflection is included in case
	// there is a desire to model different conditions in the future
	double Ra, Ma, thetaA, F1, F2, F3, F4, F5, wAp;

	Ra = 0;
	Ma = 0;
	thetaA = 0;

	F1 = cosh(beta*x)*cos(beta*x);
	F2 = cosh(beta*x)*sin(beta*x) + sinh(beta*x)*cos(beta*x);
	F3 = sinh(beta*x)*sin(beta*x);
	F5 = 1 - cosh(beta*x)*cos(beta*x);

	wAp = (UW*(C4*C2 - 2 * pow(C3, 2))) / (4 * E*I*pow(beta, 4)*C11);

	double wp;
	wp = wAp*F1 + (thetaA*F2) / (2 * beta) + (Ma*F3) / (2 * E*I*pow(beta, 2)) + (Ra*F4) / (4 * E*I*pow(beta, 3)) - (UW*F5) / (4 * E*I*pow(beta, 4));
	return wp;
}

// Deflection due to temperature differential
double temp_defl(double dT, double beta, double t, double gamma, double E, double I, double C1, double C2, double C3, double C4, double C11){

	// Ra and Ma boundary conditions go to zero for the loading conditions
	// The entire equation of temperature deflection is included in case
	// there is a desire to model different conditions in the future
	double Ra, Ma, F1, F2, F3, F4, thetaA, wAT, x;

	Ra = 0;
	Ma = 0;

	thetaA = (-(dT)*gamma*(C1*C2 + C3*C4 - C2)) / (beta*t*C11);
	wAT = (-(dT)*gamma*(pow(C4, 2) + 2 * C1*C3 - 2 * C3)) / (2 * pow(beta, 2)*t*C11);

	F1 = cosh(beta*x)*cos(beta*x);
	F2 = cosh(beta*x)*sin(beta*x) + sinh(beta*x)*cos(beta*x);
	F3 = sinh(beta*x)*sin(beta*x);

	double wt;
	wt = wAT*F1 + (thetaA*F2) / (2 * beta) + (Ma*F3) / (2 * E*I*pow(beta, 2)) + (Ra*F4) / (4 * E*I*pow(beta, 3)) - ((dT)*gamma*F3) / (2 * t*pow(beta, 2));
	return wt;
}

int main(){
	std::string temp_diff, beam_thick, beam_leng, beam_width, Em, rho, cote, kvalue;
	std::string num_points, file_name;
	double dT, h, L, bo, E, UW, gamma, k, x;
	int N;

	std::cout << "Enter temperature differential (deg F): ";
	std::cin >> temp_diff;
	std::cout << temp_diff << " deg F\n";
	std::cout << "Enter beam thickness (in): ";
	std::cin >> beam_thick;
	std::cout << beam_thick << " in\n";
	std::cout << "Enter beam length (in): ";
	std::cin >> beam_leng;
	std::cout << beam_leng << " in\n";
	std::cout << "Enter beam width (in): ";
	std::cin >> beam_width;
	std::cout << beam_width << " in\n";
	std::cout << "Enter beam modulus of elasticity (psi): ";
	std::cin >> Em;
	std::cout << Em << " psi\n";
	std::cout << "Enter beam unit weight (lbs/ft3): ";
	std::cin >> rho;
	std::cout << rho << " lbs/ft3\n";
	std::cout << "Enter the beam coeff. of thermal expansion (1/F x10-5): ";
	std::cin >> cote;
	std::cout << cote << "E-05 /F\n";
	std::cout << "Enter subgrad k-value (pci): ";
	std::cin >> kvalue;
	std::cout << kvalue << " pci\n";
	std::cout << "How many points to generate for plot? ";
	std::cin >> num_points;
	std::cout << num_points << " points will be generated.\n";
	std::cout << "Enter file name for output of points: ";
	std::cin >> file_name;
	std::cout << "Data points will be outputted to " << file_name;

	try{
		dT = stod(temp_diff);
		h = stod(beam_thick);
		L = stod(beam_leng);
		bo = stod(beam_width);
		E = stod(Em);
		UW = stod(rho);
		gamma = stod(cote);
		k = stod(kvalue);
		N = stod(num_points);
	}
	catch (const std::invalid_argument ia){
		std::cout << "\nOne of the values entered is incorrect.\nGeneral Error: INVALID ARGUMENT\nSpecific Error: " << ia.what() << "\nTHIS ERROR IS IRRECOVERABLE. PROGRAM TERMINATING...\n";
		exit(EXIT_FAILURE);
	}
	catch (...){
		std::cout << "\nGENERAL EXCEPTION THROWN. UNRECOVERABLE. PROGRAM TERMINATING...\n";
		exit(EXIT_FAILURE);
	}

	std::ofstream output_file;
	// The underscore for the hardfail option is a bit puzzling. There is no data from MSDN about it.
	output_file.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::_Hardfail);
	try{
		output_file.open(file_name);
	}
	catch (std::ofstream::failure e){
		std::cout << "Failure reading creating file. Please make sure the file name does not conflict with an existing name. Also make sure you have write access to the location you are outputting data to.";
		exit(EXIT_FAILURE);
	}
	// Calculate moment of inertia
	double I;
	I = (bo*pow(h,3)) / 12.0;

	// Calculate beta factor, constant for any location
	double beta;
	beta = pow((bo*k)/(4*E*I), 1.0 / 4.0);

	// Calculate boundary condition factors
	double C1, C2, C3, C4, C11;
	C1 = cosh(beta*L)*cos(beta*L);
	C2 = cosh(beta*L)*sin(beta*L) + sinh(beta*L)*cos(beta*L);
	C3 = sinh(beta*L)*sin(beta*L);
	C4 = cosh(beta*L)*sin(beta*L) - sinh(beta*L)*cos(beta*L);
	C11 = pow(sinh(beta*L), 2) - pow(sin(beta*L), 2);

	// Write header for output file
	output_file << "Output file from FuBeam\n";
	output_file << "Temperature differential: " << temp_diff << " deg F\n";
	output_file << "Beam thickness: " << beam_thick << " in\n";
	output_file << "Beam length: " << beam_leng << " in\n";
	output_file << "Beam width: " << beam_width << " in\n";
	output_file << "Elastic Modulus: " << Em << " psi\n";
	output_file << "Unit weight: " << rho << " lbs/ft3\n";
	output_file << "Coeff. of thermal expansion: " << cote << "E-05 /F\n";
	output_file << "Subgrade modulus: " << kvalue << " pci\n";
	output_file << num_points << " points will be generated.\n";
	output_file << "Dist. From End [in]\t" << "Deflection [in]\n";

	for (int i = 0; i < N; i++){
		x = (i / N)*L;
		output_file << x << "\t";
		output_file << temp_defl(dT, beta, h, gamma, E, I, C1, C2, C3, C4, C11) + uni_defl(beta, UW, L, C2, C3, C4, C11, E, I, x) << "\n";
	}
}<|endoftext|>


<commit_before>/* Copyright 2007-2015 QReal Research Group
 *
 * 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. */

#include "metaEditorSupportPlugin.h"

#include <QtCore/QProcess>
#include <QtWidgets/QApplication>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QProgressBar>
#include <QtWidgets/QDesktopWidget>

#include <qrkernel/settingsManager.h>
#include <qrmc/metaCompiler.h>

#include "editorGenerator.h"
#include "xmlParser.h"

using namespace qReal;
using namespace metaEditor;

MetaEditorSupportPlugin::MetaEditorSupportPlugin()
		: mGenerateEditorForQrxcAction(NULL)
		, mGenerateEditorWithQrmcAction(NULL)
		, mParseEditorXmlAction(NULL)
		, mRepoControlApi(NULL)
		, mCompilerSettingsPage(new PreferencesCompilerPage())
{
}

MetaEditorSupportPlugin::~MetaEditorSupportPlugin()
{
}

void MetaEditorSupportPlugin::init(PluginConfigurator const &configurator)
{
	mMainWindowInterface = &configurator.mainWindowInterpretersInterface();
	mLogicalRepoApi = &configurator.logicalModelApi().mutableLogicalRepoApi();
	mRepoControlApi = &configurator.repoControlInterface();
}

QList<ActionInfo> MetaEditorSupportPlugin::actions()
{
	mGenerateEditorForQrxcAction.setText(tr("Generate editor"));
	ActionInfo generateEditorForQrxcActionInfo(&mGenerateEditorForQrxcAction, "generators", "tools");
	connect(&mGenerateEditorForQrxcAction, SIGNAL(triggered()), this, SLOT(generateEditorForQrxc()));

	mGenerateEditorWithQrmcAction.setText(tr("Generate editor (qrmc)"));
	ActionInfo generateEditorWithQrmcActionInfo(&mGenerateEditorWithQrmcAction, "generators", "tools");
	connect(&mGenerateEditorWithQrmcAction, SIGNAL(triggered()), this, SLOT(generateEditorWithQrmc()));

	/*
	mParseEditorXmlAction.setText(tr("Parse editor xml")); // button for parsing xml, doesn't work
	ActionInfo parseEditorXmlActionInfo(&mParseEditorXmlAction, "generators", "tools");
	connect(&mParseEditorXmlAction, SIGNAL(triggered()), this, SLOT(parseEditorXml()));
	*/

	return QList<ActionInfo>() << generateEditorForQrxcActionInfo
	<< generateEditorWithQrmcActionInfo;
	//<< parseEditorXmlActionInfo;
}

QPair<QString, gui::PreferencesPage *> MetaEditorSupportPlugin::preferencesPage()
{
	return qMakePair(QObject::tr("Compiler"), static_cast<gui::PreferencesPage *>(mCompilerSettingsPage));
}

void MetaEditorSupportPlugin::generateEditorForQrxc()
{
	EditorGenerator editorGenerator(*mLogicalRepoApi, *mMainWindowInterface->errorReporter());

	QDir dir(".");

	QHash<Id, QPair<QString, QString> > metamodelList = editorGenerator.getMetamodelList();
	foreach (Id const &key, metamodelList.keys()) {
		QString const nameOfTheDirectory = metamodelList[key].first;
		QString const pathToQRealRoot = metamodelList[key].second;
		dir.mkpath(nameOfTheDirectory);
		QPair<QString, QString> const metamodelNames = editorGenerator.generateEditor(key, nameOfTheDirectory, pathToQRealRoot);

		if (!mMainWindowInterface->errorReporter()->wereErrors()) {
			if (QMessageBox::question(mMainWindowInterface->windowWidget()
					, tr("loading.."), QString(tr("Do you want to load generated editor %1?")).arg(metamodelNames.first),
					QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
			{
				return;
			}
			loadNewEditor(nameOfTheDirectory, metamodelNames
					, SettingsManager::value("pathToQmake").toString()
					, SettingsManager::value("pathToMake").toString()
					, SettingsManager::value("pluginExtension").toString()
					, SettingsManager::value("prefix").toString()
					, mLogicalRepoApi->stringProperty(key, "buildConfiguration"));
		}
	}
	if (metamodelList.isEmpty()) {
		mMainWindowInterface->errorReporter()->addError(tr("There is nothing to generate"));
	}
}

void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
	qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../../qrmc", mLogicalRepoApi);

	IdList const metamodels = mLogicalRepoApi->children(Id::rootId());

	QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QApplication::processEvents();
	QRect const screenRect = qApp->desktop()->availableGeometry();
	progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
	progress->setFixedWidth(progressBarWidth);
	progress->setFixedHeight(progressBarHeight);
	progress->setRange(0, 100);

	int forEditor = 60 / metamodels.size();

	foreach (Id const &key, metamodels) {
		QString const objectType = key.element();
	if (objectType == "MetamodelDiagram" && mLogicalRepoApi->isLogicalElement(key)) {
			QString nameOfTheDirectory = mLogicalRepoApi->stringProperty(key, "name of the directory");
			QString nameOfMetamodel = mLogicalRepoApi->stringProperty(key, "name");
			QString nameOfPlugin = nameOfTheDirectory.split("/").last();

			if (QMessageBox::question(mMainWindowInterface->windowWidget()
					, tr("loading..")
					, QString(tr("Do you want to compile and load editor %1?")).arg(nameOfPlugin)
					, QMessageBox::Yes, QMessageBox::No)
					== QMessageBox::No)
			{
				continue;
			}

			progress->setValue(5);

			if (!metaCompiler.compile(nameOfMetamodel)) { // generating source code for all metamodels
				QMessageBox::warning(mMainWindowInterface->windowWidget()
						, tr("error")
						, tr("Cannot generate source code for editor ") + nameOfPlugin);
				continue;
			}
			progress->setValue(20);

			QStringList qmakeArgs;
			qmakeArgs.append("CONFIG+=" + mLogicalRepoApi->stringProperty(key, "buildConfiguration"));
			qmakeArgs.append(nameOfMetamodel + ".pro");

			QProcess builder;
			builder.setWorkingDirectory(nameOfTheDirectory);
			const QStringList environment = QProcess::systemEnvironment();
			builder.setEnvironment(environment);
			builder.start(SettingsManager::value("pathToQmake").toString(), qmakeArgs);

			qDebug()  << "qmake";
			if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
				progress->setValue(40);
				builder.start(SettingsManager::value("pathToMake").toString());

				bool finished = builder.waitForFinished(100000);
				qDebug()  << "make";

				if (finished && (builder.exitCode() == 0)) {
					qDebug()  << "make ok";
					progress->setValue(progress->value() + forEditor / 2);

					QString normalizedName = nameOfPlugin.at(0).toUpper() + nameOfPlugin.mid(1);
					if (!nameOfPlugin.isEmpty()) {
						if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
							QMessageBox::warning(mMainWindowInterface->windowWidget()
									, tr("error")
									, tr("cannot unload plugin ") + normalizedName);
							progress->close();
							delete progress;
							continue;
						}
					}

					QString suffix = "";
					if (mLogicalRepoApi->stringProperty(key, "buildConfiguration") == "debug") {
						suffix = "-d";
					}

					QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
							//+ nameOfPlugin
							+ nameOfMetamodel
							+ suffix
							+ "."
							+ SettingsManager::value("pluginExtension").toString()
							;

					if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
						progress->setValue(progress->value() + forEditor / 2);
					}
				}
				progress->setValue(100);
			}
		}
	}
	if (progress->value() != 100) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
	}
	progress->setValue(100);
	progress->close();
	delete progress;
}

void MetaEditorSupportPlugin::parseEditorXml()
{
	if (!mMainWindowInterface->pluginLoaded("MetaEditor")) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("required plugin (MetaEditor) is not loaded"));
		return;
	}
	QDir dir(".");
	QString directoryName = ".";
	while (dir.cdUp()) {
		QFileInfoList const infoList = dir.entryInfoList(QDir::Dirs);
		foreach (QFileInfo const &directory, infoList){
			if (directory.baseName() == "qrxml") {
				directoryName = directory.absolutePath() + "/qrxml";
			}
		}
	}
	QString const fileName = QFileDialog::getOpenFileName(mMainWindowInterface->windowWidget()
			, tr("Select xml file to parse")
			, directoryName
			, "XML files (*.xml)");

	if (fileName.isEmpty())
		return;

	XmlParser parser(*mLogicalRepoApi);

	parser.parseFile(fileName);

	parser.loadIncludeList(fileName);

	mMainWindowInterface->reinitModels();
}

void MetaEditorSupportPlugin::loadNewEditor(QString const &directoryName
		, QPair<QString, QString> const &metamodelNames
		, QString const &commandFirst
		, QString const &commandSecond
		, QString const &extension
		, QString const &prefix
		, QString const &buildConfiguration
		)
{
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QString const metamodelName = metamodelNames.first;
	QString const normalizerMetamodelName = metamodelNames.second;

	if ((commandFirst == "") || (commandSecond == "") || (extension == "")) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("please, fill compiler settings"));
		return;
	}

	QString const normalizeDirName = metamodelName.at(0).toUpper() + metamodelName.mid(1);

	QProgressBar * const progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();

	QApplication::processEvents();

	QRect const screenRect = qApp->desktop()->availableGeometry();
	progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
	progress->setFixedWidth(progressBarWidth);
	progress->setFixedHeight(progressBarHeight);
	progress->setRange(0, 100);
	progress->setValue(5);

	const bool stateOfLoad = mMainWindowInterface->pluginLoaded(normalizeDirName);
	if (!mMainWindowInterface->unloadPlugin(normalizeDirName)) {
		progress->close();
		delete progress;
		return;
	}

	progress->setValue(20);
	QStringList qmakeArgs;
	qmakeArgs.append("CONFIG+=" + buildConfiguration);
	qmakeArgs.append(metamodelName + ".pro");

	QProcess builder;
	builder.setWorkingDirectory(directoryName);
	const QStringList environment = QProcess::systemEnvironment();
	builder.setEnvironment(environment);
	builder.start(commandFirst, qmakeArgs);

	if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
		progress->setValue(60);
		builder.start(commandSecond);

		if (builder.waitForFinished(60000) && (builder.exitCode() == 0)) {
			progress->setValue(80);

			if (stateOfLoad) {
				QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("Attention!"), tr("Please close QReal."));
				progress->close();
				delete progress;
				return;
			} else if (buildConfiguration == "debug") {
				if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "-d"+ "." + extension, normalizeDirName)) {
					progress->setValue(100);
				}
			} else {
				if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "." + extension, normalizeDirName)) {
					progress->setValue(100);
				}
			}
		}
	}

	if (progress->value() == 20) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot qmake new editor"));
	} else if (progress->value() == 60) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot make new editor"));
	}

	progress->setValue(100);
	progress->close();
	delete progress;
}
<commit_msg>- loading in palette is correct<commit_after>/* Copyright 2007-2015 QReal Research Group
 *
 * 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. */

#include "metaEditorSupportPlugin.h"

#include <QtCore/QProcess>
#include <QtWidgets/QApplication>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QProgressBar>
#include <QtWidgets/QDesktopWidget>

#include <qrkernel/settingsManager.h>
#include <qrmc/metaCompiler.h>

#include "editorGenerator.h"
#include "xmlParser.h"

using namespace qReal;
using namespace metaEditor;

MetaEditorSupportPlugin::MetaEditorSupportPlugin()
		: mGenerateEditorForQrxcAction(NULL)
		, mGenerateEditorWithQrmcAction(NULL)
		, mParseEditorXmlAction(NULL)
		, mRepoControlApi(NULL)
		, mCompilerSettingsPage(new PreferencesCompilerPage())
{
}

MetaEditorSupportPlugin::~MetaEditorSupportPlugin()
{
}

void MetaEditorSupportPlugin::init(PluginConfigurator const &configurator)
{
	mMainWindowInterface = &configurator.mainWindowInterpretersInterface();
	mLogicalRepoApi = &configurator.logicalModelApi().mutableLogicalRepoApi();
	mRepoControlApi = &configurator.repoControlInterface();
}

QList<ActionInfo> MetaEditorSupportPlugin::actions()
{
	mGenerateEditorForQrxcAction.setText(tr("Generate editor"));
	ActionInfo generateEditorForQrxcActionInfo(&mGenerateEditorForQrxcAction, "generators", "tools");
	connect(&mGenerateEditorForQrxcAction, SIGNAL(triggered()), this, SLOT(generateEditorForQrxc()));

	mGenerateEditorWithQrmcAction.setText(tr("Generate editor (qrmc)"));
	ActionInfo generateEditorWithQrmcActionInfo(&mGenerateEditorWithQrmcAction, "generators", "tools");
	connect(&mGenerateEditorWithQrmcAction, SIGNAL(triggered()), this, SLOT(generateEditorWithQrmc()));

	/*
	mParseEditorXmlAction.setText(tr("Parse editor xml")); // button for parsing xml, doesn't work
	ActionInfo parseEditorXmlActionInfo(&mParseEditorXmlAction, "generators", "tools");
	connect(&mParseEditorXmlAction, SIGNAL(triggered()), this, SLOT(parseEditorXml()));
	*/

	return QList<ActionInfo>() << generateEditorForQrxcActionInfo
	<< generateEditorWithQrmcActionInfo;
	//<< parseEditorXmlActionInfo;
}

QPair<QString, gui::PreferencesPage *> MetaEditorSupportPlugin::preferencesPage()
{
	return qMakePair(QObject::tr("Compiler"), static_cast<gui::PreferencesPage *>(mCompilerSettingsPage));
}

void MetaEditorSupportPlugin::generateEditorForQrxc()
{
	EditorGenerator editorGenerator(*mLogicalRepoApi, *mMainWindowInterface->errorReporter());

	QDir dir(".");

	QHash<Id, QPair<QString, QString> > metamodelList = editorGenerator.getMetamodelList();
	foreach (Id const &key, metamodelList.keys()) {
		QString const nameOfTheDirectory = metamodelList[key].first;
		QString const pathToQRealRoot = metamodelList[key].second;
		dir.mkpath(nameOfTheDirectory);
		QPair<QString, QString> const metamodelNames = editorGenerator.generateEditor(key, nameOfTheDirectory, pathToQRealRoot);

		if (!mMainWindowInterface->errorReporter()->wereErrors()) {
			if (QMessageBox::question(mMainWindowInterface->windowWidget()
					, tr("loading.."), QString(tr("Do you want to load generated editor %1?")).arg(metamodelNames.first),
					QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
			{
				return;
			}
			loadNewEditor(nameOfTheDirectory, metamodelNames
					, SettingsManager::value("pathToQmake").toString()
					, SettingsManager::value("pathToMake").toString()
					, SettingsManager::value("pluginExtension").toString()
					, SettingsManager::value("prefix").toString()
					, mLogicalRepoApi->stringProperty(key, "buildConfiguration"));
		}
	}
	if (metamodelList.isEmpty()) {
		mMainWindowInterface->errorReporter()->addError(tr("There is nothing to generate"));
	}
}

void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
	qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../../qrmc", mLogicalRepoApi);

	IdList const metamodels = mLogicalRepoApi->children(Id::rootId());

	QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QApplication::processEvents();
	QRect const screenRect = qApp->desktop()->availableGeometry();
	progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
	progress->setFixedWidth(progressBarWidth);
	progress->setFixedHeight(progressBarHeight);
	progress->setRange(0, 100);

	int forEditor = 60 / metamodels.size();

	foreach (Id const &key, metamodels) {
		QString const objectType = key.element();
	if (objectType == "MetamodelDiagram" && mLogicalRepoApi->isLogicalElement(key)) {
			QString nameOfTheDirectory = mLogicalRepoApi->stringProperty(key, "name of the directory");
			QString nameOfMetamodel = mLogicalRepoApi->stringProperty(key, "name");
			QString nameOfPlugin = nameOfTheDirectory.split("/").last();

			if (QMessageBox::question(mMainWindowInterface->windowWidget()
					, tr("loading..")
					, QString(tr("Do you want to compile and load editor %1?")).arg(nameOfPlugin)
					, QMessageBox::Yes, QMessageBox::No)
					== QMessageBox::No)
			{
				continue;
			}

			progress->setValue(5);

			if (!metaCompiler.compile(nameOfMetamodel)) { // generating source code for all metamodels
				QMessageBox::warning(mMainWindowInterface->windowWidget()
						, tr("error")
						, tr("Cannot generate source code for editor ") + nameOfPlugin);
				continue;
			}
			progress->setValue(20);

			QStringList qmakeArgs;
			qmakeArgs.append("CONFIG+=" + mLogicalRepoApi->stringProperty(key, "buildConfiguration"));
			qmakeArgs.append(nameOfMetamodel + ".pro");

			QProcess builder;
			builder.setWorkingDirectory(nameOfTheDirectory);
			const QStringList environment = QProcess::systemEnvironment();
			builder.setEnvironment(environment);
			builder.start(SettingsManager::value("pathToQmake").toString(), qmakeArgs);

			qDebug()  << "qmake";
			if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
				progress->setValue(40);
				builder.start(SettingsManager::value("pathToMake").toString());

				bool finished = builder.waitForFinished(100000);
				qDebug()  << "make";

				if (finished && (builder.exitCode() == 0)) {
					qDebug()  << "make ok";
					progress->setValue(progress->value() + forEditor / 2);

					QString normalizedName = nameOfMetamodel.at(0).toUpper() + nameOfMetamodel.mid(1);
					if (!nameOfMetamodel.isEmpty()) {
						if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
							QMessageBox::warning(mMainWindowInterface->windowWidget()
									, tr("error")
									, tr("cannot unload plugin ") + normalizedName);
							progress->close();
							delete progress;
							continue;
						}
					}

					QString suffix = "";
					if (mLogicalRepoApi->stringProperty(key, "buildConfiguration") == "debug") {
						suffix = "-d";
					}
					QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
							+ nameOfMetamodel
							+ suffix
							+ "."
							+ SettingsManager::value("pluginExtension").toString()
							;

					if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
						progress->setValue(progress->value() + forEditor / 2);
					}
				}
				progress->setValue(100);
			}
		}
	}
	if (progress->value() != 100) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
	}
	progress->setValue(100);
	progress->close();
	delete progress;
}

void MetaEditorSupportPlugin::parseEditorXml()
{
	if (!mMainWindowInterface->pluginLoaded("MetaEditor")) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("required plugin (MetaEditor) is not loaded"));
		return;
	}
	QDir dir(".");
	QString directoryName = ".";
	while (dir.cdUp()) {
		QFileInfoList const infoList = dir.entryInfoList(QDir::Dirs);
		foreach (QFileInfo const &directory, infoList){
			if (directory.baseName() == "qrxml") {
				directoryName = directory.absolutePath() + "/qrxml";
			}
		}
	}
	QString const fileName = QFileDialog::getOpenFileName(mMainWindowInterface->windowWidget()
			, tr("Select xml file to parse")
			, directoryName
			, "XML files (*.xml)");

	if (fileName.isEmpty())
		return;

	XmlParser parser(*mLogicalRepoApi);

	parser.parseFile(fileName);

	parser.loadIncludeList(fileName);

	mMainWindowInterface->reinitModels();
}

void MetaEditorSupportPlugin::loadNewEditor(QString const &directoryName
		, QPair<QString, QString> const &metamodelNames
		, QString const &commandFirst
		, QString const &commandSecond
		, QString const &extension
		, QString const &prefix
		, QString const &buildConfiguration
		)
{
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QString const metamodelName = metamodelNames.first;
	QString const normalizerMetamodelName = metamodelNames.second;

	if ((commandFirst == "") || (commandSecond == "") || (extension == "")) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("please, fill compiler settings"));
		return;
	}

	QString const normalizeDirName = metamodelName.at(0).toUpper() + metamodelName.mid(1);

	QProgressBar * const progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();

	QApplication::processEvents();

	QRect const screenRect = qApp->desktop()->availableGeometry();
	progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
	progress->setFixedWidth(progressBarWidth);
	progress->setFixedHeight(progressBarHeight);
	progress->setRange(0, 100);
	progress->setValue(5);

	const bool stateOfLoad = mMainWindowInterface->pluginLoaded(normalizeDirName);
	if (!mMainWindowInterface->unloadPlugin(normalizeDirName)) {
		progress->close();
		delete progress;
		return;
	}

	progress->setValue(20);
	QStringList qmakeArgs;
	qmakeArgs.append("CONFIG+=" + buildConfiguration);
	qmakeArgs.append(metamodelName + ".pro");

	QProcess builder;
	builder.setWorkingDirectory(directoryName);
	const QStringList environment = QProcess::systemEnvironment();
	builder.setEnvironment(environment);
	builder.start(commandFirst, qmakeArgs);

	if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
		progress->setValue(60);
		builder.start(commandSecond);

		if (builder.waitForFinished(60000) && (builder.exitCode() == 0)) {
			progress->setValue(80);

			if (stateOfLoad) {
				QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("Attention!"), tr("Please close QReal."));
				progress->close();
				delete progress;
				return;
			} else if (buildConfiguration == "debug") {
				if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "-d"+ "." + extension, normalizeDirName)) {
					progress->setValue(100);
				}
			} else {
				if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "." + extension, normalizeDirName)) {
					progress->setValue(100);
				}
			}
		}
	}

	if (progress->value() == 20) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot qmake new editor"));
	} else if (progress->value() == 60) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot make new editor"));
	}

	progress->setValue(100);
	progress->close();
	delete progress;
}
<|endoftext|>


<commit_before>#include "EnvMapMath.h"
#include "TextureUtils.h"
#include "CoordinateTransform.h"
#include "Actions/Actions.h"
#include "GaussianWeights.h"
#include <stdio.h>

void FastBlurCubemap::DoTask(const Texture& inputTex, Texture& outputTex)
{
	if (!inputTex.m_cubemap)
	{
		printf("Error: For this task required cubmap.\n");
		return;
	}

	int radius = m_blurRadius;
	int kernelSize = 2 * radius + 1;
	std::vector<double> kernel = GenerateKernel(1.0 / 3.0 * radius, kernelSize, 1000.0);
	Texture tmpTex = outputTex;

	Texture tmpTex2 = outputTex;
	Texture resTex = outputTex;

	for(int k = 0; k <6; ++k)
	{
		tmpTex = outputTex;
		tmpTex2 = outputTex;

		for(int ki = 0; ki <6; ++ki)
		{
			for (int i = 0;i<outputTex.m_height;i++)
			{
				for (int j = 0;j<outputTex.m_width;j++)
				{
					fpixel s(0.0, 0.0, 0.0);
					for(int n = -radius; n < radius+1; ++n)
					{
						int j_ = j + n;
						int k_ = ki;
						if (ki != 2 && ki != 3)
						{
							if (j_ < 0)
							{
								j_ += outputTex.m_width;
								switch(ki)
								{
								case 4:k_ = 0; break;
								case 5:k_ = 1; break;
								case 0:k_ = 5; break;
								case 1:k_ = 4; break;
								}
							}
							if (j_ >= outputTex.m_width)
							{
								j_ -= outputTex.m_width;
								switch(ki)
								{
								case 0:k_ = 4; break;
								case 1:k_ = 5; break;
								case 5:k_ = 0; break;
								case 4:k_ = 1; break;

								}
							}
							s += outputTex.m_faces[k_].m_buff[j_ + i*outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							if(k!= 0 && k!= 1)
							{
								if (ki==2)
								{
									if (j_ < 0)
									{
										j_ += outputTex.m_width;
										k_ = 0;
										s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - i - 1) + j_*outputTex.m_width] * kernel[n + radius];
									}
									else if (j_ >= outputTex.m_width)
									{
										j_ -= outputTex.m_width;
										j_ = outputTex.m_height - j_ - 1;
										k_ = 1;
										s += outputTex.m_faces[k_].m_buff[i + j_*outputTex.m_width] * kernel[n + radius];
									}
									else
									{
										s += outputTex.m_faces[k_].m_buff[j_ + i*outputTex.m_width] * kernel[n + radius];
									}
								}
								else//ki = 3
								{
									if (j_ < 0)
									{
										j_ += outputTex.m_width;
										k_ = 0;
										s += outputTex.m_faces[k_].m_buff[i + (outputTex.m_height - j_ - 1)*outputTex.m_width] * kernel[n + radius];
									}
									else if (j_ >= outputTex.m_width)
									{
										j_ -= outputTex.m_width;
										j_ = outputTex.m_height - j_ - 1;
										k_ = 1;
										s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - i - 1) + (outputTex.m_height - j_ - 1)*outputTex.m_width] * kernel[n + radius];
									}
									else
									{
										s += outputTex.m_faces[k_].m_buff[j_ + i*outputTex.m_width] * kernel[n + radius];
									}
								}
							}
							else
							{
								int i_ = i + n;
								int k_ = ki;
								if (ki == 2)
								{
									if (i_ < 0)
									{
										i_ += outputTex.m_height;
										k_ = 4;
										s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
									}
									else if (i_ >= outputTex.m_width)
									{
										i_ -= outputTex.m_width;
										i_ = outputTex.m_height - i_ - 1;
										k_ = 5;
										s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
									}
									else
									{
										s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
									}
								}
								if (ki == 3)
								{
									if (i_ < 0)
									{
										i_ += outputTex.m_height;
										i_ = outputTex.m_height - i_ - 1;
										k_ = 5;
										s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
									}
									else if (i_ >= outputTex.m_width)
									{
										i_ -= outputTex.m_width;
										k_ = 4;
										s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
									}
									else
									{
										s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
									}
								}
							}
						}
					}
					tmpTex.m_faces[ki].m_buff[j + i*outputTex.m_width]  = s;
				}
			}
		}

		for (int j = 0 ;j<outputTex.m_width;j++)
		{
			for (int i = 0;i<outputTex.m_height;i++)
			{
				fpixel s(0.0, 0.0, 0.0);
				for(int n = -radius; n < radius+1; ++n)
				{
					int i_ = i + n;
					int k_ = k;
					if (k == 2)
					{
						if (i_ < 0)
						{
							i_ += outputTex.m_height;
							k_ = 4;
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
						else if (i_ >= outputTex.m_width)
						{
							i_ -= outputTex.m_width;
							i_ = outputTex.m_height - i_ - 1;
							k_ = 5;
							s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
					}
					if (k == 3)
					{
						if (i_ < 0)
						{
							i_ += outputTex.m_height;
							i_ = outputTex.m_height - i_ - 1;
							k_ = 5;
							s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
						}
						else if (i_ >= outputTex.m_width)
						{
							i_ -= outputTex.m_width;
							k_ = 4;
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
					}
					else if(k == 5)
					{
						if (i_ < 0)
						{
							i_ += outputTex.m_height;
							i_ = outputTex.m_height - i_ - 1;
							k_ = 3;
							s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
						}
						else if (i_ >= outputTex.m_width)
						{
							i_ -= outputTex.m_width;
							i_ = outputTex.m_height - i_ - 1;
							k_ = 2;
							s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
					}
					else if(k == 4)
					{
						if (i_ < 0)
						{
							i_ += outputTex.m_height;
							k_ = 3;
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
						else if (i_ >= outputTex.m_width)
						{
							i_ -= outputTex.m_width;
							k_ = 2;
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
					}
					else if(k == 0)
					{
						if (i_ < 0)
						{
							i_ += outputTex.m_height;
							i_ = outputTex.m_width - 1 - i_;
							k_ = 3;
							s += tmpTex.m_faces[k_].m_buff[i_ + j * outputTex.m_width] * kernel[n + radius];
						}
						else if (i_ >= outputTex.m_width)
						{
							i_ -= outputTex.m_width;
							k_ = 2;
							s += tmpTex.m_faces[k_].m_buff[i_ + (outputTex.m_height - j - 1)*outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
					}
					else if(k == 1)
					{
						if (i_ < 0)
						{
							i_ += outputTex.m_height;
							k_ = 3;
							s += tmpTex.m_faces[k_].m_buff[i_ + (outputTex.m_height - j - 1) * outputTex.m_width] * kernel[n + radius];
						}
						else if (i_ >= outputTex.m_width)
						{
							i_ -= outputTex.m_width;
							i_ = outputTex.m_width - 1 - i_;
							k_ = 2;
							s += tmpTex.m_faces[k_].m_buff[i_ + j * outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
					}
				}
				tmpTex2.m_faces[k].m_buff[j + i*outputTex.m_width]  = s;
			}
		}
		resTex.m_faces[k] = tmpTex2.m_faces[k];
	}

	outputTex = resTex;
	outputTex.m_cubemap = true;
}
<commit_msg>Fixed crash<commit_after>#include "EnvMapMath.h"
#include "TextureUtils.h"
#include "CoordinateTransform.h"
#include "Actions/Actions.h"
#include "GaussianWeights.h"
#include <stdio.h>

void FastBlurCubemap::DoTask(const Texture& inputTex, Texture& outputTex)
{
	if (!inputTex.m_cubemap)
	{
		printf("Error: For this task required cubmap.\n");
		return;
	}

	outputTex = inputTex;

	int radius = m_blurRadius;
	int kernelSize = 2 * radius + 1;
	std::vector<double> kernel = GenerateKernel(1.0 / 3.0 * radius, kernelSize, 1000.0);
	Texture tmpTex = outputTex;

	Texture tmpTex2 = outputTex;
	Texture resTex = outputTex;

	for(int k = 0; k <6; ++k)
	{
		tmpTex = outputTex;
		tmpTex2 = outputTex;

		for(int ki = 0; ki <6; ++ki)
		{
			for (int i = 0;i<outputTex.m_height;i++)
			{
				for (int j = 0;j<outputTex.m_width;j++)
				{
					fpixel s(0.0, 0.0, 0.0);
					for(int n = -radius; n < radius+1; ++n)
					{
						int j_ = j + n;
						int k_ = ki;
						if (ki != 2 && ki != 3)
						{
							if (j_ < 0)
							{
								j_ += outputTex.m_width;
								switch(ki)
								{
								case 4:k_ = 0; break;
								case 5:k_ = 1; break;
								case 0:k_ = 5; break;
								case 1:k_ = 4; break;
								}
							}
							if (j_ >= outputTex.m_width)
							{
								j_ -= outputTex.m_width;
								switch(ki)
								{
								case 0:k_ = 4; break;
								case 1:k_ = 5; break;
								case 5:k_ = 0; break;
								case 4:k_ = 1; break;

								}
							}
							s += outputTex.m_faces[k_].m_buff[j_ + i*outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							if(k!= 0 && k!= 1)
							{
								if (ki==2)
								{
									if (j_ < 0)
									{
										j_ += outputTex.m_width;
										k_ = 0;
										s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - i - 1) + j_*outputTex.m_width] * kernel[n + radius];
									}
									else if (j_ >= outputTex.m_width)
									{
										j_ -= outputTex.m_width;
										j_ = outputTex.m_height - j_ - 1;
										k_ = 1;
										s += outputTex.m_faces[k_].m_buff[i + j_*outputTex.m_width] * kernel[n + radius];
									}
									else
									{
										s += outputTex.m_faces[k_].m_buff[j_ + i*outputTex.m_width] * kernel[n + radius];
									}
								}
								else//ki = 3
								{
									if (j_ < 0)
									{
										j_ += outputTex.m_width;
										k_ = 0;
										s += outputTex.m_faces[k_].m_buff[i + (outputTex.m_height - j_ - 1)*outputTex.m_width] * kernel[n + radius];
									}
									else if (j_ >= outputTex.m_width)
									{
										j_ -= outputTex.m_width;
										j_ = outputTex.m_height - j_ - 1;
										k_ = 1;
										s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - i - 1) + (outputTex.m_height - j_ - 1)*outputTex.m_width] * kernel[n + radius];
									}
									else
									{
										s += outputTex.m_faces[k_].m_buff[j_ + i*outputTex.m_width] * kernel[n + radius];
									}
								}
							}
							else
							{
								int i_ = i + n;
								int k_ = ki;
								if (ki == 2)
								{
									if (i_ < 0)
									{
										i_ += outputTex.m_height;
										k_ = 4;
										s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
									}
									else if (i_ >= outputTex.m_width)
									{
										i_ -= outputTex.m_width;
										i_ = outputTex.m_height - i_ - 1;
										k_ = 5;
										s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
									}
									else
									{
										s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
									}
								}
								if (ki == 3)
								{
									if (i_ < 0)
									{
										i_ += outputTex.m_height;
										i_ = outputTex.m_height - i_ - 1;
										k_ = 5;
										s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
									}
									else if (i_ >= outputTex.m_width)
									{
										i_ -= outputTex.m_width;
										k_ = 4;
										s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
									}
									else
									{
										s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
									}
								}
							}
						}
					}
					tmpTex.m_faces[ki].m_buff[j + i*outputTex.m_width]  = s;
				}
			}
		}

		for (int j = 0 ;j<outputTex.m_width;j++)
		{
			for (int i = 0;i<outputTex.m_height;i++)
			{
				fpixel s(0.0, 0.0, 0.0);
				for(int n = -radius; n < radius+1; ++n)
				{
					int i_ = i + n;
					int k_ = k;
					if (k == 2)
					{
						if (i_ < 0)
						{
							i_ += outputTex.m_height;
							k_ = 4;
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
						else if (i_ >= outputTex.m_width)
						{
							i_ -= outputTex.m_width;
							i_ = outputTex.m_height - i_ - 1;
							k_ = 5;
							s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
					}
					if (k == 3)
					{
						if (i_ < 0)
						{
							i_ += outputTex.m_height;
							i_ = outputTex.m_height - i_ - 1;
							k_ = 5;
							s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
						}
						else if (i_ >= outputTex.m_width)
						{
							i_ -= outputTex.m_width;
							k_ = 4;
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
					}
					else if(k == 5)
					{
						if (i_ < 0)
						{
							i_ += outputTex.m_height;
							i_ = outputTex.m_height - i_ - 1;
							k_ = 3;
							s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
						}
						else if (i_ >= outputTex.m_width)
						{
							i_ -= outputTex.m_width;
							i_ = outputTex.m_height - i_ - 1;
							k_ = 2;
							s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
					}
					else if(k == 4)
					{
						if (i_ < 0)
						{
							i_ += outputTex.m_height;
							k_ = 3;
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
						else if (i_ >= outputTex.m_width)
						{
							i_ -= outputTex.m_width;
							k_ = 2;
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
					}
					else if(k == 0)
					{
						if (i_ < 0)
						{
							i_ += outputTex.m_height;
							i_ = outputTex.m_width - 1 - i_;
							k_ = 3;
							s += tmpTex.m_faces[k_].m_buff[i_ + j * outputTex.m_width] * kernel[n + radius];
						}
						else if (i_ >= outputTex.m_width)
						{
							i_ -= outputTex.m_width;
							k_ = 2;
							s += tmpTex.m_faces[k_].m_buff[i_ + (outputTex.m_height - j - 1)*outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
					}
					else if(k == 1)
					{
						if (i_ < 0)
						{
							i_ += outputTex.m_height;
							k_ = 3;
							s += tmpTex.m_faces[k_].m_buff[i_ + (outputTex.m_height - j - 1) * outputTex.m_width] * kernel[n + radius];
						}
						else if (i_ >= outputTex.m_width)
						{
							i_ -= outputTex.m_width;
							i_ = outputTex.m_width - 1 - i_;
							k_ = 2;
							s += tmpTex.m_faces[k_].m_buff[i_ + j * outputTex.m_width] * kernel[n + radius];
						}
						else
						{
							s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
						}
					}
				}
				tmpTex2.m_faces[k].m_buff[j + i*outputTex.m_width]  = s;
			}
		}
		resTex.m_faces[k] = tmpTex2.m_faces[k];
	}

	outputTex = resTex;
	outputTex.m_cubemap = true;
}
<|endoftext|>