<commit_before>#include <string>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include "paraverconfig.h"

ParaverConfig *ParaverConfig::instance = NULL;

ParaverConfig *ParaverConfig::getInstance()
{
  if ( ParaverConfig::instance == NULL )
    ParaverConfig::instance = new ParaverConfig();
  return ParaverConfig::instance;
}

ParaverConfig::ParaverConfig() :
    precision( 2 ),
    histoNumColumns( 20 ),
    showUnits( true ),
    thousandSep( true )
{
  loadMap();
}

ParaverConfig::~ParaverConfig()
{
  unLoadMap();
}

UINT32 ParaverConfig::getPrecision() const
{
  return precision;
}

TObjectOrder ParaverConfig::getHistoNumColumns() const
{
  return histoNumColumns;
}

bool ParaverConfig::getShowUnits() const
{
  return showUnits;
}

bool ParaverConfig::getThousandSep() const
{
  return thousandSep;
}

void ParaverConfig::setPrecision( UINT32 prec )
{
  precision = prec;
}

void ParaverConfig::setHistoNumColumns( TObjectOrder columns )
{
  histoNumColumns = columns;
}

void ParaverConfig::setShowUnits( bool units )
{
  showUnits = units;
}

void ParaverConfig::setThousandSep( bool sep )
{
  thousandSep = sep;
}

void ParaverConfig::readParaverConfigFile()
{
  ParaverConfig& config = *ParaverConfig::instance;

  ifstream file;
  string strLine;
  string strTag;
  string strFile;
  string homedir;

#ifdef WIN32
  homedir = getenv( "HOMEDRIVE" );
  homedir.append( getenv( "HOMEPATH" ) );
#else
  homedir = getenv( "HOME" );
#endif
  strFile.append( homedir );
#ifdef WIN32
  strFile.append( "\\paraver\\paraver" );
#else
  strFile.append( "/.paraver/paraver" );
#endif

  file.open( strFile.c_str() );

  if ( !file )
  {
    if ( !ParaverConfig::writeDefaultConfig() )
      return;
    file.open( strFile.c_str() );
  }

  while ( !file.eof() )
  {
    getline( file, strLine );
    if ( strLine.length() == 0 )
      continue;
    else if ( strLine[ 0 ] == '#' || strLine[ 0 ] == '<' )
      continue;

    istringstream auxStream( strLine );
    getline( auxStream, strTag, ' ' );

    map<string, PropertyFunction*>::iterator it =
      config.propertyFunctions.find( strTag );
    if ( it != config.propertyFunctions.end() )
    {
      it->second->parseLine( auxStream, config );
    }
  }
  file.close();
}

bool ParaverConfig::writeDefaultConfig()
{
  ofstream file;
  string strFile;
  string homedir;

#ifdef WIN32
  homedir = getenv( "HOMEDRIVE" );
  homedir.append( getenv( "HOMEPATH" ) );
#else
  homedir = getenv( "HOME" );
#endif
  strFile.append( homedir );
#ifdef WIN32
  strFile.append( "\\paraver\\paraver" );
#else
  strFile.append( "/.paraver/paraver" );
#endif

  file.open( strFile.c_str() );

  if ( !file )
    return false;

  file.close();

  return true;
}

void ParaverConfig::loadMap()
{
  propertyFunctions[ "WhatWhere.num_decimals:" ] = new WWNumDecimals();
  propertyFunctions[ "Analyzer2D.num_columns:" ] = new HistoNumColumns();
  propertyFunctions[ "Analyzer2D.units:" ] = new HistoUnits();
  propertyFunctions[ "Analyzer2D.thousandsep:" ] = new HistoThousanSep();
}

void ParaverConfig::unLoadMap()
{
  for ( map<string, PropertyFunction*>::iterator it = propertyFunctions.begin();
        it != propertyFunctions.end();
        ++it )
    delete ( *it ).second;
}

void WWNumDecimals::parseLine( istringstream& line, ParaverConfig& config )
{
  string strNumDecimals;
  UINT32 precision;

  getline( line, strNumDecimals );
  istringstream streamNumDecimals( strNumDecimals );

  if ( streamNumDecimals >> precision )
    config.setPrecision( precision );
}

void HistoNumColumns::parseLine( istringstream& line, ParaverConfig& config )
{
  string strNumColumns;
  TObjectOrder numColumns;

  getline( line, strNumColumns );
  istringstream streamNumColumns( strNumColumns );

  if ( streamNumColumns >> numColumns )
    config.setHistoNumColumns( numColumns );
}

void HistoUnits::parseLine( istringstream& line, ParaverConfig& config )
{
  string strUnits;

  getline( line, strUnits );

  if ( strUnits.compare( "True" ) == 0 )
    config.setShowUnits( true );
  else
    config.setShowUnits( false );
}

void HistoThousanSep::parseLine( istringstream& line, ParaverConfig& config )
{
  string strSep;

  getline( line, strSep );

  if ( strSep.compare( "True" ) == 0 )
    config.setThousandSep( true );
  else
    config.setThousandSep( false );
}
<commit_msg>*** empty log message ***<commit_after>#include <string>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#ifdef WIN32
  #include <shlobj.h>
#else
  #include <sys/stat.h>
  #include <sys/types.h>
#endif
#include "paraverconfig.h"

ParaverConfig *ParaverConfig::instance = NULL;

ParaverConfig *ParaverConfig::getInstance()
{
  if ( ParaverConfig::instance == NULL )
    ParaverConfig::instance = new ParaverConfig();
  return ParaverConfig::instance;
}

ParaverConfig::ParaverConfig() :
    precision( 2 ),
    histoNumColumns( 20 ),
    showUnits( true ),
    thousandSep( true )
{
  loadMap();
}

ParaverConfig::~ParaverConfig()
{
  unLoadMap();
}

UINT32 ParaverConfig::getPrecision() const
{
  return precision;
}

TObjectOrder ParaverConfig::getHistoNumColumns() const
{
  return histoNumColumns;
}

bool ParaverConfig::getShowUnits() const
{
  return showUnits;
}

bool ParaverConfig::getThousandSep() const
{
  return thousandSep;
}

void ParaverConfig::setPrecision( UINT32 prec )
{
  precision = prec;
}

void ParaverConfig::setHistoNumColumns( TObjectOrder columns )
{
  histoNumColumns = columns;
}

void ParaverConfig::setShowUnits( bool units )
{
  showUnits = units;
}

void ParaverConfig::setThousandSep( bool sep )
{
  thousandSep = sep;
}

void ParaverConfig::readParaverConfigFile()
{
  ParaverConfig& config = *ParaverConfig::instance;

  ifstream file;
  string strLine;
  string strTag;
  string strFile;
  string homedir;

#ifdef WIN32
  homedir = getenv( "HOMEDRIVE" );
  homedir.append( getenv( "HOMEPATH" ) );
#else
  homedir = getenv( "HOME" );
#endif
  strFile.append( homedir );
#ifdef WIN32
  strFile.append( "\\paraver\\paraver" );
#else
  strFile.append( "/.paraver/paraver" );
#endif

  file.open( strFile.c_str() );

  if ( !file )
  {
    file.close();
    if ( !ParaverConfig::writeDefaultConfig() )
      return;
    file.open( strFile.c_str() );
  }

  while ( !file.eof() )
  {
    getline( file, strLine );
    if ( strLine.length() == 0 )
      continue;
    else if ( strLine[ 0 ] == '#' || strLine[ 0 ] == '<' )
      continue;

    istringstream auxStream( strLine );
    getline( auxStream, strTag, ' ' );

    map<string, PropertyFunction*>::iterator it =
      config.propertyFunctions.find( strTag );
    if ( it != config.propertyFunctions.end() )
    {
      it->second->parseLine( auxStream, config );
    }
  }
  file.close();
}

bool ParaverConfig::writeDefaultConfig()
{
  ofstream file;
  string strFile;
  string homedir;

#ifdef WIN32
  homedir = getenv( "HOMEDRIVE" );
  homedir.append( getenv( "HOMEPATH" ) );
#else
  homedir = getenv( "HOME" );
#endif
  strFile.append( homedir );

#ifdef WIN32
  strFile.append( "\\paraver\\paraver" );
  SHCreateDirectoryEx( NULL, homedir + "\\paraver", NULL );
#else
  strFile.append( "/.paraver/paraver" );
  mkdir( ( homedir + "/.paraver" ).c_str(), (mode_t)0700 );
#endif

  file.open( strFile.c_str() );

  if ( !file )
    return false;

  file.close();

  return true;
}

void ParaverConfig::loadMap()
{
  propertyFunctions[ "WhatWhere.num_decimals:" ] = new WWNumDecimals();
  propertyFunctions[ "Analyzer2D.num_columns:" ] = new HistoNumColumns();
  propertyFunctions[ "Analyzer2D.units:" ] = new HistoUnits();
  propertyFunctions[ "Analyzer2D.thousandsep:" ] = new HistoThousanSep();
}

void ParaverConfig::unLoadMap()
{
  for ( map<string, PropertyFunction*>::iterator it = propertyFunctions.begin();
        it != propertyFunctions.end();
        ++it )
    delete ( *it ).second;
}

void WWNumDecimals::parseLine( istringstream& line, ParaverConfig& config )
{
  string strNumDecimals;
  UINT32 precision;

  getline( line, strNumDecimals );
  istringstream streamNumDecimals( strNumDecimals );

  if ( streamNumDecimals >> precision )
    config.setPrecision( precision );
}

void HistoNumColumns::parseLine( istringstream& line, ParaverConfig& config )
{
  string strNumColumns;
  TObjectOrder numColumns;

  getline( line, strNumColumns );
  istringstream streamNumColumns( strNumColumns );

  if ( streamNumColumns >> numColumns )
    config.setHistoNumColumns( numColumns );
}

void HistoUnits::parseLine( istringstream& line, ParaverConfig& config )
{
  string strUnits;

  getline( line, strUnits );

  if ( strUnits.compare( "True" ) == 0 )
    config.setShowUnits( true );
  else
    config.setShowUnits( false );
}

void HistoThousanSep::parseLine( istringstream& line, ParaverConfig& config )
{
  string strSep;

  getline( line, strSep );

  if ( strSep.compare( "True" ) == 0 )
    config.setThousandSep( true );
  else
    config.setThousandSep( false );
}
<|endoftext|>


<commit_before>#include "cpu.h"

void CPU::instruction_decode(bool& exception) {
    switch (main_opcode()) {
        case 0b000000:
            switch (sub_opcode()) {
                // sll
                case 0b000000:
                    return exe_sll();
                // srl
                case 0b000010:
                    return exe_srl();
                // sra
                case 0b000011:
                    return exe_sra();
                // sllv
                case 0b000100:
                    return exe_sllv();
                // srav
                case 0b000110:
                    return exe_srav();
                // srav
                case 0b000111:
                    return exe_srav();
                // jr
                case 0b001000:
                    return exe_jr();
                // jalr
                case 0b001001:
                    return exe_jalr();
                // syscall
                case 0b001100:
                    return exe_syscall();
                // mfhi
                case 0b010000:
                    return exe_mfhi();
                // mthi
                case 0b010001:
                    return exe_mthi();
                // mflo
                case 0b010010:
                    return exe_mflo();
                // mtlo
                case 0b010011:
                    return exe_mtlo();
                // mult
                case 0b011000:
                    return exe_mult();
                // addu
                case 0b100001:
                    return exe_addu();
                // subu
                case 0b100011:
                    return exe_subu();
                // and
                case 0b100100:
                    return exe_and();
                // or
                case 0b100101:
                    return exe_or();
                // xor
                case 0b100110:
                    return exe_xor();
                // nor
                case 0b100111:
                    return exe_nor();
                // slt
                case 0b101010:
                    return exe_slt();
                // sltu
                case 0b101011:
                    return exe_sltu();
                default:
                    cp0_.set_exception_code(cp0_.Exc_RI);
                    exception = true;
                    return;
            }
        case 0b000001:
            switch (rt()) {
                // bltz
                case 0b00000:
                    return exe_bltz();
                // bgez
                case 0b00001:
                    return exe_bgez();
                default:
                    cp0_.set_exception_code(cp0_.Exc_RI);
                    exception = true;
                    return;
            }
        // j
        case 0b000010:
            return exe_j();
        // jal
        case 0b000011:
            return exe_jal();
        // beq
        case 0b000100:
            return exe_beq();
        // bne
        case 0b000101:
            return exe_bne();
        // blez
        case 0b000110:
            return exe_blez();
        // bgtz
        case 0b000111:
            return exe_bgtz();
        // addiu
        case 0b001001:
            return exe_addiu();
        // slti
        case 0b001010:
            return exe_slti();
        // sltiu
        case 0b001011:
            return exe_sltiu();
        // andi
        case 0b001100:
            return exe_andi();
        // ori
        case 0b001101:
            return exe_ori();
        // xori
        case 0b001110:
            return exe_xori();
        // lui
        case 0b001111:
            return exe_lui();
        case 0b010000:
            switch (sub_opcode()) {
                case 0b000000:
                    switch (rs()) {
                        // mfc0
                        case 0b00000:
                            return exe_mfc0();
                        // mtc0
                        case 0b00100:
                            return exe_mtc0();
                        default:
                            cp0_.set_exception_code(cp0_.Exc_RI);
                            exception = true;
                            return;
                    }
                // tlbwi
                case 0b000010:
                    return exe_tlbwi();
                // eret
                case 0b011000:
                    return exe_eret();
                default:
                    cp0_.set_exception_code(cp0_.Exc_RI);
                    exception = true;
                    return;
            }
        // lb
        case 0b100000:
            return exe_lb();
        // lw
        case 0b100011:
            return exe_lw();
        // lbu
        case 0b100100:
            return exe_lbu();
        // lhu
        case 0b100101:
            return exe_lhu();
        // sb
        case 0b101000:
            return exe_sb();
        // sw
        case 0b101011:
            return exe_sw();
        // cache
        case 0b101111:
            return exe_cache();
    }
}
<commit_msg>add check exception : RI<commit_after>#include "cpu.h"

void CPU::instruction_decode(bool& exception) {
    switch (main_opcode()) {
        case 0b000000:
            switch (sub_opcode()) {
                // sll
                case 0b000000:
                    return exe_sll();
                // srl
                case 0b000010:
                    return exe_srl();
                // sra
                case 0b000011:
                    return exe_sra();
                // sllv
                case 0b000100:
                    return exe_sllv();
                // srav
                case 0b000110:
                    return exe_srav();
                // srav
                case 0b000111:
                    return exe_srav();
                // jr
                case 0b001000:
                    return exe_jr();
                // jalr
                case 0b001001:
                    return exe_jalr();
                // syscall
                case 0b001100:
                    return exe_syscall();
                // mfhi
                case 0b010000:
                    return exe_mfhi();
                // mthi
                case 0b010001:
                    return exe_mthi();
                // mflo
                case 0b010010:
                    return exe_mflo();
                // mtlo
                case 0b010011:
                    return exe_mtlo();
                // mult
                case 0b011000:
                    return exe_mult();
                // addu
                case 0b100001:
                    return exe_addu();
                // subu
                case 0b100011:
                    return exe_subu();
                // and
                case 0b100100:
                    return exe_and();
                // or
                case 0b100101:
                    return exe_or();
                // xor
                case 0b100110:
                    return exe_xor();
                // nor
                case 0b100111:
                    return exe_nor();
                // slt
                case 0b101010:
                    return exe_slt();
                // sltu
                case 0b101011:
                    return exe_sltu();
                default:
                    cp0_.set_exception_code(cp0_.Exc_RI);
                    exception = true;
                    return;
            }
        case 0b000001:
            switch (rt()) {
                // bltz
                case 0b00000:
                    return exe_bltz();
                // bgez
                case 0b00001:
                    return exe_bgez();
                default:
                    cp0_.set_exception_code(cp0_.Exc_RI);
                    exception = true;
                    return;
            }
        // j
        case 0b000010:
            return exe_j();
        // jal
        case 0b000011:
            return exe_jal();
        // beq
        case 0b000100:
            return exe_beq();
        // bne
        case 0b000101:
            return exe_bne();
        // blez
        case 0b000110:
            return exe_blez();
        // bgtz
        case 0b000111:
            return exe_bgtz();
        // addiu
        case 0b001001:
            return exe_addiu();
        // slti
        case 0b001010:
            return exe_slti();
        // sltiu
        case 0b001011:
            return exe_sltiu();
        // andi
        case 0b001100:
            return exe_andi();
        // ori
        case 0b001101:
            return exe_ori();
        // xori
        case 0b001110:
            return exe_xori();
        // lui
        case 0b001111:
            return exe_lui();
        case 0b010000:
            switch (sub_opcode()) {
                case 0b000000:
                    switch (rs()) {
                        // mfc0
                        case 0b00000:
                            return exe_mfc0();
                        // mtc0
                        case 0b00100:
                            return exe_mtc0();
                        default:
                            cp0_.set_exception_code(cp0_.Exc_RI);
                            exception = true;
                            return;
                    }
                // tlbwi
                case 0b000010:
                    return exe_tlbwi();
                // eret
                case 0b011000:
                    return exe_eret();
                default:
                    cp0_.set_exception_code(cp0_.Exc_RI);
                    exception = true;
                    return;
            }
        // lb
        case 0b100000:
            return exe_lb();
        // lw
        case 0b100011:
            return exe_lw();
        // lbu
        case 0b100100:
            return exe_lbu();
        // lhu
        case 0b100101:
            return exe_lhu();
        // sb
        case 0b101000:
            return exe_sb();
        // sw
        case 0b101011:
            return exe_sw();
        // cache
        case 0b101111:
            return exe_cache();
        default:
            cp0_.set_exception_code(cp0_.Exc_RI);
            exception = true;
            return;
    }
}
<|endoftext|>


<commit_before>/*
 * DesktopSatelliteWindow.cpp
 *
 * Copyright (C) 2009-18 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "DesktopSatelliteWindow.hpp"

#include <QShortcut>
#include <QWebChannel>

namespace rstudio {
namespace desktop {

SatelliteWindow::SatelliteWindow(MainWindow* pMainWindow, QString name) :
    GwtWindow(false, true, name),
    gwtCallback_(pMainWindow, this),
    close_(CloseStageOpen)
{
   setAttribute(Qt::WA_QuitOnClose, false);
   setAttribute(Qt::WA_DeleteOnClose, true);

   setWindowIcon(QIcon(QString::fromUtf8(":/icons/RStudio.ico")));

   // bind GWT callbacks
   auto* channel = webPage()->webChannel();
   channel->registerObject(QStringLiteral("desktop"), &gwtCallback_);

   // satellites don't have a menu, so connect zoom keyboard shortcuts
   // directly
   // NOTE: CTRL implies META on macOS
   QShortcut* zoomActualSizeShortcut = new QShortcut(Qt::CTRL + Qt::Key_0, this);
   QShortcut* zoomInShortcut = new QShortcut(QKeySequence::ZoomIn, this);
   QShortcut* zoomOutShortcut = new QShortcut(QKeySequence::ZoomOut, this);

   connect(zoomActualSizeShortcut, SIGNAL(activated()), this, SLOT(zoomActualSize()));
   connect(zoomInShortcut, SIGNAL(activated()), this, SLOT(zoomIn()));
   connect(zoomOutShortcut, SIGNAL(activated()), this, SLOT(zoomOut()));
}

void SatelliteWindow::finishLoading(bool ok)
{
   BrowserWindow::finishLoading(ok);

   if (ok)
   {
      avoidMoveCursorIfNecessary();
      connect(webView(), SIGNAL(onCloseWindowShortcut()), this,
              SLOT(onCloseWindowShortcut()));
   }
}

void SatelliteWindow::closeSatellite(QCloseEvent *event)
{
   webPage()->runJavaScript(
      QStringLiteral(
          "if (window.notifyRStudioSatelliteClosing) "
          "   window.notifyRStudioSatelliteClosing();"));
   webView()->event(event);
}

void SatelliteWindow::closeEvent(QCloseEvent *event)
{
   // the source window has special close semantics; if we're not currently
   // closing, then invoke custom close handlers
   if (getName().startsWith(QString::fromUtf8(SOURCE_WINDOW_PREFIX)) &&
       close_ == CloseStageOpen)
   {
      // ignore this event; we need to make sure the window can be
      // closed ourselves
      event->ignore();
      close_ = CloseStagePending;

      webPage()->runJavaScript(
               QStringLiteral("window.rstudioReadyToClose"),
               [&](QVariant qReadyToClose)
      {
         bool readyToClose = qReadyToClose.toBool();
         if (readyToClose)
         {
            // all clear, close the window
            close_ = CloseStageAccepted;
            close();
         }
         else
         {
            // not ready to close, revert close stage and take care of business
            close_ = CloseStageOpen;
            webPage()->runJavaScript(
                     QStringLiteral("window.rstudioCloseSourceWindow()"),
                     [&](QVariant ignored)
            {
               // no work to do here
            });
         }
      });
   }
   else
   {
      // not a  source window, just close it
      closeSatellite(event);
   }
}

void SatelliteWindow::onActivated()
{
   webView()->webPage()->runJavaScript(
            QString::fromUtf8(
               "if (window.notifyRStudioSatelliteReactivated) "
               "   window.notifyRStudioSatelliteReactivated(null);"));
}

} // namespace desktop
} // namespace rstudio
<commit_msg>use preferred zoomIn shortcut for macOS<commit_after>/*
 * DesktopSatelliteWindow.cpp
 *
 * Copyright (C) 2009-18 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "DesktopSatelliteWindow.hpp"

#include <QShortcut>
#include <QWebChannel>

namespace rstudio {
namespace desktop {

SatelliteWindow::SatelliteWindow(MainWindow* pMainWindow, QString name) :
    GwtWindow(false, true, name),
    gwtCallback_(pMainWindow, this),
    close_(CloseStageOpen)
{
   setAttribute(Qt::WA_QuitOnClose, false);
   setAttribute(Qt::WA_DeleteOnClose, true);

   setWindowIcon(QIcon(QString::fromUtf8(":/icons/RStudio.ico")));

   // bind GWT callbacks
   auto* channel = webPage()->webChannel();
   channel->registerObject(QStringLiteral("desktop"), &gwtCallback_);

   // satellites don't have a menu, so connect zoom keyboard shortcuts
   // directly
   // NOTE: CTRL implies META on macOS
   QShortcut* zoomActualSizeShortcut = new QShortcut(Qt::CTRL + Qt::Key_0, this);
#ifdef Q_OS_MAC
   QShortcut* zoomInShortcut = new QShortcut(Qt::CTRL + Qt::Key_Equal, this);
#else
   QShortcut* zoomInShortcut = new QShortcut(QKeySequence::ZoomIn, this);
#endif

   QShortcut* zoomOutShortcut = new QShortcut(QKeySequence::ZoomOut, this);

   connect(zoomActualSizeShortcut, SIGNAL(activated()), this, SLOT(zoomActualSize()));
   connect(zoomInShortcut, SIGNAL(activated()), this, SLOT(zoomIn()));
   connect(zoomOutShortcut, SIGNAL(activated()), this, SLOT(zoomOut()));
}

void SatelliteWindow::finishLoading(bool ok)
{
   BrowserWindow::finishLoading(ok);

   if (ok)
   {
      avoidMoveCursorIfNecessary();
      connect(webView(), SIGNAL(onCloseWindowShortcut()), this,
              SLOT(onCloseWindowShortcut()));
   }
}

void SatelliteWindow::closeSatellite(QCloseEvent *event)
{
   webPage()->runJavaScript(
      QStringLiteral(
          "if (window.notifyRStudioSatelliteClosing) "
          "   window.notifyRStudioSatelliteClosing();"));
   webView()->event(event);
}

void SatelliteWindow::closeEvent(QCloseEvent *event)
{
   // the source window has special close semantics; if we're not currently
   // closing, then invoke custom close handlers
   if (getName().startsWith(QString::fromUtf8(SOURCE_WINDOW_PREFIX)) &&
       close_ == CloseStageOpen)
   {
      // ignore this event; we need to make sure the window can be
      // closed ourselves
      event->ignore();
      close_ = CloseStagePending;

      webPage()->runJavaScript(
               QStringLiteral("window.rstudioReadyToClose"),
               [&](QVariant qReadyToClose)
      {
         bool readyToClose = qReadyToClose.toBool();
         if (readyToClose)
         {
            // all clear, close the window
            close_ = CloseStageAccepted;
            close();
         }
         else
         {
            // not ready to close, revert close stage and take care of business
            close_ = CloseStageOpen;
            webPage()->runJavaScript(
                     QStringLiteral("window.rstudioCloseSourceWindow()"),
                     [&](QVariant ignored)
            {
               // no work to do here
            });
         }
      });
   }
   else
   {
      // not a  source window, just close it
      closeSatellite(event);
   }
}

void SatelliteWindow::onActivated()
{
   webView()->webPage()->runJavaScript(
            QString::fromUtf8(
               "if (window.notifyRStudioSatelliteReactivated) "
               "   window.notifyRStudioSatelliteReactivated(null);"));
}

} // namespace desktop
} // namespace rstudio
<|endoftext|>


<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/xla/client/lib/comparators.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"

namespace tensorflow {
namespace {

// TODO: This is only a dummy kernel
class DenseBincountOp : public XlaOpKernel {
 public:
  explicit DenseBincountOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
    DataType dtype;
  }

  void Compile(XlaOpKernelContext* ctx) override {
  // Dumb implementation for the simplest test case
    xla::XlaOp input = ctx->Input(0);
    int64_t output_size;
    ctx->ConstantInputAsIntScalar("size",&output_size);
    StatusOr<xla::Shape> input_shape_or = ctx->builder()->GetShape(input);
    OP_REQUIRES_OK(ctx, input_shape_or.status());
    auto input_shape = input_shape_or.ValueOrDie();
    int64_t size = input_shape.dimensions(0);
    auto counter_shape = xla::ShapeUtil::MakeShape(xla::S32, {});
    const xla::Shape data_shape = xla::ShapeUtil::MakeShape(xla::S32, {size});

    const xla::Shape output_shape = xla::ShapeUtil::MakeShape(xla::S32, {output_size});

    auto loop_shape = xla::ShapeUtil::MakeTupleShape(
        {counter_shape, data_shape, output_shape});

    // Create a computation for the condition
    xla::XlaComputation condition;
    {
      std::unique_ptr<xla::XlaBuilder> builder =
          ctx->builder()->CreateSubBuilder("condition");
      auto param = xla::Parameter(builder.get(), 0, loop_shape, "param");
      auto counter = xla::GetTupleElement(param, 0);
      xla::Gt(xla::ConstantR0<int32_t>(builder.get(), size), counter);
      condition = builder->Build().ConsumeValueOrDie();
    }

    // Create a computation for the body
    xla::XlaComputation body;
    {
      std::unique_ptr<xla::XlaBuilder> builder =
          ctx->builder()->CreateSubBuilder("body");
      auto param = Parameter(builder.get(), 0, loop_shape, "param");
      auto counter = xla::GetTupleElement(param, 0);
      auto data_stack = xla::GetTupleElement(param, 1);
      auto accum_stack = xla::GetTupleElement(param, 2);
      auto data = xla::DynamicSlice(data_stack, {counter}, {1});
      auto accum = xla::DynamicSlice(accum_stack, {data}, {1});
      accum = accum + xla::One(builder.get(), xla::S32);
      accum_stack = xla::DynamicUpdateSlice(
          accum_stack, xla::Reshape(accum, {1}), {data});
      counter = counter + xla::One(builder.get(), xla::S32);
      xla::Tuple(builder.get(), {counter, data_stack, accum_stack});
      body = builder->Build().ConsumeValueOrDie();
    }
    // Create a While node with computations for the condition and the body.
    auto zero = xla::Zero(ctx->builder(), xla::S32);
    auto zero_broadcast = xla::Broadcast(zero, {output_size});
    auto init = xla::Tuple(ctx->builder(), {zero, input, zero_broadcast});
    auto result = xla::While(condition, body, init);
    auto output = xla::GetTupleElement(result,2);
    ctx->SetOutput(0, output);
  }
};

REGISTER_XLA_OP(Name("DenseBincount").CompileTimeConstantInput("size"), DenseBincountOp);

}  // namespace
}  // namespace tensorflow
<commit_msg>Add rank2 code<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/xla/client/lib/comparators.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"

namespace tensorflow {
namespace {

// TODO: This is only a dummy kernel
class DenseBincountOp : public XlaOpKernel {
 public:
  explicit DenseBincountOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
    DataType dtype;
  }

  void Compile(XlaOpKernelContext* ctx) override {
  // Dumb implementation for the simplest test case
    xla::XlaOp input = ctx->Input(0);
    int64_t output_size;
    ctx->ConstantInputAsIntScalar("size", &output_size);
    StatusOr<xla::Shape> input_shape_or = ctx->builder()->GetShape(input);
    OP_REQUIRES_OK(ctx, input_shape_or.status());
    auto input_shape = input_shape_or.ValueOrDie();
    auto size = input_shape.dimensions(0);
    auto dim = 1;
    auto rank = input_shape.rank();
    auto counter_shape = xla::ShapeUtil::MakeShape(xla::S32, {});
    const xla::Shape data_shape = xla::ShapeUtil::MakeShape(xla::S32, {input_shape.dimensions()});

    xla::Shape output_shape = xla::ShapeUtil::MakeShape(xla::S32, {output_size});
    if (rank == 2) {
      output_shape = xla::ShapeUtil::MakeShape(xla::S32, {rank, output_size});
      dim = input_shape.dimensions(1);
    }

    auto loop_shape = xla::ShapeUtil::MakeTupleShape(
        {counter_shape, data_shape, output_shape});

    // Create a computation for the condition
    xla::XlaComputation condition;
    {
      std::unique_ptr<xla::XlaBuilder> builder =
          ctx->builder()->CreateSubBuilder("condition");
      auto param = xla::Parameter(builder.get(), 0, loop_shape, "param");
      auto counter = xla::GetTupleElement(param, 0);
      xla::Gt(xla::ConstantR0<int32_t>(builder.get(), size*dim), counter);
      condition = builder->Build().ConsumeValueOrDie();
    }

    // Create a computation for the body
    xla::XlaComputation body;
    {
      std::unique_ptr<xla::XlaBuilder> builder =
      ctx->builder()->CreateSubBuilder("body");
      auto param = Parameter(builder.get(), 0, loop_shape, "param");
      auto counter = xla::GetTupleElement(param, 0);
      auto data_stack = xla::GetTupleElement(param, 1);
      auto accum_stack = xla::GetTupleElement(param, 2);
    if (rank == 1) {
      auto data = xla::DynamicSlice(data_stack, {counter}, {1});
      auto accum = xla::DynamicSlice(accum_stack, {data}, {1});
      accum = accum + xla::One(builder.get(), xla::S32);
      accum_stack = xla::DynamicUpdateSlice(
          accum_stack, xla::Reshape(accum, {1}), {data});
    }
    else {
      auto dim_xla = xla::ConstantR0<int32_t>(builder.get(), dim);
      auto idx_1 = xla::Div(counter, dim_xla);
      auto idx_2 = counter % dim_xla;
      auto data = xla::DynamicSlice(data_stack, {idx_1, idx_2}, {1, 1});
      auto data_scalar = xla::Reshape(data, {0,1}, {});
      auto accum = xla::DynamicSlice(accum_stack, {idx_1, data_scalar}, {1, 1});
      accum = accum + xla::One(builder.get(), xla::S32);
      accum_stack = xla::DynamicUpdateSlice(
          accum_stack, xla::Reshape(accum, {1, 1}), {idx_1, data_scalar});
    }
      counter = counter + xla::One(builder.get(), xla::S32);
      xla::Tuple(builder.get(), {counter, data_stack, accum_stack});
      body = builder->Build().ConsumeValueOrDie();
    }

    // Create a While node with computations for the condition and the body.
    auto zero = xla::Zero(ctx->builder(), xla::S32);
    auto zero_broadcast = xla::Broadcast(zero, {output_shape.dimensions()});
    auto init = xla::Tuple(ctx->builder(), {zero, input, zero_broadcast});
    auto result = xla::While(condition, body, init);
    auto output = xla::GetTupleElement(result,2);
    ctx->SetOutput(0, output);
  }
};

REGISTER_XLA_OP(Name("DenseBincount").CompileTimeConstantInput("size"), DenseBincountOp);

}  // namespace
}  // namespace tensorflow
<|endoftext|>


<commit_before>// Copyright © 2017-2018 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.08.16

// Sink.cpp

#include <stdexcept>
#include "Sink.hpp"
#include "Log.hpp"
#include "../utils/Time.hpp"
#include "../thread/Thread.hpp"
#include <sstream>
#include <mutex>
#include <cstring>
#include <cstdarg>
#include <algorithm>

Sink::Sink(const Setting& setting)
{
	_f = nullptr;

	if (!setting.lookupValue("name", _name))
	{
		throw std::runtime_error("Not found name for one of sinks");
	}

	std::string type;
	if (!setting.lookupValue("type", type))
	{
		throw std::runtime_error("Undefined type for sink '" + _name + "'");
	}
	if (type == "console")
	{
		_type = Type::CONSOLE;
	}
	else if (type == "file")
	{
		_type = Type::FILE;
	}
	else if (type == "null")
	{
		_type = Type::BLACKHOLE;
	}
	else
	{
		throw std::runtime_error("Unknown type ('" + type + "') for sink '" + _name + "'");
	}

	if (_type == Type::FILE)
	{
		std::string directory;
		if (!setting.lookupValue("directory", directory))
		{
			throw std::runtime_error("Undefined directory for sink '" + _name + "'");
		}
		if (directory.empty() || directory[0] != '/')
		{
			throw std::runtime_error("Invalid directory for sink '" + _name + "': path must be absolute");
		}

		std::string filename;
		if (!setting.lookupValue("filename", filename))
		{
			throw std::runtime_error("Undefined filename for sink '" + _name + "'");
		}
		if (filename.empty() || std::find_if(filename.begin(), filename.end(), [](const auto& s){ return s == '/'; }) != filename.end())
		{
			throw std::runtime_error("Invalid filename for sink '" + _name + "'");
		}

		_path = directory + "/" + filename;
		_f = fopen(_path.c_str(), "a+");

		if (_f == nullptr)
		{
			throw std::runtime_error("Can't open log-file (" + _path + "): " + strerror(errno));
		}
	}
	else if (_type == Type::CONSOLE)
	{
		_f = stdout;
	}
}

Sink::Sink()
{
	_type = Type::BLACKHOLE;
}

Sink::~Sink()
{
	if (_type == Type::FILE)
	{
		if (_f)
		{
			fclose(_f);
			_f = nullptr;
		}
	}
}

void Sink::push(Log::Detail logLevel, const std::string& name, const std::string& message)
{
	char buff[1<<6]; // 64

	time_t ts;
	struct tm tm;

	auto now = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
	ts = now / 1'000'000;
	auto ms = static_cast<uint32_t>(now % 1'000'000 / 1000);
	auto mcs = static_cast<uint32_t>(now % 1'000);

	localtime_r(&ts, &tm);

	const char* threadLabel = Thread::self()->name().c_str();

	static const char *levelLabel[] = {
		"TRC",
		"DEB",
		"INF",
		"WRN",
		"ERR",
		"CRT"
	};

	int n = 0;

	n = snprintf(buff, sizeof(buff),
		"%02u-%02u-%02u %02u:%02u:%02u.%03u'%03u\t%s\t%s\t%s\t",
		tm.tm_year%100, tm.tm_mon+1, tm.tm_mday,
		tm.tm_hour, tm.tm_min, tm.tm_sec,
		ms, mcs,
		threadLabel, name.c_str(), levelLabel[static_cast<int>(logLevel)]
	);

	if (_f == nullptr)
	{
		std::lock_guard<std::recursive_mutex> lockGuard(_mutex);
		_preInitBuff += buff + message + "\n";
	}
	else
	{
#ifdef	PRE_ACCUMULATE_LOG
		_mutex.lock();
		if ((_accum.length() + n + message.length() + 1) > (1<<14))
		{
			_mutex.unlock();
			flush();
			_mutex.lock();
		}
		_accum.append(buff);
		_accum.append(message);
		_accum.append("\n");
		_mutex.unlock();
#else
		std::lock_guard<std::recursive_mutex> lockGuard(_mutex);
		fwrite(buff, n, 1, _f);
		fwrite(message.data(), message.size(), 1, _f);
		fputc('\n', _f);
		fflush(_f);
#endif
	}
}

void Sink::push(Log::Detail level, const std::string& name, const std::string& format, va_list ap)
{
	time_t ts;
	struct tm tm;

	auto now = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
	ts = now / 1'000'000;
	auto ms = static_cast<uint32_t>(now % 1'000'000 / 1000);
	auto mcs = static_cast<uint32_t>(now % 1'000);

	localtime_r(&ts, &tm);

	const char* threadLabel = Thread::self()->name().c_str();

	static const char *levelLabel[] = {
		"TRC",
		"DEB",
		"INF",
		"WRN",
		"ERR",
		"CRT"
	};

	if (_f == nullptr)
	{
		char buff[1<<6]; // 64

		snprintf(buff, sizeof(buff),
			 "%02u-%02u-%02u %02u:%02u:%02u.%03u'%03u\t%s\t%s\t%s\t",
			 tm.tm_year%100, tm.tm_mon+1, tm.tm_mday,
			 tm.tm_hour, tm.tm_min, tm.tm_sec,
			 ms, mcs,
			 threadLabel, name.c_str(), levelLabel[static_cast<int>(level)]
		);

		int size = ((int)format.size()) * 2 + 50;   // Use a rubric appropriate for your code
		std::string message;
		while (1) // Maximum two passes on a POSIX system...
		{
			message.resize(size);
			va_list ap1;
			va_copy(ap1, ap);
			int n = vsnprintf((char *)message.data(), size, format.c_str(), ap1);
			va_end(ap1);
			if (n > -1 && n < size)
			{  // Everything worked
				message.resize(n);
				break;
			}
			if (n > -1)  // Needed size returned
			{
				size = n + 1;   // For null char
			}
			else
			{
				size *= 2;      // Guess at a larger size (OS specific)
			}
		}

		std::lock_guard<std::recursive_mutex> lockGuard(_mutex);

		_preInitBuff += buff + message + "\n";
	}
	else
	{
#ifdef	PRE_ACCUMULATE_LOG
		char buff[1<<6]; // 64

		int n = snprintf(buff, sizeof(buff),
				 "%02u-%02u-%02u %02u:%02u:%02u.%03u'%03u\t%s\t%s\t%s\t",
				 tm.tm_year%100, tm.tm_mon+1, tm.tm_mday,
				 tm.tm_hour, tm.tm_min, tm.tm_sec,
				 ms, mcs,
				 threadLabel, name.c_str(), levelLabel[static_cast<int>(level)]
		);

		int size = ((int)format.size()) * 2 + 64;
		std::string message;
		for (;;) // Maximum two passes on a POSIX system...
		{
			message.resize(size);
			va_list ap1;
			va_copy(ap1, ap);
			int n = vsnprintf((char *)message.data(), size, format.c_str(), ap1);
			va_end(ap1);
			if (n > -1 && n < size)
			{  // Everything worked
				message.resize(n);
				break;
			}
			if (n > -1)  // Needed size returned
			{
				size = n + 1;   // For null char
			}
			else
			{
				size *= 2;      // Guess at a larger size (OS specific)
			}
		}

		std::lock_guard<std::recursive_mutex> lockGuard(_mutex);
		if ((_accum.length() + n + message.length() + 1) > (1<<14))
		{
			_mutex.unlock();
			flush();
			_mutex.lock();
		}
		_accum.append(buff);
		_accum.append(message);
		_accum.append("\n");

		if (!_flushTimeout)
		{
			_flushTimeout = std::make_shared<Timeout>(
				[wp = std::weak_ptr<Sink>(std::dynamic_pointer_cast<Sink>(ptr()))]
				{
					auto iam = wp.lock();
					if (!iam) return;
					try
					{
						iam->flush();
						iam->_flushTimeout->startOnce(std::chrono::milliseconds(250));
					} catch (...) {}
				},
				"Timeout to flush sink"
			);
		}

		_flushTimeout->startOnce(std::chrono::milliseconds(250));
#else
		std::lock_guard<std::recursive_mutex> lockGuard(_mutex);
		fprintf(_f, "%02u-%02u-%02u %02u:%02u:%02u.%03u'%03u\t%s\t%s\t%s\t",
			tm.tm_year%100, tm.tm_mon+1, tm.tm_mday,
			tm.tm_hour, tm.tm_min, tm.tm_sec,
			ms, mcs,
			threadLabel, name.c_str(), levelLabel[static_cast<int>(level)]
		);
		vfprintf(_f, format.c_str(), ap);
		fputc('\n', _f);
		fflush(_f);
#endif
	}
}

// Принудительно сбросить на диск
void Sink::flush()
{
	std::lock_guard<std::recursive_mutex> lockGuard(_mutex);

#ifdef	PRE_ACCUMULATE_LOG
	if (_accum.empty())
	{
		return;
	}
#endif

	if (_f == nullptr)
	{
		return;
	}

#ifdef	PRE_ACCUMULATE_LOG
	std::string chunk = std::move(_accum);

	fwrite(chunk.data(), chunk.size(), 1, _f);
#endif

	fflush(_f);
}

void Sink::rotate()
{
	if (_type == Type::FILE)
	{
		push(Log::Detail::INFO, "Logger", "Close logfile for rotation");

		std::lock_guard<std::recursive_mutex> lockGuard(_mutex);

		auto f = fopen(_path.c_str(), "a+");
		if (f == nullptr)
		{
			throw std::runtime_error("Can't reopen log-file (" + _path + "): " + strerror(errno));
		}

		push(Log::Detail::INFO, "Logger", "Reopen logfile for rotation");

		if (_f != nullptr)
		{
			fflush(_f);
			fclose(_f);
		}

		_f = f;
	}
}
<commit_msg>Fix dealock in logger sink<commit_after>// Copyright © 2017-2018 Dmitriy Khaustov
//
// 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.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.08.16

// Sink.cpp

#include <stdexcept>
#include "Sink.hpp"
#include "Log.hpp"
#include "../utils/Time.hpp"
#include "../thread/Thread.hpp"
#include <sstream>
#include <mutex>
#include <cstring>
#include <cstdarg>
#include <algorithm>

Sink::Sink(const Setting& setting)
{
	_f = nullptr;

	if (!setting.lookupValue("name", _name))
	{
		throw std::runtime_error("Not found name for one of sinks");
	}

	std::string type;
	if (!setting.lookupValue("type", type))
	{
		throw std::runtime_error("Undefined type for sink '" + _name + "'");
	}
	if (type == "console")
	{
		_type = Type::CONSOLE;
	}
	else if (type == "file")
	{
		_type = Type::FILE;
	}
	else if (type == "null")
	{
		_type = Type::BLACKHOLE;
	}
	else
	{
		throw std::runtime_error("Unknown type ('" + type + "') for sink '" + _name + "'");
	}

	if (_type == Type::FILE)
	{
		std::string directory;
		if (!setting.lookupValue("directory", directory))
		{
			throw std::runtime_error("Undefined directory for sink '" + _name + "'");
		}
		if (directory.empty() || directory[0] != '/')
		{
			throw std::runtime_error("Invalid directory for sink '" + _name + "': path must be absolute");
		}

		std::string filename;
		if (!setting.lookupValue("filename", filename))
		{
			throw std::runtime_error("Undefined filename for sink '" + _name + "'");
		}
		if (filename.empty() || std::find_if(filename.begin(), filename.end(), [](const auto& s){ return s == '/'; }) != filename.end())
		{
			throw std::runtime_error("Invalid filename for sink '" + _name + "'");
		}

		_path = directory + "/" + filename;
		_f = fopen(_path.c_str(), "a+");

		if (_f == nullptr)
		{
			throw std::runtime_error("Can't open log-file (" + _path + "): " + strerror(errno));
		}
	}
	else if (_type == Type::CONSOLE)
	{
		_f = stdout;
	}
}

Sink::Sink()
{
	_type = Type::BLACKHOLE;
}

Sink::~Sink()
{
	if (_type == Type::FILE)
	{
		if (_f)
		{
			fclose(_f);
			_f = nullptr;
		}
	}
}

void Sink::push(Log::Detail logLevel, const std::string& name, const std::string& message)
{
	char buff[1<<6]; // 64

	time_t ts;
	struct tm tm;

	auto now = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
	ts = now / 1'000'000;
	auto ms = static_cast<uint32_t>(now % 1'000'000 / 1000);
	auto mcs = static_cast<uint32_t>(now % 1'000);

	localtime_r(&ts, &tm);

	const char* threadLabel = Thread::self()->name().c_str();

	static const char *levelLabel[] = {
		"TRC",
		"DEB",
		"INF",
		"WRN",
		"ERR",
		"CRT"
	};

	int n = 0;

	n = snprintf(buff, sizeof(buff),
		"%02u-%02u-%02u %02u:%02u:%02u.%03u'%03u\t%s\t%s\t%s\t",
		tm.tm_year%100, tm.tm_mon+1, tm.tm_mday,
		tm.tm_hour, tm.tm_min, tm.tm_sec,
		ms, mcs,
		threadLabel, name.c_str(), levelLabel[static_cast<int>(logLevel)]
	);

	if (_f == nullptr)
	{
		std::lock_guard<std::recursive_mutex> lockGuard(_mutex);
		_preInitBuff += buff + message + "\n";
	}
	else
	{
#ifdef	PRE_ACCUMULATE_LOG
		_mutex.lock();
		if ((_accum.length() + n + message.length() + 1) > (1<<14))
		{
			_mutex.unlock();
			flush();
			_mutex.lock();
		}
		_accum.append(buff);
		_accum.append(message);
		_accum.append("\n");
		_mutex.unlock();
#else
		std::lock_guard<std::recursive_mutex> lockGuard(_mutex);
		fwrite(buff, n, 1, _f);
		fwrite(message.data(), message.size(), 1, _f);
		fputc('\n', _f);
		fflush(_f);
#endif
	}
}

void Sink::push(Log::Detail level, const std::string& name, const std::string& format, va_list ap)
{
	time_t ts;
	struct tm tm;

	auto now = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
	ts = now / 1'000'000;
	auto ms = static_cast<uint32_t>(now % 1'000'000 / 1000);
	auto mcs = static_cast<uint32_t>(now % 1'000);

	localtime_r(&ts, &tm);

	const char* threadLabel = Thread::self()->name().c_str();

	static const char *levelLabel[] = {
		"TRC",
		"DEB",
		"INF",
		"WRN",
		"ERR",
		"CRT"
	};

	if (_f == nullptr)
	{
		char buff[1<<6]; // 64

		snprintf(buff, sizeof(buff),
			 "%02u-%02u-%02u %02u:%02u:%02u.%03u'%03u\t%s\t%s\t%s\t",
			 tm.tm_year%100, tm.tm_mon+1, tm.tm_mday,
			 tm.tm_hour, tm.tm_min, tm.tm_sec,
			 ms, mcs,
			 threadLabel, name.c_str(), levelLabel[static_cast<int>(level)]
		);

		int size = ((int)format.size()) * 2 + 50;   // Use a rubric appropriate for your code
		std::string message;
		while (1) // Maximum two passes on a POSIX system...
		{
			message.resize(size);
			va_list ap1;
			va_copy(ap1, ap);
			int n = vsnprintf((char *)message.data(), size, format.c_str(), ap1);
			va_end(ap1);
			if (n > -1 && n < size)
			{  // Everything worked
				message.resize(n);
				break;
			}
			if (n > -1)  // Needed size returned
			{
				size = n + 1;   // For null char
			}
			else
			{
				size *= 2;      // Guess at a larger size (OS specific)
			}
		}

		std::lock_guard<std::recursive_mutex> lockGuard(_mutex);

		_preInitBuff += buff + message + "\n";
	}
	else
	{
#ifdef	PRE_ACCUMULATE_LOG
		char buff[1<<6]; // 64

		int n = snprintf(buff, sizeof(buff),
				 "%02u-%02u-%02u %02u:%02u:%02u.%03u'%03u\t%s\t%s\t%s\t",
				 tm.tm_year%100, tm.tm_mon+1, tm.tm_mday,
				 tm.tm_hour, tm.tm_min, tm.tm_sec,
				 ms, mcs,
				 threadLabel, name.c_str(), levelLabel[static_cast<int>(level)]
		);

		int size = ((int)format.size()) * 2 + 64;
		std::string message;
		for (;;) // Maximum two passes on a POSIX system...
		{
			message.resize(size);
			va_list ap1;
			va_copy(ap1, ap);
			int n = vsnprintf((char *)message.data(), size, format.c_str(), ap1);
			va_end(ap1);
			if (n > -1 && n < size)
			{  // Everything worked
				message.resize(n);
				break;
			}
			if (n > -1)  // Needed size returned
			{
				size = n + 1;   // For null char
			}
			else
			{
				size *= 2;      // Guess at a larger size (OS specific)
			}
		}

		{
			std::lock_guard<std::recursive_mutex> lockGuard(_mutex);

			if ((_accum.length() + n + message.length() + 1) > (1<<14))
			{
				_mutex.unlock();
				flush();
				_mutex.lock();
			}
			_accum.append(buff);
			_accum.append(message);
			_accum.append("\n");

			if (!_flushTimeout)
			{
				_flushTimeout = std::make_shared<Timeout>(
					[wp = std::weak_ptr<Sink>(std::dynamic_pointer_cast<Sink>(ptr()))]
					{
						auto iam = wp.lock();
						if (!iam) return;
						try
						{
							iam->flush();
							iam->_flushTimeout->startOnce(std::chrono::milliseconds(250));
						} catch (...) {}
					},
					"Timeout to flush sink"
				);
			}
		}

		_flushTimeout->startOnce(std::chrono::milliseconds(250));
#else
		std::lock_guard<std::recursive_mutex> lockGuard(_mutex);
		fprintf(_f, "%02u-%02u-%02u %02u:%02u:%02u.%03u'%03u\t%s\t%s\t%s\t",
			tm.tm_year%100, tm.tm_mon+1, tm.tm_mday,
			tm.tm_hour, tm.tm_min, tm.tm_sec,
			ms, mcs,
			threadLabel, name.c_str(), levelLabel[static_cast<int>(level)]
		);
		vfprintf(_f, format.c_str(), ap);
		fputc('\n', _f);
		fflush(_f);
#endif
	}
}

// Принудительно сбросить на диск
void Sink::flush()
{
	std::lock_guard<std::recursive_mutex> lockGuard(_mutex);

#ifdef	PRE_ACCUMULATE_LOG
	if (_accum.empty())
	{
		return;
	}
#endif

	if (_f == nullptr)
	{
		return;
	}

#ifdef	PRE_ACCUMULATE_LOG
	std::string chunk = std::move(_accum);

	fwrite(chunk.data(), chunk.size(), 1, _f);
#endif

	fflush(_f);
}

void Sink::rotate()
{
	if (_type == Type::FILE)
	{
		push(Log::Detail::INFO, "Logger", "Close logfile for rotation");

		std::lock_guard<std::recursive_mutex> lockGuard(_mutex);

		auto f = fopen(_path.c_str(), "a+");
		if (f == nullptr)
		{
			throw std::runtime_error("Can't reopen log-file (" + _path + "): " + strerror(errno));
		}

		push(Log::Detail::INFO, "Logger", "Reopen logfile for rotation");

		if (_f != nullptr)
		{
			fflush(_f);
			fclose(_f);
		}

		_f = f;
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright © 2014, United States Government, as represented by the
 * Administrator of the National Aeronautics and Space Administration.
 * All rights reserved.
 *
 * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

/**
 * @file Escape_T6Model.cpp
 * @brief Contains the implementation of class Escape_T6Model.
 * $Id$
 */

// This module
#include "Escape_T6Model.h"
// This library
#include "core/tgLinearString.h"
#include "core/tgRod.h"
#include "tgcreator/tgBuildSpec.h"
#include "tgcreator/tgLinearStringInfo.h"
#include "tgcreator/tgRodInfo.h"
#include "tgcreator/tgStructure.h"
#include "tgcreator/tgStructureInfo.h"
// The Bullet Physics library
#include "LinearMath/btVector3.h"
// The C++ Standard Library
#include <stdexcept>

namespace
{
    // see tgBaseString.h for a descripton of some of these rod parameters
    // (specifically, those related to the motor moving the strings.)
    // NOTE that any parameter that depends on units of length will scale
    // with the current gravity scaling. E.g., with gravity as 98.1,
    // the length units below are in decimeters.

    // Note: This current model of the SUPERball rod is 1.5m long by 3 cm radius,
    // which is 0.00424 m^3.
    // For SUPERball v1.5, mass = 3.5kg per strut, which comes out to
    // 0.825 kg / (decimeter^3).

    // similarly, frictional parameters are for the tgRod objects.
    const struct Config
    {
        double density;
        double radius;
        double stiffness;
        double damping;
        double rod_length;
        double rod_space;
        double friction;
        double rollFriction;
        double restitution;
        double rotation;
        double maxTens;
        double targetVelocity;
        double maxAcc;
    } c =
    {
        0.825,    // density (kg / length^3)
        0.31,     // radius (length)
        3000.0,   // stiffness (kg / sec^2)
        200.0,    // damping (kg / sec)
        15.0,     // rod_length (length)
        7.5,      // rod_space (length)
        1.0,      // friction (unitless)
        0.01,     // rollFriction (unitless)
        0.2,      // restitution (?)
        0,        // rotation
        100000,   // maxTens
        10000,    // targetVelocity
        20000     // maxAcc

            // Use the below values for earlier versions of simulation.
            // 1.006,
            // 0.31,
            // 300000.0,
            // 3000.0,
            // 15.0,
            // 7.5,
    };
} // namespace

/*
 * helper arrays for node and rod numbering schema
 */
/*returns the number of the rod for a given node */
const int rodNumbersPerNode[13]={0,1,2,3,3,4,0,1,2,5,5,4,6};

/*returns the node that is at the other end of the given node */
const int otherEndOfTheRod[13]={6,7,8,4,3,11,0,1,2,10,9,5,12};

/*returns the node that is at the parallel rod
 * and at the same end of the given node
 */
const int parallelNode[13]={1,0,5,9,10,2,7,6,11,3,4,8,12};

Escape_T6Model::Escape_T6Model() : tgModel()
{
}

Escape_T6Model::~Escape_T6Model()
{
}

//Node numbers seen from Front
// -----0-------1------
// ---------2----------
// 3------------------4
// ---------5----------
// -----6-------7------
//
//Node numbers seen from Back
// -----0-------1------
// ---------8----------
// 9-----------------10
// ---------11---------
// -----6-------7------
//

void Escape_T6Model::addNodes(tgStructure& s)
{
    const double half_length = c.rod_length / 2;

    nodePositions.push_back(btVector3(-half_length, c.rod_space, 0));            // 0
    nodePositions.push_back(btVector3( half_length, c.rod_space, 0));            // 1
    nodePositions.push_back(btVector3(0,            half_length, -c.rod_space)); // 2
    nodePositions.push_back(btVector3(-c.rod_space, 0,           -half_length)); // 3
    nodePositions.push_back(btVector3( c.rod_space, 0,           -half_length)); // 4
    nodePositions.push_back(btVector3(0,            -half_length, -c.rod_space));// 5
    nodePositions.push_back(btVector3(-half_length, -c.rod_space, 0));           // 6
    nodePositions.push_back(btVector3( half_length, -c.rod_space, 0));           // 7
    nodePositions.push_back(btVector3(0,            half_length,  c.rod_space)); // 8
    nodePositions.push_back(btVector3(-c.rod_space, 0,            half_length)); // 9
    nodePositions.push_back(btVector3( c.rod_space, 0,            half_length)); // 10
    nodePositions.push_back(btVector3(0,            -half_length, c.rod_space)); // 11

    for(int i=0;i<12;i++)
    {
        s.addNode(nodePositions[i][0],nodePositions[i][1],nodePositions[i][2]);
    }
}

void Escape_T6Model::addRods(tgStructure& s)
{
    s.addPair( 0,  6, "r1 rod");
    s.addPair( 1,  7, "r2 rod");
    s.addPair( 2,  8, "r3 rod");
    s.addPair( 3,  4, "r4 rod");
    s.addPair( 5, 11, "r5 rod");
    s.addPair( 9, 10, "r6 rod");
}

void Escape_T6Model::addMarkers(tgStructure &s)
{
    std::vector<tgRod *> rods=find<tgRod>("rod");

    for(int i=0;i<12;i++)
    {
        const btRigidBody* bt = rods[rodNumbersPerNode[i]]->getPRigidBody();
        btTransform inverseTransform = bt->getWorldTransform().inverse();
        btVector3 pos = inverseTransform * (nodePositions[i]);
        abstractMarker tmp=abstractMarker(bt,pos,btVector3(0.08*i,1.0 - 0.08*i,.0),i);
        this->addMarker(tmp);
    }
}

/**
 * Defines muscles in the structure by their end nodes
 * as well as the cluster to which they belong
 * A cluster is any three muscles that form a triangle (with nodes as vertices)
 */
void Escape_T6Model::addMuscles(tgStructure& s)
{
    // Cluster 1
    s.addPair(0, 3, "muscle cluster1");
    s.addPair(3, 2, "muscle cluster1");
    s.addPair(2, 0, "muscle cluster1");

    // Cluster 2
    s.addPair(4, 5, "muscle cluster2");
    s.addPair(5, 7, "muscle cluster2");
    s.addPair(7, 4, "muscle cluster2");

    // Cluster 3
    s.addPair(1, 8, "muscle cluster3");
    s.addPair(8, 10, "muscle cluster3");
    s.addPair(10, 1, "muscle cluster3");

    //Cluster 4
    s.addPair(9, 11, "muscle cluster4");
    s.addPair(11, 6, "muscle cluster4");
    s.addPair(6, 9, "muscle cluster4");

    // Cluster 5
    s.addPair(1, 2, "muscle cluster5");
    s.addPair(2, 4, "muscle cluster5");
    s.addPair(4, 1, "muscle cluster5");

    // Cluster 6
    s.addPair(3, 5, "muscle cluster6");
    s.addPair(5, 6, "muscle cluster6");
    s.addPair(6, 3, "muscle cluster6");

    // Cluster 7
    s.addPair(0, 8, "muscle cluster7");
    s.addPair(8, 9, "muscle cluster7");
    s.addPair(0, 9, "muscle cluster7");

    // Cluster 8
    s.addPair(11, 7, "muscle cluster8");
    s.addPair(7, 10, "muscle cluster8");
    s.addPair(10, 11, "muscle cluster8");
}

void Escape_T6Model::setup(tgWorld& world)
{

    const tgRod::Config rodConfig(c.radius, c.density, c.friction,
            c.rollFriction, c.restitution);

    tgLinearString::Config muscleConfig(c.stiffness, c.damping, c.rotation,
            c.maxTens, c.targetVelocity,
            c.maxAcc);

    // Start creating the structure
    tgStructure s;
    addNodes(s);
    addRods(s);
    addMuscles(s);

    //    // Add a rotation. This is needed if the ground slopes too much,
    //    // otherwise  glitches put a rod below the ground.
    //    btVector3 rotationPoint = btVector3(0, 0, 0); // origin
    //    btVector3 rotationAxis = btVector3(0, 1, 0);  // y-axis
    //    double rotationAngle = M_PI/2;
    //    s.addRotation(rotationPoint, rotationAxis, rotationAngle);

    //s.move(btVector3(0,30,0));

    // Create the build spec that uses tags to turn the structure into a real model
    tgBuildSpec spec;
    spec.addBuilder("rod", new tgRodInfo(rodConfig));
    spec.addBuilder("muscle", new tgLinearStringInfo(muscleConfig));

    // Create your structureInfo
    tgStructureInfo structureInfo(s, spec);

    // Use the structureInfo to build ourselves
    structureInfo.buildInto(*this, world);

    // We could now use tgCast::filter or similar to pull out the
    // models (e.g. muscles) that we want to control.
    allMuscles = tgCast::filter<tgModel, tgLinearString> (getDescendants());

    // call the onSetup methods of all observed things e.g. controllers
    notifySetup();

    // Actually setup the children
    tgModel::setup(world);

    //map the rods and add the markers to them
    addMarkers(s);

    btVector3 location(0,50.0,0);
    btVector3 rotation(0.0,0.6,0.8);
    btVector3 speed(0,0,0);
    this->moveModel(location,rotation,speed);
}

void Escape_T6Model::step(double dt)
{
    // Precondition
    if (dt <= 0.0)
    {
        throw std::invalid_argument("dt is not positive");
    }
    else
    {
        //Notify observers (controllers) of the step so that they can take action
        notifyStep(dt);
        tgModel::step(dt);  // Step any children
    }
}

void Escape_T6Model::onVisit(tgModelVisitor& r)
{
    tgModel::onVisit(r);
}

const std::vector<tgLinearString*>& Escape_T6Model::getAllMuscles() const
{
    return allMuscles;
}

void Escape_T6Model::teardown()
{
    notifyTeardown();
    tgModel::teardown();
}

void Escape_T6Model::moveModel(btVector3 positionVector,btVector3 rotationVector,btVector3 speedVector)
{
    std::vector<tgRod *> rods=find<tgRod>("rod");

    btQuaternion initialRotationQuat;
    initialRotationQuat.setEuler(rotationVector[0],rotationVector[1],rotationVector[2]);
    btTransform initialTransform;
    initialTransform.setIdentity();
    initialTransform.setRotation(initialRotationQuat);
    initialTransform.setOrigin(positionVector);
    for(int i=0;i<rods.size();i++)
    {
        rods[i]->getPRigidBody()->setLinearVelocity(speedVector);
        rods[i]->getPRigidBody()->setWorldTransform(initialTransform * rods[i]->getPRigidBody()->getWorldTransform());
    }
}
<commit_msg>Explicitly includes string history in the muscle config (for energy spent calculations). String history is set to 'true' by default (records)<commit_after>/*
 * Copyright © 2014, United States Government, as represented by the
 * Administrator of the National Aeronautics and Space Administration.
 * All rights reserved.
 *
 * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

/**
 * @file Escape_T6Model.cpp
 * @brief Contains the implementation of class Escape_T6Model.
 * $Id$
 */

// This module
#include "Escape_T6Model.h"
// This library
#include "core/tgLinearString.h"
#include "core/tgRod.h"
#include "tgcreator/tgBuildSpec.h"
#include "tgcreator/tgLinearStringInfo.h"
#include "tgcreator/tgRodInfo.h"
#include "tgcreator/tgStructure.h"
#include "tgcreator/tgStructureInfo.h"
// The Bullet Physics library
#include "LinearMath/btVector3.h"
// The C++ Standard Library
#include <stdexcept>

namespace
{
    // see tgBaseString.h for a descripton of some of these rod parameters
    // (specifically, those related to the motor moving the strings.)
    // NOTE that any parameter that depends on units of length will scale
    // with the current gravity scaling. E.g., with gravity as 98.1,
    // the length units below are in decimeters.

    // Note: This current model of the SUPERball rod is 1.5m long by 3 cm radius,
    // which is 0.00424 m^3.
    // For SUPERball v1.5, mass = 3.5kg per strut, which comes out to
    // 0.825 kg / (decimeter^3).

    // similarly, frictional parameters are for the tgRod objects.
    const struct Config
    {
        double density;
        double radius;
        double stiffness;
        bool   history;
        double damping;
        double rod_length;
        double rod_space;
        double friction;
        double rollFriction;
        double restitution;
        double rotation;
        double maxTens;
        double targetVelocity;
        double maxAcc;
    } c =
    {
        0.825,    // density (kg / length^3)
        0.31,     // radius (length)
        3000.0,   // stiffness (kg / sec^2)
        true,     // history (record?)
        200.0,    // damping (kg / sec)
        15.0,     // rod_length (length)
        7.5,      // rod_space (length)
        1.0,      // friction (unitless)
        0.01,     // rollFriction (unitless)
        0.2,      // restitution (?)
        0,        // rotation
        100000,   // maxTens
        10000,    // targetVelocity
        20000     // maxAcc

            // Use the below values for earlier versions of simulation.
            // 1.006,
            // 0.31,
            // 300000.0,
            // 3000.0,
            // 15.0,
            // 7.5,
    };
} // namespace

/*
 * helper arrays for node and rod numbering schema
 */
/*returns the number of the rod for a given node */
const int rodNumbersPerNode[13]={0,1,2,3,3,4,0,1,2,5,5,4,6};

/*returns the node that is at the other end of the given node */
const int otherEndOfTheRod[13]={6,7,8,4,3,11,0,1,2,10,9,5,12};

/*returns the node that is at the parallel rod
 * and at the same end of the given node
 */
const int parallelNode[13]={1,0,5,9,10,2,7,6,11,3,4,8,12};

Escape_T6Model::Escape_T6Model() : tgModel()
{
}

Escape_T6Model::~Escape_T6Model()
{
}

//Node numbers seen from Front
// -----0-------1------
// ---------2----------
// 3------------------4
// ---------5----------
// -----6-------7------
//
//Node numbers seen from Back
// -----0-------1------
// ---------8----------
// 9-----------------10
// ---------11---------
// -----6-------7------
//

void Escape_T6Model::addNodes(tgStructure& s)
{
    const double half_length = c.rod_length / 2;

    nodePositions.push_back(btVector3(-half_length, c.rod_space, 0));            // 0
    nodePositions.push_back(btVector3( half_length, c.rod_space, 0));            // 1
    nodePositions.push_back(btVector3(0,            half_length, -c.rod_space)); // 2
    nodePositions.push_back(btVector3(-c.rod_space, 0,           -half_length)); // 3
    nodePositions.push_back(btVector3( c.rod_space, 0,           -half_length)); // 4
    nodePositions.push_back(btVector3(0,            -half_length, -c.rod_space));// 5
    nodePositions.push_back(btVector3(-half_length, -c.rod_space, 0));           // 6
    nodePositions.push_back(btVector3( half_length, -c.rod_space, 0));           // 7
    nodePositions.push_back(btVector3(0,            half_length,  c.rod_space)); // 8
    nodePositions.push_back(btVector3(-c.rod_space, 0,            half_length)); // 9
    nodePositions.push_back(btVector3( c.rod_space, 0,            half_length)); // 10
    nodePositions.push_back(btVector3(0,            -half_length, c.rod_space)); // 11

    for(int i=0;i<12;i++)
    {
        s.addNode(nodePositions[i][0],nodePositions[i][1],nodePositions[i][2]);
    }
}

void Escape_T6Model::addRods(tgStructure& s)
{
    s.addPair( 0,  6, "r1 rod");
    s.addPair( 1,  7, "r2 rod");
    s.addPair( 2,  8, "r3 rod");
    s.addPair( 3,  4, "r4 rod");
    s.addPair( 5, 11, "r5 rod");
    s.addPair( 9, 10, "r6 rod");
}

void Escape_T6Model::addMarkers(tgStructure &s)
{
    std::vector<tgRod *> rods=find<tgRod>("rod");

    for(int i=0;i<12;i++)
    {
        const btRigidBody* bt = rods[rodNumbersPerNode[i]]->getPRigidBody();
        btTransform inverseTransform = bt->getWorldTransform().inverse();
        btVector3 pos = inverseTransform * (nodePositions[i]);
        abstractMarker tmp=abstractMarker(bt,pos,btVector3(0.08*i,1.0 - 0.08*i,.0),i);
        this->addMarker(tmp);
    }
}

/**
 * Defines muscles in the structure by their end nodes
 * as well as the cluster to which they belong
 * A cluster is any three muscles that form a triangle (with nodes as vertices)
 */
void Escape_T6Model::addMuscles(tgStructure& s)
{
    // Cluster 1
    s.addPair(0, 3, "muscle cluster1");
    s.addPair(3, 2, "muscle cluster1");
    s.addPair(2, 0, "muscle cluster1");

    // Cluster 2
    s.addPair(4, 5, "muscle cluster2");
    s.addPair(5, 7, "muscle cluster2");
    s.addPair(7, 4, "muscle cluster2");

    // Cluster 3
    s.addPair(1, 8, "muscle cluster3");
    s.addPair(8, 10, "muscle cluster3");
    s.addPair(10, 1, "muscle cluster3");

    //Cluster 4
    s.addPair(9, 11, "muscle cluster4");
    s.addPair(11, 6, "muscle cluster4");
    s.addPair(6, 9, "muscle cluster4");

    // Cluster 5
    s.addPair(1, 2, "muscle cluster5");
    s.addPair(2, 4, "muscle cluster5");
    s.addPair(4, 1, "muscle cluster5");

    // Cluster 6
    s.addPair(3, 5, "muscle cluster6");
    s.addPair(5, 6, "muscle cluster6");
    s.addPair(6, 3, "muscle cluster6");

    // Cluster 7
    s.addPair(0, 8, "muscle cluster7");
    s.addPair(8, 9, "muscle cluster7");
    s.addPair(0, 9, "muscle cluster7");

    // Cluster 8
    s.addPair(11, 7, "muscle cluster8");
    s.addPair(7, 10, "muscle cluster8");
    s.addPair(10, 11, "muscle cluster8");
}

void Escape_T6Model::setup(tgWorld& world)
{

    const tgRod::Config rodConfig(c.radius, c.density, c.friction,
            c.rollFriction, c.restitution);

    tgLinearString::Config muscleConfig(c.stiffness, c.damping,
            c.history, c.rotation, c.maxTens, c.targetVelocity,
            c.maxAcc);

    // Start creating the structure
    tgStructure s;
    addNodes(s);
    addRods(s);
    addMuscles(s);

    //    // Add a rotation. This is needed if the ground slopes too much,
    //    // otherwise  glitches put a rod below the ground.
    //    btVector3 rotationPoint = btVector3(0, 0, 0); // origin
    //    btVector3 rotationAxis = btVector3(0, 1, 0);  // y-axis
    //    double rotationAngle = M_PI/2;
    //    s.addRotation(rotationPoint, rotationAxis, rotationAngle);

    //s.move(btVector3(0,30,0));

    // Create the build spec that uses tags to turn the structure into a real model
    tgBuildSpec spec;
    spec.addBuilder("rod", new tgRodInfo(rodConfig));
    spec.addBuilder("muscle", new tgLinearStringInfo(muscleConfig));

    // Create your structureInfo
    tgStructureInfo structureInfo(s, spec);

    // Use the structureInfo to build ourselves
    structureInfo.buildInto(*this, world);

    // We could now use tgCast::filter or similar to pull out the
    // models (e.g. muscles) that we want to control.
    allMuscles = tgCast::filter<tgModel, tgLinearString> (getDescendants());

    // call the onSetup methods of all observed things e.g. controllers
    notifySetup();

    // Actually setup the children
    tgModel::setup(world);

    //map the rods and add the markers to them
    addMarkers(s);

    btVector3 location(0,50.0,0);
    btVector3 rotation(0.0,0.6,0.8);
    btVector3 speed(0,0,0);
    this->moveModel(location,rotation,speed);
}

void Escape_T6Model::step(double dt)
{
    // Precondition
    if (dt <= 0.0)
    {
        throw std::invalid_argument("dt is not positive");
    }
    else
    {
        //Notify observers (controllers) of the step so that they can take action
        notifyStep(dt);
        tgModel::step(dt);  // Step any children
    }
}

void Escape_T6Model::onVisit(tgModelVisitor& r)
{
    tgModel::onVisit(r);
}

const std::vector<tgLinearString*>& Escape_T6Model::getAllMuscles() const
{
    return allMuscles;
}

void Escape_T6Model::teardown()
{
    notifyTeardown();
    tgModel::teardown();
}

void Escape_T6Model::moveModel(btVector3 positionVector,btVector3 rotationVector,btVector3 speedVector)
{
    std::vector<tgRod *> rods=find<tgRod>("rod");

    btQuaternion initialRotationQuat;
    initialRotationQuat.setEuler(rotationVector[0],rotationVector[1],rotationVector[2]);
    btTransform initialTransform;
    initialTransform.setIdentity();
    initialTransform.setRotation(initialRotationQuat);
    initialTransform.setOrigin(positionVector);
    for(int i=0;i<rods.size();i++)
    {
        rods[i]->getPRigidBody()->setLinearVelocity(speedVector);
        rods[i]->getPRigidBody()->setWorldTransform(initialTransform * rods[i]->getPRigidBody()->getWorldTransform());
    }
}
<|endoftext|>


<commit_before>///
/// @file  S1.cpp
/// @brief Functions to calculate the contribution of the ordinary
///        leaves in the Lagarias-Miller-Odlyzko and Deleglise-Rivat
///        prime counting algorithms.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <S1.hpp>
#include <primecount-internal.hpp>
#include <FactorTable.hpp>
#include <PhiTiny.hpp>
#include <generate.hpp>
#include <pmath.hpp>

#include <stdint.h>
#include <iostream>
#include <vector>

#ifdef _OPENMP
  #include <omp.h>
#endif

using namespace std;
using namespace primecount;

namespace {
namespace S1 {

/// Run time: O(y) operations, O(y) space.
/// @pre is_phi_tiny(c) == true
///
template <typename T>
T S1(T x, int64_t y, int64_t c, int64_t prime_c, vector<int32_t>& lpf, vector<int32_t>& mu, int threads)
{
  if (print_status())
  {
    cout << endl;
    cout << "=== S1(x, y) ===" << endl;
    cout << "Computation of the ordinary leaves" << endl;
  }

  T sum = 0;
  int64_t thread_threshold = ipow(10, 6);
  threads = validate_threads(threads, y, thread_threshold);
  double time = get_wtime();

  #pragma omp parallel for num_threads(threads) reduction (+: sum)
  for (int64_t n = 1; n <= y; n++)
    if (lpf[n] > prime_c)
      sum += mu[n] * phi_tiny(x / n, c);

  if (print_status())
    print_result("S1", sum, time);

  return sum;
}

/// This version uses less memory (due to FactorTable compression).
/// Run time: O(y) operations, O(y) space.
/// @pre is_phi_tiny(c) == true
///
template <typename T, typename F>
T S1(T x, int64_t y, int64_t c, int64_t prime_c, FactorTable<F>& factors, int threads)
{
  // the factors lookup table contains only numbers
  // which are coprime to 2, 3, 5 and 7
  if (prime_c <= 7)
  {
    vector<int32_t> mu = generate_moebius(y);
    vector<int32_t> lpf = generate_least_prime_factors(y);
    return S1(x, y, c, prime_c, lpf, mu, threads);
  }

  if (print_status())
  {
    cout << endl;
    cout << "=== S1(x, y) ===" << endl;
    cout << "Computation of the ordinary leaves" << endl;
  }

  T sum = 0;
  int64_t limit = factors.get_index(y);
  int64_t thread_threshold = ipow(10, 6);
  threads = validate_threads(threads, y, thread_threshold);
  double time = get_wtime();

  #pragma omp parallel for num_threads(threads) reduction (+: sum)
  for (int64_t i = factors.get_index(1); i <= limit; i++)
    if (factors.lpf(i) > prime_c)
      sum += factors.mu(i) * phi_tiny(x / factors.get_number(i), c);

  if (print_status())
    print_result("S1", sum, time);

  return sum;
}

} // namespace S1
} // namespace

namespace primecount {

int64_t S1(int64_t x,
           int64_t y,
           int64_t c,
           int64_t prime_c,
           vector<int32_t>& lpf,
           vector<int32_t>& mu,
           int threads)
{
  return S1::S1(x, y, c, prime_c, lpf, mu, threads);
}

int64_t S1(int64_t x,
           int64_t y,
           int64_t c,
           int64_t prime_c,
           FactorTable<uint16_t>& factors,
           int threads)
{
  return S1::S1(x, y, c, prime_c, factors, threads);
}

#ifdef HAVE_INT128_T

int128_t S1(uint128_t x,
            int64_t y,
            int64_t c,
            int64_t prime_c,
            vector<int32_t>& lpf,
            vector<int32_t>& mu,
            int threads)
{
  return S1::S1(x, y, c, prime_c, lpf, mu, threads);
}

int128_t S1(uint128_t x,
            int64_t y,
            int64_t c,
            int64_t prime_c,
            FactorTable<uint16_t>& factors,
            int threads)
{
  return S1::S1(x, y, c, prime_c, factors, threads);
}

int128_t S1(uint128_t x,
            int64_t y,
            int64_t c,
            int64_t prime_c,
            FactorTable<uint32_t>& factors,
            int threads)
{
  return S1::S1(x, y, c, prime_c, factors, threads);
}

#endif

} // namespace primecount
<commit_msg>Fix wrong type<commit_after>///
/// @file  S1.cpp
/// @brief Functions to calculate the contribution of the ordinary
///        leaves in the Lagarias-Miller-Odlyzko and Deleglise-Rivat
///        prime counting algorithms.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <S1.hpp>
#include <primecount-internal.hpp>
#include <FactorTable.hpp>
#include <PhiTiny.hpp>
#include <generate.hpp>
#include <pmath.hpp>

#include <stdint.h>
#include <iostream>
#include <vector>

#ifdef _OPENMP
  #include <omp.h>
#endif

using namespace std;
using namespace primecount;

namespace {
namespace S1 {

/// Run time: O(y) operations, O(y) space.
/// @pre is_phi_tiny(c) == true
///
template <typename T>
T S1(T x, int64_t y, int64_t c, int64_t prime_c, vector<int32_t>& lpf, vector<int32_t>& mu, int threads)
{
  if (print_status())
  {
    cout << endl;
    cout << "=== S1(x, y) ===" << endl;
    cout << "Computation of the ordinary leaves" << endl;
  }

  T sum = 0;
  int64_t thread_threshold = ipow(10, 6);
  threads = validate_threads(threads, y, thread_threshold);
  double time = get_wtime();

  #pragma omp parallel for num_threads(threads) reduction (+: sum)
  for (int64_t n = 1; n <= y; n++)
    if (lpf[n] > prime_c)
      sum += mu[n] * phi_tiny(x / n, c);

  if (print_status())
    print_result("S1", sum, time);

  return sum;
}

/// This version uses less memory (due to FactorTable compression).
/// Run time: O(y) operations, O(y) space.
/// @pre is_phi_tiny(c) == true
///
template <typename T, typename F>
T S1(T x, int64_t y, int64_t c, int64_t prime_c, FactorTable<F>& factors, int threads)
{
  // the factors lookup table contains only numbers
  // which are coprime to 2, 3, 5 and 7
  if (prime_c <= 7)
  {
    vector<int32_t> mu = generate_moebius(y);
    vector<int32_t> lpf = generate_least_prime_factors(y);
    return S1(x, y, c, prime_c, lpf, mu, threads);
  }

  if (print_status())
  {
    cout << endl;
    cout << "=== S1(x, y) ===" << endl;
    cout << "Computation of the ordinary leaves" << endl;
  }

  T sum = 0;
  int64_t limit = factors.get_index(y);
  int64_t thread_threshold = ipow(10, 6);
  threads = validate_threads(threads, y, thread_threshold);
  double time = get_wtime();

  #pragma omp parallel for num_threads(threads) reduction (+: sum)
  for (int64_t i = factors.get_index(1); i <= limit; i++)
    if (factors.lpf(i) > prime_c)
      sum += factors.mu(i) * phi_tiny(x / factors.get_number(i), c);

  if (print_status())
    print_result("S1", sum, time);

  return sum;
}

} // namespace S1
} // namespace

namespace primecount {

int64_t S1(int64_t x,
           int64_t y,
           int64_t c,
           int64_t prime_c,
           vector<int32_t>& lpf,
           vector<int32_t>& mu,
           int threads)
{
  return S1::S1(x, y, c, prime_c, lpf, mu, threads);
}

int64_t S1(int64_t x,
           int64_t y,
           int64_t c,
           int64_t prime_c,
           FactorTable<uint16_t>& factors,
           int threads)
{
  return S1::S1(x, y, c, prime_c, factors, threads);
}

#ifdef HAVE_INT128_T

int128_t S1(uint128_t x,
            int64_t y,
            int64_t c,
            int64_t prime_c,
            vector<int32_t>& lpf,
            vector<int32_t>& mu,
            int threads)
{
  return S1::S1(x, y, c, prime_c, lpf, mu, threads);
}

int128_t S1(uint128_t x,
            int64_t y,
            int64_t c,
            uint32_t prime_c,
            FactorTable<uint16_t>& factors,
            int threads)
{
  return S1::S1(x, y, c, prime_c, factors, threads);
}

int128_t S1(uint128_t x,
            int64_t y,
            int64_t c,
            int64_t prime_c,
            FactorTable<uint32_t>& factors,
            int threads)
{
  return S1::S1(x, y, c, prime_c, factors, threads);
}

#endif

} // namespace primecount
<|endoftext|>


<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/python/framework/python_op_gen.h"

#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/framework/op_gen_lib.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace {

TEST(PythonOpGen, Basic) {
  OpList ops;
  OpRegistry::Global()->Export(false, &ops);

  ApiDefMap api_def_map(ops);

  string code = GetPythonOps(ops, api_def_map, {}, "");

  EXPECT_TRUE(absl::StrContains(code, "def case"));

  // TODO(mdan): Add tests to verify type annotations are correctly added.
}

// TODO(mdan): Include more tests with synhtetic ops and api defs.

}  // namespace
}  // namespace tensorflow
<commit_msg>Add tests to verify type annotations are correctly added<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/python/framework/python_op_gen.h"

#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/framework/op_gen_lib.h"
#include "tensorflow/core/platform/test.h"

#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/str_util.h"

namespace tensorflow {
namespace {

constexpr char kBaseOpDef[] = R"(
op {
  name: "Foo"
  input_arg {
    name: "x"
    type_attr: "T"
  }
  input_arg {
    name: "y"
    type_attr: "T2"
  }
  output_arg {
    name: "output"
    type_attr: "T"
  }
  attr {
    name: "T"
    type: "type"
    allowed_values {
      list {
        type: DT_UINT8
        type: DT_INT8
      }
    }
  }
  attr {
    name: "T2"
    type: "type"
    allowed_values {
      list {
        type: DT_STRING
        type: DT_FLOAT
        type: DT_DOUBLE
      }
    }
  }
  summary: "Summary for op Foo."
  description: "Description for op Foo."
}
op {
  name: "Bar"
  input_arg {
    name: "x"
    type: DT_STRING
  }
  input_arg {
    name: "y"
    type: DT_QINT8
  }
  output_arg {
    name: "output"
    type: DT_BOOL
  }
  summary: "Summary for op Bar."
  description: "Description for op Bar."
}
op {
  name: "FooBar"
  input_arg {
    name: "x"
    type: DT_FLOAT
  }
  output_arg {
    name: "output"
    type: DT_BOOL
  }
  attr {
    name: "t"
    type: "type"
    allowed_values {
      list {
        type: DT_HALF
        type: DT_INT8
      }
    }
  }
  attr {
    name: "var1"
    type: "bool"
    default_value {
      b: false
    }
  }
  attr {
    name: "var2"
    type: "int"
    default_value {
      i: 0
    }
  }
  summary: "Summary for op FooBar."
  description: "Description for op FooBar."
}
op {
  name: "Baz"
  input_arg {
    name: "inputs"
    number_attr: "N"
    type_list_attr: "T"
  }
  output_arg {
    name: "output1"
    type: DT_BOOL
  }
  output_arg {
    name: "output2"
    type: DT_BOOL
  }
  attr {
    name: "T"
    type: "bool"
  }
  attr {
    name: "N"
    type: "int"
  }
  summary: "Summary for op Baz."
  description: "Description for op Baz."
}
)";

std::unordered_set<string> type_annotate_ops {
  "Foo",
  "Bar",
  "FooBar",
  "Baz"
};

void ExpectHasSubstr(const string& s, const string& expected) {
  EXPECT_TRUE(absl::StrContains(s, expected))
      << "'Generated ops does not contain '" << expected << "'";
}

void ExpectDoesNotHaveSubstr(const string& s, const string& expected) {
  EXPECT_FALSE(absl::StrContains(s, expected))
      << "'Generated ops contains '" << expected << "'";
}

void ExpectSubstrOrder(const string& s, const string& before,
                       const string& after) {
  int before_pos = s.find(before);
  int after_pos = s.find(after);
  ASSERT_NE(std::string::npos, before_pos);
  ASSERT_NE(std::string::npos, after_pos);
  EXPECT_LT(before_pos, after_pos)
      << before << "' is not before '" << after;
}

TEST(PythonOpGen, Basic) {
  OpList ops;
  OpRegistry::Global()->Export(false, &ops);

  ApiDefMap api_def_map(ops);

  string code = GetPythonOps(ops, api_def_map, {}, "", {});

  EXPECT_TRUE(absl::StrContains(code, "def case"));
  // TODO(mdan): Add tests to verify type annotations are correctly added.
}

TEST(PythonOpGen, TypeAnnotateSingleTypeTensor) {
  OpList op_defs;
  OpRegistry::Global()->Export(false, &op_defs);
  protobuf::TextFormat::ParseFromString(kBaseOpDef, &op_defs);  // NOLINT
  ApiDefMap api_def_map(op_defs);

  string code = GetPythonOps(op_defs, api_def_map, {}, "", type_annotate_ops);

  const string typed_bar = "def bar(x: _ops.Tensor[_dtypes.String], y: _ops.Tensor[_dtypes.QInt8], name=None) -> _ops.Tensor[_dtypes.Bool]:";
  ExpectHasSubstr(code, typed_bar);

  const string untyped_bar = "def bar(x, y, name=None):";
  ExpectDoesNotHaveSubstr(code, untyped_bar);
}

TEST(PythonOpGen, TypeAnnotateMultiTypeTensor) {
  OpList op_defs;
  OpRegistry::Global()->Export(false, &op_defs);
  protobuf::TextFormat::ParseFromString(kBaseOpDef, &op_defs);  // NOLINT
  ApiDefMap api_def_map(op_defs);

  string code = GetPythonOps(op_defs, api_def_map, {}, "", type_annotate_ops);

  const string typed_foo = "def foo(x: _ops.Tensor[TV_Foo_T], y: _ops.Tensor[TV_Foo_T2], name=None) -> _ops.Tensor[TV_Foo_T]:";
  ExpectHasSubstr(code, typed_foo);
}

TEST(PythonOpGen, GenerateCorrectTypeVars) {
  OpList op_defs;
  OpRegistry::Global()->Export(false, &op_defs);
  protobuf::TextFormat::ParseFromString(kBaseOpDef, &op_defs);  // NOLINT
  ApiDefMap api_def_map(op_defs);

  string code = GetPythonOps(op_defs, api_def_map, {}, "", type_annotate_ops);

  const string typevars_foo = R"(
TV_Foo_T = TypeVar("TV_Foo_T", _dtypes.Int8, _dtypes.UInt8)
TV_Foo_T2 = TypeVar("TV_Foo_T2", _dtypes.Float32, _dtypes.Float64, _dtypes.String)
)";

  ExpectHasSubstr(code, typevars_foo);
}

TEST(PythonOpGen, TypeAnnotateFallback) {
  OpList op_defs;
  OpRegistry::Global()->Export(false, &op_defs);
  protobuf::TextFormat::ParseFromString(kBaseOpDef, &op_defs);  // NOLINT
  ApiDefMap api_def_map(op_defs);

  string code = GetPythonOps(op_defs, api_def_map, {}, "", type_annotate_ops);

  const string typed_foo_fallback = "def foo_eager_fallback(x: _ops.Tensor[TV_Foo_T], y: _ops.Tensor[TV_Foo_T2], name, ctx) -> _ops.Tensor[TV_Foo_T]:";
  ExpectHasSubstr(code, typed_foo_fallback);
}

TEST(PythonOpGen, GenerateTypeVarAboveOp) {
  OpList op_defs;
  OpRegistry::Global()->Export(false, &op_defs);
  protobuf::TextFormat::ParseFromString(kBaseOpDef, &op_defs);  // NOLINT
  ApiDefMap api_def_map(op_defs);

  string code = GetPythonOps(op_defs, api_def_map, {}, "", type_annotate_ops);

  const string typevar_foo = "TV_Foo_";
  const string def_foo = "def foo";
  ExpectSubstrOrder(code, typevar_foo, def_foo);
}

TEST(PythonOpGen, TypeAnnotateDefaultParams) {
  OpList op_defs;
  OpRegistry::Global()->Export(false, &op_defs);
  protobuf::TextFormat::ParseFromString(kBaseOpDef, &op_defs);  // NOLINT
  ApiDefMap api_def_map(op_defs);

  string code = GetPythonOps(op_defs, api_def_map, {}, "", type_annotate_ops);

  const string params = "def foo_bar(x: _ops.Tensor[_dtypes.Float32], t: TV_FooBar_t, var1: bool = False, var2: int = 0, name=None)";
  const string params_fallback = "def foo_bar_eager_fallback(x: _ops.Tensor[_dtypes.Float32], t: TV_FooBar_t, var1: bool, var2: int, name, ctx)";
  ExpectHasSubstr(code, params);
  ExpectHasSubstr(code, params_fallback);
}

TEST(PythonOpGen, NoTypingSequenceTensors) {
  OpList op_defs;
  OpRegistry::Global()->Export(false, &op_defs);
  protobuf::TextFormat::ParseFromString(kBaseOpDef, &op_defs);  // NOLINT
  ApiDefMap api_def_map(op_defs);

  string code = GetPythonOps(op_defs, api_def_map, {}, "", type_annotate_ops);

  const string baz_def_line = "def baz(inputs, name=None):";

  ExpectHasSubstr(code, baz_def_line);
}

// TODO(mdan): Include more tests with synhtetic ops and api defs.

}  // namespace
}  // namespace tensorflow
<|endoftext|>