<commit_before>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){

	printf("OSS :: Open Strip Spatializer setup\n");

	ofSetWindowTitle("OSS :: Open Strip Spatializer");
	ofSetWindowShape(640,480);			// Set the initial window size

	//ofSetFrameRate(100);

    #ifdef WIN32
	spout.setup();
    #elif MAC_OS_X_VERSION_10_6
    syphonClient.setup();
    //syphonClient.set("","")
    #endif

	gui.setup();
	ofAddListener(gui.panel->newGUIEvent,this,&ofApp::guiEvent);
	ofAddListener(gui.ledPanel->newGUIEvent,this,&ofApp::guiEvent);

	directPix = new unsigned char[1920*1080*3];

	//Init with black
	memset(directPix,0,1920*1080*3);
	pixels.setFromPixels(directPix,1920,1080,OF_IMAGE_COLOR);

	fileName = "settings.xml";
	loadSettings(fileName);

    showTexture = true;
}

//--------------------------------------------------------------
void ofApp::update(){

}

//--------------------------------------------------------------
void ofApp::draw(){

	ofBackground(0);
	ofTexture * targetTex = NULL;

    #ifdef _WIN32
	bool spoutReceiveOK = spout.receiveTexture();

	if(showTexture && spoutReceiveOK)
	{
		targetTex = &spout.myTexture;

	}

    #elif MAC_OS_X_VERSION_10_6

    if(syphonClient.isSetup())
    {
        targetTex = &syphonClient.getTexture();
    }
    #endif

	if(targetTex)
	{

#ifdef MAC_OS_X_VERSION_10_6
        syphonClient.bind();
#endif

      if(showTexture)  targetTex->draw(0,0,ofGetWidth(),ofGetHeight());

      ledManager.draw(targetTex);

#ifdef MAC_OS_X_VERSION_10_6
        syphonClient.unbind();
#endif
	}

	// TODO : move to a place where it's not calculated each time (event ?)
	gui.numLedsLabel->setLabel("Led count : "+ofToString(ledManager.ledCount));
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key)
{
	switch (key)
	{

		case '1':
			loadSettings("settings_1.xml");
			break;
		case '2':
			loadSettings("settings_2.xml");
			break;
		case '3':
			loadSettings("settings_3.xml");
			break;
		case '4':
			loadSettings("settings_4.xml");
			break;
		case '5':
			loadSettings("settings_5.xml");
			break;

		case '6':
			loadSettings("settings_6.xml");
			break;

		case 's':
			saveSettings();
			break;

		case 'l':
			loadSettings("settings.xml");
			break;

		case 'f':
			ledManager.showLeds = !ledManager.showLeds;
			break;

		case 'p':
			gui.panel->toggleMinified();
			break;

		case 'o':
			gui.ledPanel->toggleMinified();
			break;

		default:
			break;
	}
}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

    #ifdef _WIN32
	if(button == 2) spout.spoutreceiver->SelectSenderPanel("/DX11");
    #endif

    if(button == 0) ledManager.mousePressed(false);
}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
	ledManager.mouseReleased();
}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}

void ofApp::loadSettings(const std::string &file)
{
	fileName = file;

	//printf("Load Settings : %s\n",fileName.c_str());

	ofxXmlSettings settings;

	if(!ofFile::doesFileExist(fileName))
	{
		ofLogWarning("File does not exists : %s\n",fileName.c_str());
		//return;
	}

	if(settings.loadFile(fileName)){

		ledManager.loadSettings(settings);

		settings.pushTag("global");
		ledManager.setSendRate(settings.getValue("sendRate",ledManager.sendRate));
		gui.setSendRate(ledManager.sendRate);
		settings.popTag();
	}
	else{
		ofLogError("Position file did not load!");
	}

}

void ofApp::saveSettings()
{
	//printf("Save settings [%s]....",fileName.c_str());
	ofxXmlSettings settings;

	settings.addTag("global");
	settings.pushTag("global");
	settings.addValue("sendRate",ledManager.sendRate);
	settings.popTag();

	ledManager.saveSettings(settings);

	string str;
	settings.copyXmlToString(str);
	//printf("\n ***\n%s\n***\n",str.c_str());
	settings.saveFile(fileName); //puts settings.xml file in the bin/data folder

	//printf("Saved !\n");
}

void ofApp::guiEvent(ofxUIEventArgs &e)
{
	string name = e.getName();
	const char * nameC = name.c_str();
	int kind = e.getKind();

	//printf("got event from: %s\n",name.c_str());
	//printf("kind : %i\n",kind);

	switch(kind)
	{
	case OFX_UI_WIDGET_BUTTON:
		if(strcmp(nameC,"Add Strip") == 0)
		{
			if( e.getButton()->getValue()) ledManager.hubs[0]->addStrip(0);
		}else if(strcmp(nameC,"Remove Strip") == 0)
		{
			if( e.getButton()->getValue()) ledManager.hubs[0]->removeStrip(0);
		}
		break;

	case OFX_UI_WIDGET_TOGGLE:

		if(strcmp(nameC,"Show Texture") == 0)
		{
			showTexture = e.getButton()->getValue();
		}else if(strcmp(nameC,"Show Leds") == 0)
		{
			LedManager::showLeds = e.getButton()->getValue();
		}else if(strcmp(nameC,"Show Lines") == 0)
		{
			LedManager::showLines = e.getButton()->getValue();
		}else if(strcmp(nameC,"Show Links") == 0)
		{
			LedManager::showLinks = e.getButton()->getValue();
		}else if(strcmp(nameC,"Show Handles") == 0)
		{
			LedManager::showHandles = e.getButton()->getValue();
		}else if(strcmp(nameC,"Show Contour") == 0)
		{
			LedManager::showContour = e.getButton()->getValue();
		}else if(strcmp(nameC,"Update Leds") == 0)
		{
			LedManager::doUpdateLeds = !LedManager::doUpdateLeds;
		}else if(strcmp(nameC,"Assign Leds") == 0)
		{
			LedManager::assignLeds = !LedManager::assignLeds;
		}
		break;

	case OFX_UI_WIDGET_SLIDER_H:
		if(kind == OFX_UI_WIDGET_SLIDER_H)
		{
			float sliderVal = e.getSlider()->getValue();
			if(strcmp(nameC,"Send Rate") == 0)
			{
				ledManager.setSendRate(sliderVal);
			}
		}

		break;
	}

}

void ofApp::exit()
{
    #ifdef _WIN32
    spout.exit();
    #endif

}<commit_msg>Fixed GUI addstrip and removestrip crash when no hubs were created<commit_after>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){

	printf("OSS :: Open Strip Spatializer setup\n");

	ofSetWindowTitle("OSS :: Open Strip Spatializer");
	ofSetWindowShape(640,480);			// Set the initial window size

	//ofSetFrameRate(100);

    #ifdef WIN32
	spout.setup();
    #elif MAC_OS_X_VERSION_10_6
    syphonClient.setup();
    //syphonClient.set("","")
    #endif

	gui.setup();
	ofAddListener(gui.panel->newGUIEvent,this,&ofApp::guiEvent);
	ofAddListener(gui.ledPanel->newGUIEvent,this,&ofApp::guiEvent);

	directPix = new unsigned char[1920*1080*3];

	//Init with black
	memset(directPix,0,1920*1080*3);
	pixels.setFromPixels(directPix,1920,1080,OF_IMAGE_COLOR);

	fileName = "settings.xml";
	loadSettings(fileName);

    showTexture = true;
}

//--------------------------------------------------------------
void ofApp::update(){

}

//--------------------------------------------------------------
void ofApp::draw(){

	ofBackground(0);
	ofTexture * targetTex = NULL;

    #ifdef _WIN32
	bool spoutReceiveOK = spout.receiveTexture();

	if(showTexture && spoutReceiveOK)
	{
		targetTex = &spout.myTexture;

	}

    #elif MAC_OS_X_VERSION_10_6

    if(syphonClient.isSetup())
    {
        targetTex = &syphonClient.getTexture();
    }
    #endif

	if(targetTex)
	{

#ifdef MAC_OS_X_VERSION_10_6
        syphonClient.bind();
#endif

      if(showTexture)  targetTex->draw(0,0,ofGetWidth(),ofGetHeight());

      ledManager.draw(targetTex);

#ifdef MAC_OS_X_VERSION_10_6
        syphonClient.unbind();
#endif
	}

	// TODO : move to a place where it's not calculated each time (event ?)
	gui.numLedsLabel->setLabel("Led count : "+ofToString(ledManager.ledCount));
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key)
{
	switch (key)
	{

		case '1':
			loadSettings("settings_1.xml");
			break;
		case '2':
			loadSettings("settings_2.xml");
			break;
		case '3':
			loadSettings("settings_3.xml");
			break;
		case '4':
			loadSettings("settings_4.xml");
			break;
		case '5':
			loadSettings("settings_5.xml");
			break;

		case '6':
			loadSettings("settings_6.xml");
			break;

		case 's':
			saveSettings();
			break;

		case 'l':
			loadSettings("settings.xml");
			break;

		case 'f':
			ledManager.showLeds = !ledManager.showLeds;
			break;

		case 'p':
			gui.panel->toggleMinified();
			break;

		case 'o':
			gui.ledPanel->toggleMinified();
			break;

		default:
			break;
	}
}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

    #ifdef _WIN32
	if(button == 2) spout.spoutreceiver->SelectSenderPanel("/DX11");
    #endif

    if(button == 0) ledManager.mousePressed(false);
}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
	ledManager.mouseReleased();
}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}

void ofApp::loadSettings(const std::string &file)
{
	fileName = file;

	//printf("Load Settings : %s\n",fileName.c_str());

	ofxXmlSettings settings;

	if(!ofFile::doesFileExist(fileName))
	{
		ofLogWarning("File does not exists : %s\n",fileName.c_str());
		//return;
	}

	if(settings.loadFile(fileName)){

		ledManager.loadSettings(settings);

		settings.pushTag("global");
		ledManager.setSendRate(settings.getValue("sendRate",ledManager.sendRate));
		gui.setSendRate(ledManager.sendRate);
		settings.popTag();
	}
	else{
		ofLogError("Position file did not load!");
	}

}

void ofApp::saveSettings()
{
	//printf("Save settings [%s]....",fileName.c_str());
	ofxXmlSettings settings;

	settings.addTag("global");
	settings.pushTag("global");
	settings.addValue("sendRate",ledManager.sendRate);
	settings.popTag();

	ledManager.saveSettings(settings);

	string str;
	settings.copyXmlToString(str);
	//printf("\n ***\n%s\n***\n",str.c_str());
	settings.saveFile(fileName); //puts settings.xml file in the bin/data folder

	//printf("Saved !\n");
}

void ofApp::guiEvent(ofxUIEventArgs &e)
{
	string name = e.getName();
	const char * nameC = name.c_str();
	int kind = e.getKind();

	//printf("got event from: %s\n",name.c_str());
	//printf("kind : %i\n",kind);

	switch(kind)
	{
	case OFX_UI_WIDGET_BUTTON:
		if(strcmp(nameC,"Add Strip") == 0)
		{
            if( e.getButton()->getValue()) {

                if(!ledManager.hubs.empty()) {

                    ledManager.hubs[0]->addStrip(0);
                } else {

                    // TODO : Should add default hub here ?
                    //ledManager.addHub(<#ofxXmlSettings settings#>, <#int hubIndex#>)
                    ofLogWarning("You should create a hub first!");
                }
            }
		}else if(strcmp(nameC,"Remove Strip") == 0)
		{
            if( e.getButton()->getValue()) {

                if(!ledManager.hubs.empty()) {

                    ledManager.hubs[0]->removeStrip(0);
                }
            }
		}
		break;

	case OFX_UI_WIDGET_TOGGLE:

		if(strcmp(nameC,"Show Texture") == 0)
		{
			showTexture = e.getButton()->getValue();
		}else if(strcmp(nameC,"Show Leds") == 0)
		{
			LedManager::showLeds = e.getButton()->getValue();
		}else if(strcmp(nameC,"Show Lines") == 0)
		{
			LedManager::showLines = e.getButton()->getValue();
		}else if(strcmp(nameC,"Show Links") == 0)
		{
			LedManager::showLinks = e.getButton()->getValue();
		}else if(strcmp(nameC,"Show Handles") == 0)
		{
			LedManager::showHandles = e.getButton()->getValue();
		}else if(strcmp(nameC,"Show Contour") == 0)
		{
			LedManager::showContour = e.getButton()->getValue();
		}else if(strcmp(nameC,"Update Leds") == 0)
		{
			LedManager::doUpdateLeds = !LedManager::doUpdateLeds;
		}else if(strcmp(nameC,"Assign Leds") == 0)
		{
			LedManager::assignLeds = !LedManager::assignLeds;
		}
		break;

	case OFX_UI_WIDGET_SLIDER_H:
		if(kind == OFX_UI_WIDGET_SLIDER_H)
		{
			float sliderVal = e.getSlider()->getValue();
			if(strcmp(nameC,"Send Rate") == 0)
			{
				ledManager.setSendRate(sliderVal);
			}
		}

		break;
	}

}

void ofApp::exit()
{
    #ifdef _WIN32
    spout.exit();
    #endif

}<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: misc_mem.cc,v 1.15 2001/10/03 13:10:38 bdenney Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

#include "bochs.h"
#define LOG_THIS BX_MEM(0)->

#if BX_PROVIDE_CPU_MEMORY
  Bit32u
BX_MEM_C::get_memory_in_k(void)
{
  return(BX_MEM_THIS megabytes * 1024);
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  // BX_MEM_C constructor
BX_MEM_C::BX_MEM_C(void)
{
  char mem[6];
  snprintf(mem, 6, "MEM%d", BX_SIM_ID);
  put(mem);
  settype(MEMLOG);

  vector = NULL;
  len    = 0;
  megabytes = 0;
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  // BX_MEM_C constructor
BX_MEM_C::BX_MEM_C(size_t memsize)
{
  vector = new Bit8u[memsize];
  len    = memsize;
  megabytes = len / (1024*1024);
  BX_INFO(("Init(%uB == %.2f)",memsize, megabytes));
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
// BX_MEM_C destructor
BX_MEM_C::~BX_MEM_C(void)
{
  if (this-> vector != NULL) {
    delete this->vector;
    }
  else {
    BX_DEBUG(("(%u)   memory not freed as it wasn't allocated!", BX_SIM_ID));
    }
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  void
BX_MEM_C::init_memory(int memsize)
{
	BX_DEBUG(("Init $Id: misc_mem.cc,v 1.15 2001/10/03 13:10:38 bdenney Exp $"));
  // you can pass 0 if memory has been allocated already through
  // the constructor, or the desired size of memory if it hasn't

  if (BX_MEM_THIS vector == NULL) {
    // memory not already allocated, do now...
    BX_MEM_THIS vector = new Bit8u[memsize];
    BX_MEM_THIS len    = memsize;
    BX_MEM_THIS megabytes = memsize / (1024*1024);
    BX_INFO(("%.2fMB", memsize, (float)(BX_MEM_THIS megabytes) ));
    }
  // initialize all memory to 0x00
  memset(BX_MEM_THIS vector, 0x00, BX_MEM_THIS len);

  // initialize ROM area (0xc0000 .. 0xfffff) to 0xff
  memset(BX_MEM_THIS vector + 0xc0000, 0xff, 0x40000);

#if BX_DEBUGGER
  // initialize dirty pages table
  memset(dbg_dirty_pages, 0, sizeof(dbg_dirty_pages));

  if (megabytes > BX_MAX_DIRTY_PAGE_TABLE_MEGS) {
    BX_INFO(("Error: memory larger than dirty page table can handle"));
    BX_PANIC(("Error: increase BX_MAX_DIRTY_PAGE_TABLE_MEGS"));
    }
#endif

}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  void
BX_MEM_C::load_ROM(const char *path, Bit32u romaddress)
{
  struct stat stat_buf;
  int fd, ret;
  unsigned long size, offset;

  // read in ROM BIOS image file
  fd = open(path, O_RDONLY
#ifdef O_BINARY
            | O_BINARY
#endif
           );
  if (fd < 0) {
    BX_INFO(( "ROM: couldn't open ROM image file '%s'.", path));
    exit(1);
    }
  ret = fstat(fd, &stat_buf);
  if (ret) {
    BX_INFO(( "ROM: couldn't stat ROM image file '%s'.", path));
    exit(1);
    }

  size = stat_buf.st_size;

  if ( (romaddress + size) > BX_MEM_THIS len ) {
    BX_INFO(( "ROM: ROM address range > physical memsize!"));
    exit(1);
    }

  offset = 0;
  while (size > 0) {
#if BX_PCI_SUPPORT
    if (bx_options.Oi440FXSupport->get ())
      ret = read(fd, (bx_ptr_t) &bx_devices.pci->s.i440fx.shadow[romaddress - 0xC0000 + offset],
                 size);
    else
      ret = read(fd, (bx_ptr_t) &BX_MEM_THIS vector[romaddress + offset], size);
#else
    ret = read(fd, (bx_ptr_t) &BX_MEM_THIS vector[romaddress + offset], size);
#endif
    if (ret <= 0) {
      BX_PANIC(( "ROM: read failed on BIOS image: '%s'",path));
      }
    size -= ret;
    offset += ret;
    }
  close(fd);
#if BX_PCI_SUPPORT
  if (bx_options.Oi440FXSupport->get ())
    BX_INFO(("rom in i440FX RAM 0x%06x/%u ('%s')",
			(unsigned) romaddress,
			(unsigned) stat_buf.st_size,
			path
		));
  else
    BX_INFO(("rom at 0x%05x/%u ('%s')",
			(unsigned) romaddress,
			(unsigned) stat_buf.st_size,
			path
		));
#else  // #if BX_PCI_SUPPORT
  BX_INFO(("rom at 0x%05x/%u ('%s')",
			(unsigned) romaddress,
			(unsigned) stat_buf.st_size,
 			path
		));
#endif // #if BX_PCI_SUPPORT
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if ( BX_DEBUGGER || BX_DISASM )
  Boolean
BX_MEM_C::dbg_fetch_mem(Bit32u addr, unsigned len, Bit8u *buf)
{
  if ( (addr + len) > this->len ) {
    BX_INFO(("dbg_fetch_mem out of range. %p > %p",
      addr+len, this->len));
    return(0); // error, beyond limits of memory
    }
  for (; len>0; len--) {
#if BX_SUPPORT_VGA
    if ( (addr & 0xfffe0000) == 0x000a0000 ) {
      *buf = BX_VGA_MEM_READ(addr);
      }
    else {
#endif
#if BX_PCI_SUPPORT == 0
      *buf = vector[addr];
#else
      if ( bx_options.Oi440FXSupport->get () &&
          ((addr >= 0x000C0000) && (addr <= 0x000FFFFF)) ) {
        switch (bx_devices.pci->rd_memType (addr)) {
          case 0x0:  // Fetch from ShadowRAM
            *buf = vector[addr];
//          BX_INFO(("Fetching from ShadowRAM %06x, len %u !", (unsigned)addr, (unsigned)len));
            break;

          case 0x1:  // Fetch from ROM
            *buf = bx_pci.s.i440fx.shadow[(addr - 0xC0000)];
//          BX_INFO(("Fetching from ROM %06x, Data %02x ", (unsigned)addr, *buf));
            break;
          default:
            BX_PANIC(("dbg_fetch_mem: default case"));
          }
        }
      else
        *buf = vector[addr];
#endif  // #if BX_PCI_SUPPORT == 0
      }
    buf++;
    addr++;
    }
  return(1);
}
#endif

#if BX_DEBUGGER
  Boolean
BX_MEM_C::dbg_set_mem(Bit32u addr, unsigned len, Bit8u *buf)
{
  if ( (addr + len) > this->len ) {
    return(0); // error, beyond limits of memory
    }
  for (; len>0; len--) {
#if BX_SUPPORT_VGA
    if ( (addr & 0xfffe0000) == 0x000a0000 ) {
      BX_VGA_MEM_WRITE(addr, *buf);
      }
    else
#endif
      vector[addr] = *buf;
    buf++;
    addr++;
    }
  return(1);
}
#endif

  Boolean
BX_MEM_C::dbg_crc32(unsigned long (*f)(unsigned char *buf, int len),
    Bit32u addr1, Bit32u addr2, Bit32u *crc)
{
  unsigned len;

  *crc = 0;
  if (addr1 > addr2)
    return(0);

  if (addr2 >= this->len) {
    return(0); // error, specified address past last phy mem addr
    }

  len = 1 + addr2 - addr1;
  *crc = f(vector + addr1, len);

  return(1);
}
<commit_msg>- fix silly output problem that caused it to print "0 megs" all the time<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: misc_mem.cc,v 1.16 2001/11/11 05:07:05 bdenney Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2001  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

#include "bochs.h"
#define LOG_THIS BX_MEM(0)->

#if BX_PROVIDE_CPU_MEMORY
  Bit32u
BX_MEM_C::get_memory_in_k(void)
{
  return(BX_MEM_THIS megabytes * 1024);
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  // BX_MEM_C constructor
BX_MEM_C::BX_MEM_C(void)
{
  char mem[6];
  snprintf(mem, 6, "MEM%d", BX_SIM_ID);
  put(mem);
  settype(MEMLOG);

  vector = NULL;
  len    = 0;
  megabytes = 0;
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  // BX_MEM_C constructor
BX_MEM_C::BX_MEM_C(size_t memsize)
{
  vector = new Bit8u[memsize];
  len    = memsize;
  megabytes = len / (1024*1024);
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
// BX_MEM_C destructor
BX_MEM_C::~BX_MEM_C(void)
{
  if (this-> vector != NULL) {
    delete this->vector;
    }
  else {
    BX_DEBUG(("(%u)   memory not freed as it wasn't allocated!", BX_SIM_ID));
    }
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  void
BX_MEM_C::init_memory(int memsize)
{
	BX_DEBUG(("Init $Id: misc_mem.cc,v 1.16 2001/11/11 05:07:05 bdenney Exp $"));
  // you can pass 0 if memory has been allocated already through
  // the constructor, or the desired size of memory if it hasn't

  if (BX_MEM_THIS vector == NULL) {
    // memory not already allocated, do now...
    BX_MEM_THIS vector = new Bit8u[memsize];
    BX_MEM_THIS len    = memsize;
    BX_MEM_THIS megabytes = memsize / (1024*1024);
    BX_INFO(("%.2fMB", (float)(BX_MEM_THIS megabytes) ));
    }
  // initialize all memory to 0x00
  memset(BX_MEM_THIS vector, 0x00, BX_MEM_THIS len);

  // initialize ROM area (0xc0000 .. 0xfffff) to 0xff
  memset(BX_MEM_THIS vector + 0xc0000, 0xff, 0x40000);

#if BX_DEBUGGER
  // initialize dirty pages table
  memset(dbg_dirty_pages, 0, sizeof(dbg_dirty_pages));

  if (megabytes > BX_MAX_DIRTY_PAGE_TABLE_MEGS) {
    BX_INFO(("Error: memory larger than dirty page table can handle"));
    BX_PANIC(("Error: increase BX_MAX_DIRTY_PAGE_TABLE_MEGS"));
    }
#endif

}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if BX_PROVIDE_CPU_MEMORY
  void
BX_MEM_C::load_ROM(const char *path, Bit32u romaddress)
{
  struct stat stat_buf;
  int fd, ret;
  unsigned long size, offset;

  // read in ROM BIOS image file
  fd = open(path, O_RDONLY
#ifdef O_BINARY
            | O_BINARY
#endif
           );
  if (fd < 0) {
    BX_INFO(( "ROM: couldn't open ROM image file '%s'.", path));
    exit(1);
    }
  ret = fstat(fd, &stat_buf);
  if (ret) {
    BX_INFO(( "ROM: couldn't stat ROM image file '%s'.", path));
    exit(1);
    }

  size = stat_buf.st_size;

  if ( (romaddress + size) > BX_MEM_THIS len ) {
    BX_INFO(( "ROM: ROM address range > physical memsize!"));
    exit(1);
    }

  offset = 0;
  while (size > 0) {
#if BX_PCI_SUPPORT
    if (bx_options.Oi440FXSupport->get ())
      ret = read(fd, (bx_ptr_t) &bx_devices.pci->s.i440fx.shadow[romaddress - 0xC0000 + offset],
                 size);
    else
      ret = read(fd, (bx_ptr_t) &BX_MEM_THIS vector[romaddress + offset], size);
#else
    ret = read(fd, (bx_ptr_t) &BX_MEM_THIS vector[romaddress + offset], size);
#endif
    if (ret <= 0) {
      BX_PANIC(( "ROM: read failed on BIOS image: '%s'",path));
      }
    size -= ret;
    offset += ret;
    }
  close(fd);
#if BX_PCI_SUPPORT
  if (bx_options.Oi440FXSupport->get ())
    BX_INFO(("rom in i440FX RAM 0x%06x/%u ('%s')",
			(unsigned) romaddress,
			(unsigned) stat_buf.st_size,
			path
		));
  else
    BX_INFO(("rom at 0x%05x/%u ('%s')",
			(unsigned) romaddress,
			(unsigned) stat_buf.st_size,
			path
		));
#else  // #if BX_PCI_SUPPORT
  BX_INFO(("rom at 0x%05x/%u ('%s')",
			(unsigned) romaddress,
			(unsigned) stat_buf.st_size,
 			path
		));
#endif // #if BX_PCI_SUPPORT
}
#endif // #if BX_PROVIDE_CPU_MEMORY

#if ( BX_DEBUGGER || BX_DISASM )
  Boolean
BX_MEM_C::dbg_fetch_mem(Bit32u addr, unsigned len, Bit8u *buf)
{
  if ( (addr + len) > this->len ) {
    BX_INFO(("dbg_fetch_mem out of range. %p > %p",
      addr+len, this->len));
    return(0); // error, beyond limits of memory
    }
  for (; len>0; len--) {
#if BX_SUPPORT_VGA
    if ( (addr & 0xfffe0000) == 0x000a0000 ) {
      *buf = BX_VGA_MEM_READ(addr);
      }
    else {
#endif
#if BX_PCI_SUPPORT == 0
      *buf = vector[addr];
#else
      if ( bx_options.Oi440FXSupport->get () &&
          ((addr >= 0x000C0000) && (addr <= 0x000FFFFF)) ) {
        switch (bx_devices.pci->rd_memType (addr)) {
          case 0x0:  // Fetch from ShadowRAM
            *buf = vector[addr];
//          BX_INFO(("Fetching from ShadowRAM %06x, len %u !", (unsigned)addr, (unsigned)len));
            break;

          case 0x1:  // Fetch from ROM
            *buf = bx_pci.s.i440fx.shadow[(addr - 0xC0000)];
//          BX_INFO(("Fetching from ROM %06x, Data %02x ", (unsigned)addr, *buf));
            break;
          default:
            BX_PANIC(("dbg_fetch_mem: default case"));
          }
        }
      else
        *buf = vector[addr];
#endif  // #if BX_PCI_SUPPORT == 0
      }
    buf++;
    addr++;
    }
  return(1);
}
#endif

#if BX_DEBUGGER
  Boolean
BX_MEM_C::dbg_set_mem(Bit32u addr, unsigned len, Bit8u *buf)
{
  if ( (addr + len) > this->len ) {
    return(0); // error, beyond limits of memory
    }
  for (; len>0; len--) {
#if BX_SUPPORT_VGA
    if ( (addr & 0xfffe0000) == 0x000a0000 ) {
      BX_VGA_MEM_WRITE(addr, *buf);
      }
    else
#endif
      vector[addr] = *buf;
    buf++;
    addr++;
    }
  return(1);
}
#endif

  Boolean
BX_MEM_C::dbg_crc32(unsigned long (*f)(unsigned char *buf, int len),
    Bit32u addr1, Bit32u addr2, Bit32u *crc)
{
  unsigned len;

  *crc = 0;
  if (addr1 > addr2)
    return(0);

  if (addr2 >= this->len) {
    return(0); // error, specified address past last phy mem addr
    }

  len = 1 + addr2 - addr1;
  *crc = f(vector + addr1, len);

  return(1);
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// Copyright (c) 2016, Jeff Hutchinson
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of glslTranslator nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------

#include <iostream>
#include <string>
#include "shaderTranslator.h"

int main(int argc, const char * argv[]) {
	std::string vertex = "#version 120\nattribute vec3 pos;\nvarying vec3 col;\nvarying vec2 uv;\nuniform vec4 mvp;\nvoid main() {\n   gl_Position = vec4(pos, 1) * mvp;\n   col = vec4(1.0f, 0.0f, 0.0f, 1.0f);\n   uv = vec2(0, 0);\n}\n";

	// test vertex shader translation from GLSL 120 to GLSL 330 core profile
	ShaderTranslator vertexTranslator;
	const auto &translatedSource =vertexTranslator.translate(vertex, ShaderTranslator::ShaderType::VERTEX);
	printf("%s\n", translatedSource.c_str());

	std::string frag = "#version 120\nvarying vec4 col;\nvarying vec2 uv;\nuniform sampler2D diffuseTexture;\nvoid main() {\n   gl_FragColor = texture2D(diffuseTexture.st, uv) * color;\n}\n";

	// test vertex shader translation from GLSL 120 to GLSL 330 core profile
	ShaderTranslator fragmentTranslator;
	const auto &translatedFragSource = fragmentTranslator.translate(frag, ShaderTranslator::ShaderType::FRAGMENT);
	printf("%s\n", translatedFragSource.c_str());

#ifdef _WIN32
	system("PAUSE");
#endif
	return 0;
}
<commit_msg>test comments during translation<commit_after>//------------------------------------------------------------------------------
// Copyright (c) 2016, Jeff Hutchinson
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of glslTranslator nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------

#include <iostream>
#include <string>
#include "shaderTranslator.h"

int main(int argc, const char * argv[]) {
	std::string vertex = "#version 120\n\n// blah blah blah\n\nattribute vec3 pos;\nvarying vec3 col;\nvarying vec2 uv;\nuniform vec4 mvp;\nvoid main() {\n   gl_Position = vec4(pos, 1) * mvp;\n   col = vec4(1.0f, 0.0f, 0.0f, 1.0f);\n   uv = vec2(0, 0);\n}\n";

	// test vertex shader translation from GLSL 120 to GLSL 330 core profile
	ShaderTranslator vertexTranslator;
	const auto &translatedSource =vertexTranslator.translate(vertex, ShaderTranslator::ShaderType::VERTEX);
	printf("%s\n", translatedSource.c_str());

	std::string frag = "#version 120\nvarying vec4 col;\nvarying vec2 uv;\nuniform sampler2D diffuseTexture;\nvoid main() {\n   gl_FragColor = texture2D(diffuseTexture.st, uv) * color;\n}\n";

	// test vertex shader translation from GLSL 120 to GLSL 330 core profile
	ShaderTranslator fragmentTranslator;
	const auto &translatedFragSource = fragmentTranslator.translate(frag, ShaderTranslator::ShaderType::FRAGMENT);
	printf("%s\n", translatedFragSource.c_str());

#ifdef _WIN32
	system("PAUSE");
#endif
	return 0;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// task - a command line task list manager.
//
// Copyright 2006 - 2009, Paul Beckingham.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
//     Free Software Foundation, Inc.,
//     51 Franklin Street, Fifth Floor,
//     Boston, MA
//     02110-1301
//     USA
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
#include <map>

#include "Date.h"
#include "task.h"
#include "T.h"

////////////////////////////////////////////////////////////////////////////////
// NOTE: These are static arrays only because there is no initializer list for
//       std::vector.
static const char* colors[] =
{
  "bold",
  "underline",
  "bold_underline",

  "black",
  "red",
  "green",
  "yellow",
  "blue",
  "magenta",
  "cyan",
  "white",

  "bold_black",
  "bold_red",
  "bold_green",
  "bold_yellow",
  "bold_blue",
  "bold_magenta",
  "bold_cyan",
  "bold_white",

  "underline_black",
  "underline_red",
  "underline_green",
  "underline_yellow",
  "underline_blue",
  "underline_magenta",
  "underline_cyan",
  "underline_white",

  "bold_underline_black",
  "bold_underline_red",
  "bold_underline_green",
  "bold_underline_yellow",
  "bold_underline_blue",
  "bold_underline_magenta",
  "bold_underline_cyan",
  "bold_underline_white",

  "on_black",
  "on_red",
  "on_green",
  "on_yellow",
  "on_blue",
  "on_magenta",
  "on_cyan",
  "on_white",

  "on_bright_black",
  "on_bright_red",
  "on_bright_green",
  "on_bright_yellow",
  "on_bright_blue",
  "on_bright_magenta",
  "on_bright_cyan",
  "on_bright_white",
  "",
};

static const char* attributes[] =
{
  "project",
  "priority",
  "fg",
  "bg",
  "due",
  "entry",
  "start",
  "end",
  "recur",
  "until",
  "mask",
  "imask",
  "",
};

static const char* commands[] =
{
  "active",
  "add",
  "calendar",
  "colors",
  "completed",
  "delete",
  "done",
  "export",
  "help",
  "history",
  "ghistory",
  "info",
  "next",
  "overdue",
  "projects",
  "start",
  "stats",
  "stop",
  "summary",
  "tags",
  "undelete",
  "undo",
  "version",
  "",
};

static std::vector <std::string> customReports;

////////////////////////////////////////////////////////////////////////////////
void guess (const std::string& type, const char** list, std::string& candidate)
{
  std::vector <std::string> options;
  for (int i = 0; list[i][0]; ++i)
    options.push_back (list[i]);

  std::vector <std::string> matches;
  autoComplete (candidate, options, matches);
  if (1 == matches.size ())
    candidate = matches[0];

  else if (0 == matches.size ())
    candidate = "";

  else
  {
    std::string error = "Ambiguous ";
    error += type;
    error += " '";
    error += candidate;
    error += "' - could be either of ";
    for (size_t i = 0; i < matches.size (); ++i)
    {
      if (i)
        error += ", ";
      error += matches[i];
    }

    throw error;
  }
}

////////////////////////////////////////////////////////////////////////////////
void guess (const std::string& type, std::vector<std::string>& options, std::string& candidate)
{
  std::vector <std::string> matches;
  autoComplete (candidate, options, matches);
  if (1 == matches.size ())
    candidate = matches[0];

  else if (0 == matches.size ())
//    throw std::string ("Unrecognized ") + type + " '" + candidate + "'";
    candidate = "";

  else
  {
    std::string error = "Ambiguous ";
    error += type;
    error += " '";
    error += candidate;
    error += "' - could be either of ";
    for (size_t i = 0; i < matches.size (); ++i)
    {
      if (i)
        error += ", ";
      error += matches[i];
    }

    throw error;
  }
}

////////////////////////////////////////////////////////////////////////////////
static bool isCommand (const std::string& candidate)
{
  std::vector <std::string> options;
  for (int i = 0; commands[i][0]; ++i)
    options.push_back (commands[i]);

  std::vector <std::string> matches;
  autoComplete (candidate, options, matches);
  if (0 == matches.size ())
  {
    autoComplete (candidate, customReports, matches);
    if (0 == matches.size ())
      return false;
  }

  return true;
}

////////////////////////////////////////////////////////////////////////////////
bool validDate (std::string& date, Config& conf)
{
  Date test (date, conf.get ("dateformat", "m/d/Y"));

  char epoch[12];
  sprintf (epoch, "%d", (int) test.toEpoch ());
  date = epoch;

  return true;
}

////////////////////////////////////////////////////////////////////////////////
bool validPriority (const std::string& input)
{
  if (input != "H" &&
      input != "M" &&
      input != "L" &&
      input != "")
    throw std::string ("\"") +
          input              +
          "\" is not a valid priority.  Use H, M, L or leave blank.";

  return true;
}

////////////////////////////////////////////////////////////////////////////////
static bool validAttribute (
  std::string& name,
  std::string& value,
  Config& conf)
{
  guess ("attribute", attributes, name);
  if (name != "")
  {
    if ((name == "fg" || name == "bg") && value != "")
      guess ("color", colors, value);

    else if (name == "due" && value != "")
      validDate (value, conf);

    else if (name == "until" && value != "")
      validDate (value, conf);

    else if (name == "priority")
    {
      value = upperCase (value);
      return validPriority (value);
    }

    // Some attributes are intended to be private.
    else if (name == "entry" ||
             name == "start" ||
             name == "end"   ||
             name == "mask"  ||
             name == "imask")
      throw std::string ("\"") +
            name               +
            "\" is not an attribute you may modify directly.";

    return true;
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
static bool validId (const std::string& input)
{
  for (size_t i = 0; i < input.length (); ++i)
    if (!::isdigit (input[i]))
      return false;

  return true;
}

////////////////////////////////////////////////////////////////////////////////
static bool validTag (const std::string& input)
{
  if ((input[0] == '-' || input[0] == '+') &&
       input.length () > 1)
    return true;

  return false;
}

////////////////////////////////////////////////////////////////////////////////
static bool validDescription (const std::string& input)
{
  if (input.length () == 0)                   return false;
  if (input.find ("\r") != std::string::npos) return false;
  if (input.find ("\f") != std::string::npos) return false;
  if (input.find ("\n") != std::string::npos) return false;

  return true;
}

////////////////////////////////////////////////////////////////////////////////
static bool validCommand (std::string& input)
{
  std::string copy = input;
  guess ("command", commands, copy);
  if (copy == "")
  {
    copy = input;
    guess ("command", customReports, copy);
    if (copy == "")
      return false;
  }

  input = copy;
  return true;
}

////////////////////////////////////////////////////////////////////////////////
static bool validSubstitution (
  std::string& input,
  std::string& from,
  std::string& to)
{
  size_t first = input.find ('/');
  if (first != std::string::npos)
  {
    size_t second = input.find ('/', first + 1);
    if (second != std::string::npos)
    {
      size_t third = input.find ('/', second + 1);
      if (third != std::string::npos)
      {
        if (first == 0 &&
            first < second &&
            second < third &&
            third == input.length () - 1)
        {
          from = input.substr (first  + 1, second - first  - 1);
          to   = input.substr (second + 1, third  - second - 1);
          return true;
        }
      }
    }
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
bool validDuration (std::string& input)
{
  return (convertDuration (input) != 0) ? true : false;
}

////////////////////////////////////////////////////////////////////////////////
// Token        Distinguishing characteristic
// -------      -----------------------------
// command      first positional
// id           \d+
// description  default, accumulate
// substitution /\w+/\w*/
// tags         [-+]\w+
// attributes   \w+:.+
//
void parse (
  std::vector <std::string>& args,
  std::string& command,
  T& task,
  Config& conf)
{
  command = "";

  std::string descCandidate = "";
  for (size_t i = 0; i < args.size (); ++i)
  {
    std::string arg (args[i]);

    // Ignore any argument that is "rc:...", because that is the command line
    // specified rc file.
    if (arg.substr (0, 3) != "rc:")
    {
      size_t colon;               // Pointer to colon in argument.
      std::string from;
      std::string to;

      // An id is the first argument found that contains all digits.
      if (lowerCase (command) != "add" && // "add" doesn't require an ID
          task.getId () == 0           &&
          validId (arg))
        task.setId (::atoi (arg.c_str ()));

      // Tags begin with + or - and contain arbitrary text.
      else if (validTag (arg))
      {
        if (arg[0] == '+')
          task.addTag (arg.substr (1, std::string::npos));
        else if (arg[0] == '-')
          task.addRemoveTag (arg.substr (1, std::string::npos));
      }

      // Attributes contain a constant string followed by a colon, followed by a
      // value.
      else if ((colon = arg.find (":")) != std::string::npos)
      {
        std::string name  = lowerCase (arg.substr (0, colon));
        std::string value = arg.substr (colon + 1, std::string::npos);

        if (validAttribute (name, value, conf))
        {
          if (name != "recur" || validDuration (value))
            task.setAttribute (name, value);
        }

        // If it is not a valid attribute, then allow the argument as part of
        // the description.
        else
          descCandidate += arg;
      }

      // Substitution of description text.
      else if (validSubstitution (arg, from, to))
      {
        task.setSubstitution (from, to);
      }

      // Command.
      else if (command == "")
      {
        std::string l = lowerCase (arg);
        if (isCommand (l) && validCommand (l))
          command = l;
        else
        {
          if (descCandidate.length ())
            descCandidate += " ";
          descCandidate += std::string (arg);
        }
      }

      // Anything else is just considered description.
      else
      {
        if (descCandidate.length ())
          descCandidate += " ";
        descCandidate += std::string (arg);
      }
    }
  }

  if (task.getAttribute ("recur") != "" &&
      task.getAttribute ("due")   == "")
    throw std::string ("You cannot specify a recurring task without a due date.");

  if (task.getAttribute ("until") != "" &&
      task.getAttribute ("recur") == "")
    throw std::string ("You cannot specify an until date for a non-recurring task.");

  if (validDescription (descCandidate))
    task.setDescription (descCandidate);
}

////////////////////////////////////////////////////////////////////////////////
void loadCustomReports (Config& conf)
{
  std::vector <std::string> all;
  conf.all (all);

  foreach (i, all)
  {
    if (i->substr (0, 7) == "report.")
    {
      std::string report = i->substr (7, std::string::npos);
      size_t columns = report.find (".columns");
      if (columns != std::string::npos)
      {
        report = report.substr (0, columns);
        customReports.push_back (report);
      }
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
bool isCustomReport (const std::string& report)
{
  foreach (i, customReports)
    if (*i == report)
      return true;

  return false;
}
////////////////////////////////////////////////////////////////////////////////
void allCustomReports (std::vector <std::string>& all)
{
  all = customReports;
}

////////////////////////////////////////////////////////////////////////////////

<commit_msg>Portability - Fedora 9<commit_after>////////////////////////////////////////////////////////////////////////////////
// task - a command line task list manager.
//
// Copyright 2006 - 2009, Paul Beckingham.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation; either version 2 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the
//
//     Free Software Foundation, Inc.,
//     51 Franklin Street, Fifth Floor,
//     Boston, MA
//     02110-1301
//     USA
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
#include <map>

#include "Date.h"
#include "task.h"
#include "T.h"

////////////////////////////////////////////////////////////////////////////////
// NOTE: These are static arrays only because there is no initializer list for
//       std::vector.
static const char* colors[] =
{
  "bold",
  "underline",
  "bold_underline",

  "black",
  "red",
  "green",
  "yellow",
  "blue",
  "magenta",
  "cyan",
  "white",

  "bold_black",
  "bold_red",
  "bold_green",
  "bold_yellow",
  "bold_blue",
  "bold_magenta",
  "bold_cyan",
  "bold_white",

  "underline_black",
  "underline_red",
  "underline_green",
  "underline_yellow",
  "underline_blue",
  "underline_magenta",
  "underline_cyan",
  "underline_white",

  "bold_underline_black",
  "bold_underline_red",
  "bold_underline_green",
  "bold_underline_yellow",
  "bold_underline_blue",
  "bold_underline_magenta",
  "bold_underline_cyan",
  "bold_underline_white",

  "on_black",
  "on_red",
  "on_green",
  "on_yellow",
  "on_blue",
  "on_magenta",
  "on_cyan",
  "on_white",

  "on_bright_black",
  "on_bright_red",
  "on_bright_green",
  "on_bright_yellow",
  "on_bright_blue",
  "on_bright_magenta",
  "on_bright_cyan",
  "on_bright_white",
  "",
};

static const char* attributes[] =
{
  "project",
  "priority",
  "fg",
  "bg",
  "due",
  "entry",
  "start",
  "end",
  "recur",
  "until",
  "mask",
  "imask",
  "",
};

static const char* commands[] =
{
  "active",
  "add",
  "calendar",
  "colors",
  "completed",
  "delete",
  "done",
  "export",
  "help",
  "history",
  "ghistory",
  "info",
  "next",
  "overdue",
  "projects",
  "start",
  "stats",
  "stop",
  "summary",
  "tags",
  "undelete",
  "undo",
  "version",
  "",
};

static std::vector <std::string> customReports;

////////////////////////////////////////////////////////////////////////////////
void guess (const std::string& type, const char** list, std::string& candidate)
{
  std::vector <std::string> options;
  for (int i = 0; list[i][0]; ++i)
    options.push_back (list[i]);

  std::vector <std::string> matches;
  autoComplete (candidate, options, matches);
  if (1 == matches.size ())
    candidate = matches[0];

  else if (0 == matches.size ())
    candidate = "";

  else
  {
    std::string error = "Ambiguous ";
    error += type;
    error += " '";
    error += candidate;
    error += "' - could be either of ";
    for (size_t i = 0; i < matches.size (); ++i)
    {
      if (i)
        error += ", ";
      error += matches[i];
    }

    throw error;
  }
}

////////////////////////////////////////////////////////////////////////////////
void guess (const std::string& type, std::vector<std::string>& options, std::string& candidate)
{
  std::vector <std::string> matches;
  autoComplete (candidate, options, matches);
  if (1 == matches.size ())
    candidate = matches[0];

  else if (0 == matches.size ())
//    throw std::string ("Unrecognized ") + type + " '" + candidate + "'";
    candidate = "";

  else
  {
    std::string error = "Ambiguous ";
    error += type;
    error += " '";
    error += candidate;
    error += "' - could be either of ";
    for (size_t i = 0; i < matches.size (); ++i)
    {
      if (i)
        error += ", ";
      error += matches[i];
    }

    throw error;
  }
}

////////////////////////////////////////////////////////////////////////////////
static bool isCommand (const std::string& candidate)
{
  std::vector <std::string> options;
  for (int i = 0; commands[i][0]; ++i)
    options.push_back (commands[i]);

  std::vector <std::string> matches;
  autoComplete (candidate, options, matches);
  if (0 == matches.size ())
  {
    autoComplete (candidate, customReports, matches);
    if (0 == matches.size ())
      return false;
  }

  return true;
}

////////////////////////////////////////////////////////////////////////////////
bool validDate (std::string& date, Config& conf)
{
  Date test (date, conf.get ("dateformat", "m/d/Y"));

  char epoch[12];
  sprintf (epoch, "%d", (int) test.toEpoch ());
  date = epoch;

  return true;
}

////////////////////////////////////////////////////////////////////////////////
bool validPriority (const std::string& input)
{
  if (input != "H" &&
      input != "M" &&
      input != "L" &&
      input != "")
    throw std::string ("\"") +
          input              +
          "\" is not a valid priority.  Use H, M, L or leave blank.";

  return true;
}

////////////////////////////////////////////////////////////////////////////////
static bool validAttribute (
  std::string& name,
  std::string& value,
  Config& conf)
{
  guess ("attribute", attributes, name);
  if (name != "")
  {
    if ((name == "fg" || name == "bg") && value != "")
      guess ("color", colors, value);

    else if (name == "due" && value != "")
      validDate (value, conf);

    else if (name == "until" && value != "")
      validDate (value, conf);

    else if (name == "priority")
    {
      value = upperCase (value);
      return validPriority (value);
    }

    // Some attributes are intended to be private.
    else if (name == "entry" ||
             name == "start" ||
             name == "end"   ||
             name == "mask"  ||
             name == "imask")
      throw std::string ("\"") +
            name               +
            "\" is not an attribute you may modify directly.";

    return true;
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
static bool validId (const std::string& input)
{
  for (size_t i = 0; i < input.length (); ++i)
    if (!::isdigit (input[i]))
      return false;

  return true;
}

////////////////////////////////////////////////////////////////////////////////
static bool validTag (const std::string& input)
{
  if ((input[0] == '-' || input[0] == '+') &&
       input.length () > 1)
    return true;

  return false;
}

////////////////////////////////////////////////////////////////////////////////
static bool validDescription (const std::string& input)
{
  if (input.length () == 0)                   return false;
  if (input.find ("\r") != std::string::npos) return false;
  if (input.find ("\f") != std::string::npos) return false;
  if (input.find ("\n") != std::string::npos) return false;

  return true;
}

////////////////////////////////////////////////////////////////////////////////
static bool validCommand (std::string& input)
{
  std::string copy = input;
  guess ("command", commands, copy);
  if (copy == "")
  {
    copy = input;
    guess ("command", customReports, copy);
    if (copy == "")
      return false;
  }

  input = copy;
  return true;
}

////////////////////////////////////////////////////////////////////////////////
static bool validSubstitution (
  std::string& input,
  std::string& from,
  std::string& to)
{
  size_t first = input.find ('/');
  if (first != std::string::npos)
  {
    size_t second = input.find ('/', first + 1);
    if (second != std::string::npos)
    {
      size_t third = input.find ('/', second + 1);
      if (third != std::string::npos)
      {
        if (first == 0 &&
            first < second &&
            second < third &&
            third == input.length () - 1)
        {
          from = input.substr (first  + 1, second - first  - 1);
          to   = input.substr (second + 1, third  - second - 1);
          return true;
        }
      }
    }
  }

  return false;
}

////////////////////////////////////////////////////////////////////////////////
bool validDuration (std::string& input)
{
  return (convertDuration (input) != 0) ? true : false;
}

////////////////////////////////////////////////////////////////////////////////
// Token        Distinguishing characteristic
// -------      -----------------------------
// command      first positional
// id           \d+
// description  default, accumulate
// substitution /\w+/\w*/
// tags         [-+]\w+
// attributes   \w+:.+
//
void parse (
  std::vector <std::string>& args,
  std::string& command,
  T& task,
  Config& conf)
{
  command = "";

  std::string descCandidate = "";
  for (size_t i = 0; i < args.size (); ++i)
  {
    std::string arg (args[i]);

    // Ignore any argument that is "rc:...", because that is the command line
    // specified rc file.
    if (arg.substr (0, 3) != "rc:")
    {
      size_t colon;               // Pointer to colon in argument.
      std::string from;
      std::string to;

      // An id is the first argument found that contains all digits.
      if (lowerCase (command) != "add" && // "add" doesn't require an ID
          task.getId () == 0           &&
          validId (arg))
        task.setId (::atoi (arg.c_str ()));

      // Tags begin with + or - and contain arbitrary text.
      else if (validTag (arg))
      {
        if (arg[0] == '+')
          task.addTag (arg.substr (1, std::string::npos));
        else if (arg[0] == '-')
          task.addRemoveTag (arg.substr (1, std::string::npos));
      }

      // Attributes contain a constant string followed by a colon, followed by a
      // value.
      else if ((colon = arg.find (":")) != std::string::npos)
      {
        std::string name  = lowerCase (arg.substr (0, colon));
        std::string value = arg.substr (colon + 1, std::string::npos);

        if (validAttribute (name, value, conf))
        {
          if (name != "recur" || validDuration (value))
            task.setAttribute (name, value);
        }

        // If it is not a valid attribute, then allow the argument as part of
        // the description.
        else
          descCandidate += arg;
      }

      // Substitution of description text.
      else if (validSubstitution (arg, from, to))
      {
        task.setSubstitution (from, to);
      }

      // Command.
      else if (command == "")
      {
        std::string l = lowerCase (arg);
        if (isCommand (l) && validCommand (l))
          command = l;
        else
        {
          if (descCandidate.length ())
            descCandidate += " ";
          descCandidate += std::string (arg);
        }
      }

      // Anything else is just considered description.
      else
      {
        if (descCandidate.length ())
          descCandidate += " ";
        descCandidate += std::string (arg);
      }
    }
  }

  if (task.getAttribute ("recur") != "" &&
      task.getAttribute ("due")   == "")
    throw std::string ("You cannot specify a recurring task without a due date.");

  if (task.getAttribute ("until") != "" &&
      task.getAttribute ("recur") == "")
    throw std::string ("You cannot specify an until date for a non-recurring task.");

  if (validDescription (descCandidate))
    task.setDescription (descCandidate);
}

////////////////////////////////////////////////////////////////////////////////
void loadCustomReports (Config& conf)
{
  std::vector <std::string> all;
  conf.all (all);

  foreach (i, all)
  {
    if (i->substr (0, 7) == "report.")
    {
      std::string report = i->substr (7, std::string::npos);
      std::string::size_type columns = report.find (".columns");
      if (columns != std::string::npos)
      {
        report = report.substr (0, columns);
        customReports.push_back (report);
      }
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
bool isCustomReport (const std::string& report)
{
  foreach (i, customReports)
    if (*i == report)
      return true;

  return false;
}
////////////////////////////////////////////////////////////////////////////////
void allCustomReports (std::vector <std::string>& all)
{
  all = customReports;
}

////////////////////////////////////////////////////////////////////////////////

<|endoftext|>


<commit_before>//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <stdio.h>

class Point {
public:
    int x;
    int y;
    Point(int a, int b):
        x(a),
        y(b)
    {}
};

class Data {
public:
    int id;
    Point point;
    Data(int i):
        id(i),
        point(0, 0)
    {}
};

int main(int argc, char const *argv[]) {
    Data *data[1000];
    Data **ptr = data;
    for (int i = 0; i < 1000; ++i) {
        ptr[i] = new Data(i);
        ptr[i]->point.x = i;
        ptr[i]->point.y = i+1;
    }

    printf("Finished populating data.\n");
    for (int i = 0; i < 1000; ++i) {
        bool dump = argc > 1; // Set breakpoint here.
                              // Evaluate a couple of expressions (2*1000 = 2000 exprs):
                              // expr ptr[i]->point.x
                              // expr ptr[i]->point.y
        if (dump) {
            printf("data[%d] = %d (%d, %d)\n", i, ptr[i]->id, ptr[i]->point.x, ptr[i]->point.y);
        }
    }
    return 0;
}
<commit_msg>[test] Fix a test that never compiled under -fmodules<commit_after>//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

class Point {
public:
    int x;
    int y;
    Point(int a, int b):
        x(a),
        y(b)
    {}
};

class Data {
public:
    int id;
    Point point;
    Data(int i):
        id(i),
        point(0, 0)
    {}
};

int main(int argc, char const *argv[]) {
    Data *data[1000];
    Data **ptr = data;
    for (int i = 0; i < 1000; ++i) {
        ptr[i] = new Data(i);
        ptr[i]->point.x = i;
        ptr[i]->point.y = i+1;
    }

    for (int i = 0; i < 1000; ++i) {
        bool dump = argc > 1; // Set breakpoint here.
                              // Evaluate a couple of expressions (2*1000 = 2000 exprs):
                              // expr ptr[i]->point.x
                              // expr ptr[i]->point.y
    }
    return 0;
}
<|endoftext|>


<commit_before>/*!
 *  \file       mco-controller_McoModel.hpp
 *  \author     Francois Best
 *  \date       15/10/2013
 *  \license    GPL v3.0 - Copyright Forty Seven Effects 2013
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

BEGIN_MCO_CONTROLLER_NAMESPACE

template<class Traits>
inline McoModel<Traits>::ScopedSlaveSelector::ScopedSlaveSelector()
{
    Traits::SlaveSelectPin::clear();
}

template<class Traits>
inline McoModel<Traits>::ScopedSlaveSelector::~ScopedSlaveSelector()
{
    Traits::SpiInterface::waitForEndOfTransmission();
    Traits::SlaveSelectPin::set();
}

// ########################################################################## //

template<class Traits>
inline McoModel<Traits>::McoModel(Spi& inInterface)
    : mInterface(inInterface)
{
}

template<class Traits>
inline McoModel<Traits>::~McoModel()
{
}

// -----------------------------------------------------------------------------

template<class Traits>
inline void McoModel<Traits>::init()
{
    Traits::SlaveSelectPin::setOutput();
    Traits::SlaveSelectPin::set(); // Active low
}

// -----------------------------------------------------------------------------

template<class Traits>
inline void McoModel<Traits>::setPitch(const mco_core::Pitch& inPitch)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::FineNote);
    mInterface.send(inPitch.semitones);
    mInterface.send(inPitch.cents);
}

template<class Traits>
inline void McoModel<Traits>::setDetune(const mco_core::Pitch& inPitch)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::GlobalDetune);
    mInterface.send(inPitch.semitones);
    mInterface.send(inPitch.cents);
}

// -----------------------------------------------------------------------------

template<class Traits>
inline void McoModel<Traits>::setPortamentoAmount(unsigned inAmount)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::PortamentoAmount);
    mInterface.send(inAmount >> 7);
    mInterface.send(inAmount & 0x7f);
}

template<class Traits>
inline void McoModel<Traits>::setPortamentoMode(byte inMode)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::PortamentoMode);
    mInterface.send(inMode);
}

// -----------------------------------------------------------------------------

template<class Traits>
inline void McoModel<Traits>::setVibratoSpeed(unsigned inSpeed)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::VibratoSpeed);
    mInterface.send(inSpeed >> 7);
    mInterface.send(inSpeed & 0x7f);
}

template<class Traits>
inline void McoModel<Traits>::setVibratoAmount(unsigned inAmount)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::VibratoAmount);
    mInterface.send(inAmount >> 7);
    mInterface.send(inAmount & 0x7f);
}

template<class Traits>
inline void McoModel<Traits>::setVibratoWaveform(byte inWaveform)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::VibratoWaveform);
    mInterface.send(inWaveform);
}

// -----------------------------------------------------------------------------

template<class Traits>
inline void McoModel<Traits>::setPwmSpeed(unsigned inSpeed)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::PwmSpeed);
    mInterface.send(inSpeed >> 7);
    mInterface.send(inSpeed & 0x7f);
}

template<class Traits>
inline void McoModel<Traits>::setPwmAmount(unsigned inAmount)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::PwmAmount);
    mInterface.send(inAmount >> 7);
    mInterface.send(inAmount & 0x7f);
}

template<class Traits>
inline void McoModel<Traits>::setPwmWaveform(byte inWaveform)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::PwmWaveform);
    mInterface.send(inWaveform);
}

// -----------------------------------------------------------------------------

template<class Traits>
inline void McoModel<Traits>::sendBoolParameter(mco_common::MessageStatus::Status inMessage)
{
    ScopedSlaveSelector selector;
    mInterface.send(inMessage);
}

END_MCO_CONTROLLER_NAMESPACE
<commit_msg>Fixed detune.<commit_after>/*!
 *  \file       mco-controller_McoModel.hpp
 *  \author     Francois Best
 *  \date       15/10/2013
 *  \license    GPL v3.0 - Copyright Forty Seven Effects 2013
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

BEGIN_MCO_CONTROLLER_NAMESPACE

template<class Traits>
inline McoModel<Traits>::ScopedSlaveSelector::ScopedSlaveSelector()
{
    Traits::SlaveSelectPin::clear();
}

template<class Traits>
inline McoModel<Traits>::ScopedSlaveSelector::~ScopedSlaveSelector()
{
    Traits::SpiInterface::waitForEndOfTransmission();
    Traits::SlaveSelectPin::set();
}

// ########################################################################## //

template<class Traits>
inline McoModel<Traits>::McoModel(Spi& inInterface)
    : mInterface(inInterface)
{
}

template<class Traits>
inline McoModel<Traits>::~McoModel()
{
}

// -----------------------------------------------------------------------------

template<class Traits>
inline void McoModel<Traits>::init()
{
    Traits::SlaveSelectPin::setOutput();
    Traits::SlaveSelectPin::set(); // Active low
}

// -----------------------------------------------------------------------------

template<class Traits>
inline void McoModel<Traits>::setPitch(const mco_core::Pitch& inPitch)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::FineNote);
    mInterface.send(inPitch.semitones);
    mInterface.send(inPitch.cents);
}

template<class Traits>
inline void McoModel<Traits>::setDetune(const mco_core::Pitch& inPitch)
{
    const int16 data = inPitch.semitones * 100 + inPitch.cents;
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::GlobalDetune);
    mInterface.send((data >> 7) & 0x7f);
    mInterface.send(data & 0x7f);
}

// -----------------------------------------------------------------------------

template<class Traits>
inline void McoModel<Traits>::setPortamentoAmount(unsigned inAmount)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::PortamentoAmount);
    mInterface.send(inAmount >> 7);
    mInterface.send(inAmount & 0x7f);
}

template<class Traits>
inline void McoModel<Traits>::setPortamentoMode(byte inMode)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::PortamentoMode);
    mInterface.send(inMode);
}

// -----------------------------------------------------------------------------

template<class Traits>
inline void McoModel<Traits>::setVibratoSpeed(unsigned inSpeed)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::VibratoSpeed);
    mInterface.send(inSpeed >> 7);
    mInterface.send(inSpeed & 0x7f);
}

template<class Traits>
inline void McoModel<Traits>::setVibratoAmount(unsigned inAmount)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::VibratoAmount);
    mInterface.send(inAmount >> 7);
    mInterface.send(inAmount & 0x7f);
}

template<class Traits>
inline void McoModel<Traits>::setVibratoWaveform(byte inWaveform)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::VibratoWaveform);
    mInterface.send(inWaveform);
}

// -----------------------------------------------------------------------------

template<class Traits>
inline void McoModel<Traits>::setPwmSpeed(unsigned inSpeed)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::PwmSpeed);
    mInterface.send(inSpeed >> 7);
    mInterface.send(inSpeed & 0x7f);
}

template<class Traits>
inline void McoModel<Traits>::setPwmAmount(unsigned inAmount)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::PwmAmount);
    mInterface.send(inAmount >> 7);
    mInterface.send(inAmount & 0x7f);
}

template<class Traits>
inline void McoModel<Traits>::setPwmWaveform(byte inWaveform)
{
    ScopedSlaveSelector selector;
    mInterface.send(mco_common::MessageStatus::PwmWaveform);
    mInterface.send(inWaveform);
}

// -----------------------------------------------------------------------------

template<class Traits>
inline void McoModel<Traits>::sendBoolParameter(mco_common::MessageStatus::Status inMessage)
{
    ScopedSlaveSelector selector;
    mInterface.send(inMessage);
}

END_MCO_CONTROLLER_NAMESPACE
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkGaussianCubeReader.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkGaussianCubeReader.h"

#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkPointData.h"
#include "vtkPoints.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkObjectFactory.h"
#include "vtkTransform.h"

#include <ctype.h>

vtkCxxRevisionMacro(vtkGaussianCubeReader, "1.13");
vtkStandardNewMacro(vtkGaussianCubeReader);

// Construct object with merging set to true.
vtkGaussianCubeReader::vtkGaussianCubeReader()
{
  this->FileName = NULL;
  this->Transform = vtkTransform::New();
  // Add the second output for the grid data

  vtkImageData *grid;
  grid = vtkImageData::New();
  grid->ReleaseData();
  this->AddOutput(grid);
  grid->Delete();
}

vtkGaussianCubeReader::~vtkGaussianCubeReader()
{
  if (this->FileName)
    {
    delete [] this->FileName;
    }
  this->Transform->Delete();
  // must delete the second output added
}

void vtkGaussianCubeReader::Execute()
{
  FILE *fp;
  char Title[256];
  char data_name[256];
  double elements[16];
  int JN1, N1N2, n1, n2, n3, i, j, k;
  float tmp, *Cube_data;

  // Output 0 (the default is the polydata)
  // Output 1 will be the gridded Image data

  vtkImageData *grid = this->GetGridOutput();

  if (!this->FileName)
    {
    return;
    }

  if ((fp = fopen(this->FileName, "r")) == NULL)
    {
    vtkErrorMacro(<< "File " << this->FileName << " not found");
    return;
    }

  fgets(Title, 256, fp);
  if(strtok(Title, ":") != NULL)
    {
    if(strtok(NULL, ":") != NULL)
      {
      strcpy(data_name, strtok(NULL, ":"));
      fprintf(stderr,"label = %s\n", data_name);
      }
    }
  fgets(Title, 256, fp);

  // Read in number of atoms, x-origin, y-origin z-origin
  //
  fscanf(fp, "%d %lf %lf %lf", &(this->NumberOfAtoms), &elements[3],
         &elements[7], &elements[11]);
  if(this->NumberOfAtoms < 0 )
    {
    this->NumberOfAtoms = -this->NumberOfAtoms;
    }

  fscanf(fp, "%d %lf %lf %lf", &n1, &elements[0], &elements[4], &elements[8]);
  fscanf(fp, "%d %lf %lf %lf", &n2, &elements[1], &elements[5], &elements[9]);
  fscanf(fp, "%d %lf %lf %lf", &n3, &elements[2], &elements[6], &elements[10]);
  elements[12] = 0;
  elements[13] = 0;
  elements[14] = 0;
  elements[15] = 1;

  vtkDebugMacro(<< "Grid Size " << n1 << " " << n2 << " " << n3);

  Transform->SetMatrix(elements);
  Transform->Inverse();

  ReadMolecule(fp);

  grid->SetWholeExtent(0, n1-1,
                       0, n2-1,
                       0, n3-1);
  grid->SetUpdateExtent(grid->GetWholeExtent());
  grid->SetExtent(grid->GetWholeExtent());

  grid->SetOrigin(0, 0, 0);
  grid->SetSpacing(1, 1, 1);
  grid->SetScalarTypeToFloat();
  grid->AllocateScalars();

  grid->GetPointData()->GetScalars()->SetName("Gaussian Cube density");

  Cube_data = (float *)grid->GetPointData()->GetScalars()->GetVoidPointer(0);
  N1N2 = n1*n2;

  for(i = 0; i < n1; i++)
    {
    JN1 = 0;
    for(j = 0; j < n2; j++)
      {
      for(k = 0; k < n3; k++)
        {
        fscanf(fp,"%f", &tmp);
        Cube_data[k*N1N2 + JN1 + i] = tmp;
        }
      JN1 += n1;
      }
    }
  fclose(fp);
}

void vtkGaussianCubeReader::ReadSpecificMolecule(FILE* fp)
{
  int i, j;
  float x[3];
  float dummy;

  for(i = 0; i < this->NumberOfAtoms; i++)
    {
    fscanf(fp, "%d %f %f %f %f", &j, &dummy, x, x+1, x+2);
    this->Points->InsertNextPoint(x);
    this->AtomType->InsertNextValue(j-1);
    }
}

vtkImageData *vtkGaussianCubeReader::GetGridOutput()
{
  return vtkImageData::SafeDownCast(this->Outputs[1]);
}

void vtkGaussianCubeReader::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << "Filename: " << (this->FileName?this->FileName:"(none)") << "\n";

  os << "Tranform: ";
  if( this->Transform )
    {
    os << endl;
    this->Transform->PrintSelf(os, indent.GetNextIndent());
    }
  else
    {
    os << "(none)\n";
    }
}

// Default implementation - copy information from first input to all outputs
void vtkGaussianCubeReader::ExecuteInformation()
{
  // first invoke default supoerclass method
  this->Superclass::ExecuteInformation();

  // the set the information for the imagedat output
  vtkImageData *grid = this->GetGridOutput();
  FILE *fp;
  char Title[256];

  if (!this->FileName)
    {
    return;
    }

  if ((fp = fopen(this->FileName, "r")) == NULL)
    {
    vtkErrorMacro(<< "File " << this->FileName << " not found");
    return;
    }

  fgets(Title, 256, fp);
  fgets(Title, 256, fp);

  // Read in number of atoms, x-origin, y-origin z-origin
  double tmpd;
  int n1, n2, n3;
  fscanf(fp, "%d %lf %lf %lf", &n1, &tmpd, &tmpd, &tmpd);

  fscanf(fp, "%d %lf %lf %lf", &n1, &tmpd, &tmpd, &tmpd);
  fscanf(fp, "%d %lf %lf %lf", &n2, &tmpd, &tmpd, &tmpd);
  fscanf(fp, "%d %lf %lf %lf", &n3, &tmpd, &tmpd, &tmpd);

  vtkDebugMacro(<< "Grid Size " << n1 << " " << n2 << " " << n3);
  grid->SetWholeExtent(0, n1-1, 0, n2-1, 0, n3-1);

  grid->SetOrigin(0, 0, 0);
  grid->SetSpacing(1, 1, 1);
  grid->SetScalarTypeToFloat();

  fclose(fp);
}

//----------------------------------------------------------------------------
int vtkGaussianCubeReader::FillOutputPortInformation(int port,
                                                     vtkInformation* info)
{
  if(port == 0)
    {
    return this->Superclass::FillOutputPortInformation(port, info);
    }
  info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkImageData");
  return 1;
}
<commit_msg>BUG: incorporating Jean Favre's changes on the ParaView-1-8 branch<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkGaussianCubeReader.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkGaussianCubeReader.h"

#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkPointData.h"
#include "vtkPoints.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkObjectFactory.h"
#include "vtkTransform.h"

#include <ctype.h>

vtkCxxRevisionMacro(vtkGaussianCubeReader, "1.13.2.1");
vtkStandardNewMacro(vtkGaussianCubeReader);

// Construct object with merging set to true.
vtkGaussianCubeReader::vtkGaussianCubeReader()
{
  this->FileName = NULL;
  this->Transform = vtkTransform::New();
  // Add the second output for the grid data

  vtkImageData *grid;
  grid = vtkImageData::New();
  grid->ReleaseData();
  this->AddOutput(grid);
  grid->Delete();
}

vtkGaussianCubeReader::~vtkGaussianCubeReader()
{
  if (this->FileName)
    {
    delete [] this->FileName;
    }
  this->Transform->Delete();
  // must delete the second output added
}

void vtkGaussianCubeReader::Execute()
{
  FILE *fp;
  char Title[256];
  char data_name[256];
  double elements[16];
  int JN1, N1N2, n1, n2, n3, i, j, k;
  float tmp, *Cube_data;

  // Output 0 (the default is the polydata)
  // Output 1 will be the gridded Image data

  vtkImageData *grid = this->GetGridOutput();

  if (!this->FileName)
    {
    return;
    }

  if ((fp = fopen(this->FileName, "r")) == NULL)
    {
    vtkErrorMacro(<< "File " << this->FileName << " not found");
    return;
    }

  fgets(Title, 256, fp);
  if(strtok(Title, ":") != NULL)
    {
    if(strtok(NULL, ":") != NULL)
      {
      strcpy(data_name, strtok(NULL, ":"));
      fprintf(stderr,"label = %s\n", data_name);
      }
    }
  fgets(Title, 256, fp);

  // Read in number of atoms, x-origin, y-origin z-origin
  //
  fscanf(fp, "%d %lf %lf %lf", &(this->NumberOfAtoms), &elements[3],
         &elements[7], &elements[11]);
  if(this->NumberOfAtoms < 0 )
    {
    this->NumberOfAtoms = -this->NumberOfAtoms;
    }

  fscanf(fp, "%d %lf %lf %lf", &n1, &elements[0], &elements[4], &elements[8]);
  fscanf(fp, "%d %lf %lf %lf", &n2, &elements[1], &elements[5], &elements[9]);
  fscanf(fp, "%d %lf %lf %lf", &n3, &elements[2], &elements[6], &elements[10]);
  elements[12] = 0;
  elements[13] = 0;
  elements[14] = 0;
  elements[15] = 1;

  vtkDebugMacro(<< "Grid Size " << n1 << " " << n2 << " " << n3);

  Transform->SetMatrix(elements);
  Transform->Inverse();

  ReadMolecule(fp);

  grid->SetWholeExtent(0, n1-1,
                       0, n2-1,
                       0, n3-1);
  grid->SetUpdateExtent(grid->GetWholeExtent());
  grid->SetExtent(grid->GetWholeExtent());

  grid->SetOrigin(0, 0, 0);
  grid->SetSpacing(1, 1, 1);
  grid->SetScalarTypeToFloat();
  grid->AllocateScalars();

  grid->GetPointData()->GetScalars()->SetName(Title);

  Cube_data = (float *)grid->GetPointData()->GetScalars()->GetVoidPointer(0);
  N1N2 = n1*n2;

  for(i = 0; i < n1; i++)
    {
    JN1 = 0;
    for(j = 0; j < n2; j++)
      {
      for(k = 0; k < n3; k++)
        {
        fscanf(fp,"%f", &tmp);
        Cube_data[k*N1N2 + JN1 + i] = tmp;
        }
      JN1 += n1;
      }
    }
  fclose(fp);
}

void vtkGaussianCubeReader::ReadSpecificMolecule(FILE* fp)
{
  int i, j;
  float x[3];
  float dummy;

  for(i = 0; i < this->NumberOfAtoms; i++)
    {
    fscanf(fp, "%d %f %f %f %f", &j, &dummy, x, x+1, x+2);
    this->Transform->TransformPoint(x, x);
    this->Points->InsertNextPoint(x);
    this->AtomType->InsertNextValue(j-1);
    }
}

vtkImageData *vtkGaussianCubeReader::GetGridOutput()
{
  return vtkImageData::SafeDownCast(this->Outputs[1]);
}

void vtkGaussianCubeReader::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << "Filename: " << (this->FileName?this->FileName:"(none)") << "\n";

  os << "Tranform: ";
  if( this->Transform )
    {
    os << endl;
    this->Transform->PrintSelf(os, indent.GetNextIndent());
    }
  else
    {
    os << "(none)\n";
    }
}

// Default implementation - copy information from first input to all outputs
void vtkGaussianCubeReader::ExecuteInformation()
{
  // first invoke default supoerclass method
  this->Superclass::ExecuteInformation();

  // the set the information for the imagedat output
  vtkImageData *grid = this->GetGridOutput();
  FILE *fp;
  char Title[256];

  if (!this->FileName)
    {
    return;
    }

  if ((fp = fopen(this->FileName, "r")) == NULL)
    {
    vtkErrorMacro(<< "File " << this->FileName << " not found");
    return;
    }

  fgets(Title, 256, fp);
  fgets(Title, 256, fp);

  // Read in number of atoms, x-origin, y-origin z-origin
  double tmpd;
  int n1, n2, n3;
  fscanf(fp, "%d %lf %lf %lf", &n1, &tmpd, &tmpd, &tmpd);

  fscanf(fp, "%d %lf %lf %lf", &n1, &tmpd, &tmpd, &tmpd);
  fscanf(fp, "%d %lf %lf %lf", &n2, &tmpd, &tmpd, &tmpd);
  fscanf(fp, "%d %lf %lf %lf", &n3, &tmpd, &tmpd, &tmpd);

  vtkDebugMacro(<< "Grid Size " << n1 << " " << n2 << " " << n3);
  grid->SetWholeExtent(0, n1-1, 0, n2-1, 0, n3-1);

  grid->SetOrigin(0, 0, 0);
  grid->SetSpacing(1, 1, 1);
  grid->SetScalarTypeToFloat();

  fclose(fp);
}

//----------------------------------------------------------------------------
int vtkGaussianCubeReader::FillOutputPortInformation(int port,
                                                     vtkInformation* info)
{
  if(port == 0)
    {
    return this->Superclass::FillOutputPortInformation(port, info);
    }
  info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkImageData");
  return 1;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Author:
 *  Jeremy Lainé
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include <QDomElement>
#include <QSslKey>
#include <QSslSocket>

#include "QXmppConstants.h"
#include "QXmppDialback.h"
#include "QXmppOutgoingServer.h"
#include "QXmppStreamFeatures.h"
#include "QXmppUtils.h"

class QXmppOutgoingServerPrivate
{
public:
    QString domain;
    QString localStreamKey;
    QString verifyId;
    QString verifyKey;
    bool ready;
};

/// Constructs a new outgoing server-to-server stream.
///
/// \param socket
/// \param domain the local domain
/// \param parent the parent object
///

QXmppOutgoingServer::QXmppOutgoingServer(const QString &domain, QObject *parent)
    : QXmppOutgoingClient(parent),
    d(new QXmppOutgoingServerPrivate)
{
    d->domain = domain;
    d->ready = false;
    configuration().setKeepAliveInterval(0);
}

/// Destroys the stream.
///

QXmppOutgoingServer::~QXmppOutgoingServer()
{
    delete d;
}

void QXmppOutgoingServer::handleStart()
{
    QString data = QString("<?xml version='1.0'?><stream:stream"
        " xmlns='%1' xmlns:db='%2' xmlns:stream='%3' version='1.0'>").arg(
            ns_server,
            ns_server_dialback,
            ns_stream);
    sendData(data.toUtf8());
}

void QXmppOutgoingServer::handleStanza(const QDomElement &stanza)
{
    const QString ns = stanza.namespaceURI();

    if(QXmppStreamFeatures::isStreamFeatures(stanza))
    {
        QXmppStreamFeatures features;
        features.parse(stanza);
        if (features.securityMode() != QXmppConfiguration::TLSDisabled)
        {
            // let QXmppOutgoingClient handle TLS
            QXmppOutgoingClient::handleStanza(stanza);
        }
        else if (!d->localStreamKey.isEmpty())
        {
            // send dialback key
            QXmppDialback dialback;
            dialback.setCommand(QXmppDialback::Result);
            dialback.setFrom(d->domain);
            dialback.setTo(configuration().domain());
            dialback.setKey(d->localStreamKey);
            sendPacket(dialback);
        }
        else if (!d->verifyId.isEmpty() && !d->verifyKey.isEmpty())
        {
            // send dialback verify
            QXmppDialback verify;
            verify.setCommand(QXmppDialback::Verify);
            verify.setId(d->verifyId);
            verify.setTo(configuration().domain());
            verify.setFrom(d->domain);
            verify.setKey(d->verifyKey);
            sendPacket(verify);
        }
    }
    else if (ns == ns_tls)
    {
        if (stanza.tagName() == "proceed")
        {
            debug("Starting encryption");
            socket()->startClientEncryption();
            return;
        }
    }
    else if (QXmppDialback::isDialback(stanza))
    {
        QXmppDialback response;
        response.parse(stanza);

        // check the request is valid
        if (response.from().isEmpty() ||
            response.to() != d->domain ||
            response.type().isEmpty())
        {
            warning("Invalid dialback response received");
            return;
        }
        if (response.command() == QXmppDialback::Result)
        {
            if (response.type() == "valid")
            {
                info("Outgoing stream is ready");
                d->ready = true;
                emit connected();
            }
        }
        else if (response.command() == QXmppDialback::Verify)
        {
            emit dialbackResponseReceived(response);
        }

    }
    else
    {
        bool handled = false;
        emit elementReceived(stanza, handled);
    }
}

/// Returns true if the socket is connected and authentication succeeded.
///

bool QXmppOutgoingServer::isConnected() const
{
    return QXmppStream::isConnected() && d->ready;
}

QString QXmppOutgoingServer::localStreamKey() const
{
    return d->localStreamKey;
}

void QXmppOutgoingServer::setLocalStreamKey(const QString &key)
{
    d->localStreamKey = key;
}

void QXmppOutgoingServer::setVerify(const QString &id, const QString &key)
{
    d->verifyId = id;
    d->verifyKey = key;
}

<commit_msg>outgoing S2S has no reason to receive any stanzas<commit_after>/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Author:
 *  Jeremy Lainé
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include <QDomElement>
#include <QSslKey>
#include <QSslSocket>

#include "QXmppConstants.h"
#include "QXmppDialback.h"
#include "QXmppOutgoingServer.h"
#include "QXmppStreamFeatures.h"
#include "QXmppUtils.h"

class QXmppOutgoingServerPrivate
{
public:
    QString domain;
    QString localStreamKey;
    QString verifyId;
    QString verifyKey;
    bool ready;
};

/// Constructs a new outgoing server-to-server stream.
///
/// \param socket
/// \param domain the local domain
/// \param parent the parent object
///

QXmppOutgoingServer::QXmppOutgoingServer(const QString &domain, QObject *parent)
    : QXmppOutgoingClient(parent),
    d(new QXmppOutgoingServerPrivate)
{
    d->domain = domain;
    d->ready = false;
    configuration().setKeepAliveInterval(0);
}

/// Destroys the stream.
///

QXmppOutgoingServer::~QXmppOutgoingServer()
{
    delete d;
}

void QXmppOutgoingServer::handleStart()
{
    QString data = QString("<?xml version='1.0'?><stream:stream"
        " xmlns='%1' xmlns:db='%2' xmlns:stream='%3' version='1.0'>").arg(
            ns_server,
            ns_server_dialback,
            ns_stream);
    sendData(data.toUtf8());
}

void QXmppOutgoingServer::handleStanza(const QDomElement &stanza)
{
    const QString ns = stanza.namespaceURI();

    if(QXmppStreamFeatures::isStreamFeatures(stanza))
    {
        QXmppStreamFeatures features;
        features.parse(stanza);
        if (features.securityMode() != QXmppConfiguration::TLSDisabled)
        {
            // let QXmppOutgoingClient handle TLS
            QXmppOutgoingClient::handleStanza(stanza);
        }
        else if (!d->localStreamKey.isEmpty())
        {
            // send dialback key
            QXmppDialback dialback;
            dialback.setCommand(QXmppDialback::Result);
            dialback.setFrom(d->domain);
            dialback.setTo(configuration().domain());
            dialback.setKey(d->localStreamKey);
            sendPacket(dialback);
        }
        else if (!d->verifyId.isEmpty() && !d->verifyKey.isEmpty())
        {
            // send dialback verify
            QXmppDialback verify;
            verify.setCommand(QXmppDialback::Verify);
            verify.setId(d->verifyId);
            verify.setTo(configuration().domain());
            verify.setFrom(d->domain);
            verify.setKey(d->verifyKey);
            sendPacket(verify);
        }
    }
    else if (ns == ns_tls)
    {
        if (stanza.tagName() == "proceed")
        {
            debug("Starting encryption");
            socket()->startClientEncryption();
            return;
        }
    }
    else if (QXmppDialback::isDialback(stanza))
    {
        QXmppDialback response;
        response.parse(stanza);

        // check the request is valid
        if (response.from().isEmpty() ||
            response.to() != d->domain ||
            response.type().isEmpty())
        {
            warning("Invalid dialback response received");
            return;
        }
        if (response.command() == QXmppDialback::Result)
        {
            if (response.type() == "valid")
            {
                info("Outgoing stream is ready");
                d->ready = true;
                emit connected();
            }
        }
        else if (response.command() == QXmppDialback::Verify)
        {
            emit dialbackResponseReceived(response);
        }

    }
}

/// Returns true if the socket is connected and authentication succeeded.
///

bool QXmppOutgoingServer::isConnected() const
{
    return QXmppStream::isConnected() && d->ready;
}

QString QXmppOutgoingServer::localStreamKey() const
{
    return d->localStreamKey;
}

void QXmppOutgoingServer::setLocalStreamKey(const QString &key)
{
    d->localStreamKey = key;
}

void QXmppOutgoingServer::setVerify(const QString &id, const QString &key)
{
    d->verifyId = id;
    d->verifyKey = key;
}

<|endoftext|>