<commit_before>#include "BuildIn.h"
#include "Interpreter.h"
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>

BuildIn::BuildIn(){
    numJob=0;
    jobs=new Jobs();
    jobs->next=NULL;
}

string BuildIn::getCurrentDic(){
    char cwd[1000];
    if(!getcwd(cwd,1000)){
        perror("Error: Cannot obtain current working directory");
        exit(0);
    }
    return string(cwd);
}
void BuildIn::handleCD(command thisCommand){
    if(thisCommand.tokLen==2){
        string path=thisCommand.toks[1]->tok;
        string finalPath;
        if(path[0]=='/'){
            finalPath=path;
        }else if(((path.length()>1) && path[0]=='.' && path[1]=='/') || (path[0]=='.' && (path.length()==1))){
            finalPath=getCurrentDic();
            string rest=path.substr(1,path.length());
            finalPath.append(rest);
        }else if(((path.length()>2) && path[0]=='.' && path[1]=='.' && path[2]=='/') || (path[0]=='.' && path[1]=='.' && path.length()==2)){
            finalPath=getCurrentDic();
            int found=finalPath.find_last_of("/");
            finalPath=finalPath.substr(0,found);
            finalPath.append(path.substr(2,path.length()));
        }else{
            finalPath=getCurrentDic();
            finalPath.append("/");
            finalPath.append(path);
        }
        const char *pathTemp=finalPath.c_str();
        int ret=chdir(pathTemp);
        if(ret){
            cout << "[" << path << "]: cannot change directory\n";
        }
    }else{
        cout << "cd: wrong number of arguments\n";
    }
}

void BuildIn::handleExit(command thisCommand){
     if(thisCommand.tokLen==1){
         if(numJob>0){
             cout << "There is at least one suspended job\n";
         }else{
             exit(0);
         }
     }else{
         cout << "exit: wrong number of arguments\n";
     }
}

void BuildIn::waitingFor(string command, int pid[], int fd[], int fd2[]){
    int status;
    if(fd[1]!=-1){close(fd[1]);}
    if(fd[0]!=-1){close(fd[0]);}
    if(fd2[1]!=-1){close(fd2[1]);}
    if(fd2[0]!=-1){close(fd2[0]);}
    for(int i=0;i<3;i++){
        if(pid[i]!=-1){
            if(waitpid(pid[i],&status,WUNTRACED)!=pid[i]){
                    cout << "Error: waitpid error\n";
            }else{
                if(WIFSTOPPED(status)){
                    if(i==0){
                        storeJob(command,pid,fd,fd2);
                    }
                }
            }
        }
    }
}

void BuildIn::handleFG(command thisCommand){
    if(thisCommand.tokLen==2){
    int index=atoi(thisCommand.toks[1]->tok.c_str());
    if(index<numJob || index >0){
        Jobs* head=jobs;
        for(int i=0;i<index;i++){
            head=head->next;
        }
        string cCommand;
        int cfd[2]={-1,-1};
        int cfd2[2]={-1,-1};
        int cpids[3]={-1,-1,-1};

        cCommand=head->command;
        cfd[0]=head->fd[0];
        cfd[1]=head->fd[1];
        cfd2[0]=head->fd2[0];
        cfd2[1]=head->fd2[1];
        for(int j=0;j<3;j++){
            cpids[j]=head->pids[j];
            if(head->pids[j]!=-1){
            cout << "Job wake up: " << head->command << "\n";
            if(kill(head->pids[0],SIGCONT)==-1){
                cout << "Error: Cannot send kill signal\n";
            }
            }
        }
        if(head->next==NULL){
            free(head);
        }else{
            Jobs* temp=head->next;
            head->command=temp->command;
            head->pids[0]=temp->pids[0];
            head->pids[1]=temp->pids[1];
            head->pids[2]=temp->pids[2];
            head->fd[0]=temp->fd[0];
            head->fd[1]=temp->fd[1];
            head->fd2[0]=temp->fd2[0];
            head->fd2[1]=temp->fd2[1];
            head->next=temp->next;
            free(temp);
        }
        numJob--;
        waitingFor(cCommand,cpids,cfd,cfd2);
    }else{
        cout << "fg: no such job\n";
    }
    }else{
        cout << "fg: wrong number of arguments\n";
    }
}
void BuildIn::handleJobs(command thisCommand){
    if(thisCommand.tokLen<2){
    if(numJob>0){
        Jobs* head=jobs;
        int count=1;
        while(head!=NULL && head->next!=NULL){
            head=head->next;
            cout << "[" << count++ << "] " << head->command << "\n";
        }
    }else{
        cout << "No suspended jobs\n";
    }
    }else{
        cout << "jobs: wrong number of arguments\n";
    }
}

int BuildIn::storeJob(string command, int pid[],int fd[],int fd2[]){
    int size;
    size=sizeof pid/sizeof(int);
    if(size>3){return -1;}
    Jobs* head=jobs;

    int count=0;
    while(head->next!=NULL){
        head=head->next;
    }
    Jobs* temp=new Jobs();
    temp->command=command;
    temp->next=NULL;
    temp->pids[0]=pid[0];
    temp->pids[1]=pid[1];
    temp->pids[2]=pid[2];
    temp->fd[0]=fd[0];
    temp->fd[1]=fd[1];
    temp->fd2[0]=fd2[0];
    temp->fd2[1]=fd2[1];
    head->next=temp;
    numJob++;
    return 0;
}
Jobs::Jobs(){
    for(int i=0;i<3;i++){
        pids[i]=0;
    }
    command="";
    fd[0]=-1;
    fd[1]=-1;
    fd2[0]=-1;
    fd2[1]=-1;
}

string Jobs::getCommand(){
    return command;
}
int Jobs::getPid(int index){
    if(index>2){return -1;}
    return pids[index];
}
<commit_msg>Update build in!<commit_after>#include "BuildIn.h"
#include "Interpreter.h"
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>

BuildIn::BuildIn(){
    numJob=0;
    jobs=new Jobs();
    jobs->next=NULL;
}

string BuildIn::getCurrentDic(){
    char cwd[1000];
    if(!getcwd(cwd,1000)){
        perror("Error: Cannot obtain current working directory");
        exit(0);
    }
    return string(cwd);
}
void BuildIn::handleCD(command thisCommand){
    if(thisCommand.tokLen==2){
        string path=thisCommand.toks[1]->tok;
        string finalPath;
        if(path[0]=='/'){
            finalPath=path;
        }else if(((path.length()>1) && path[0]=='.' && path[1]=='/') || (path[0]=='.' && (path.length()==1))){
            finalPath=getCurrentDic();
            string rest=path.substr(1,path.length());
            finalPath.append(rest);
        }else if(((path.length()>2) && path[0]=='.' && path[1]=='.' && path[2]=='/') || (path[0]=='.' && path[1]=='.' && path.length()==2)){
            finalPath=getCurrentDic();
            int found=finalPath.find_last_of("/");
            finalPath=finalPath.substr(0,found);
            finalPath.append(path.substr(2,path.length()));
        }else{
            finalPath=getCurrentDic();
            finalPath.append("/");
            finalPath.append(path);
        }
        const char *pathTemp=finalPath.c_str();
        int ret=chdir(pathTemp);
        if(ret){
            cout << "[" << path << "]: cannot change directory\n";
        }
    }else{
        cout << "cd: wrong number of arguments\n";
    }
}

void BuildIn::handleExit(command thisCommand){
     if(thisCommand.tokLen==1){
         if(numJob>0){
             cout << "There is at least one suspended job\n";
         }else{
             exit(0);
         }
     }else{
         cout << "exit: wrong number of arguments\n";
     }
}

void BuildIn::waitingFor(string command, int pid[], int fd[], int fd2[]){
    int status;
    if(fd[1]!=-1){close(fd[1]);}
    if(fd[0]!=-1){close(fd[0]);}
    if(fd2[1]!=-1){close(fd2[1]);}
    if(fd2[0]!=-1){close(fd2[0]);}
    for(int i=0;i<3;i++){
        if(pid[i]!=-1){
            if(waitpid(pid[i],&status,WUNTRACED)!=pid[i]){
                    cout << "Error: waitpid error\n";
            }else{
                if(WIFSTOPPED(status)){
                    if(i==0){
                        storeJob(command,pid,fd,fd2);
                    }
                }
            }
        }
    }
}

void BuildIn::handleFG(command thisCommand){
    if(thisCommand.tokLen==2){
    int index=atoi(thisCommand.toks[1]->tok.c_str());
    cout << numJob << "\n";
    if(index<numJob && index >0){
        Jobs* head=jobs;
        Jobs* previous=jobs;
        for(int i=0;i<index;i++){
            head=head->next;
            if(i>0){
                previous=previous->next;
            }
        }
        string cCommand;
        int cfd[2]={-1,-1};
        int cfd2[2]={-1,-1};
        int cpids[3]={-1,-1,-1};

        cCommand=head->command;
        cfd[0]=head->fd[0];
        cfd[1]=head->fd[1];
        cfd2[0]=head->fd2[0];
        cfd2[1]=head->fd2[1];
        for(int j=0;j<3;j++){
            cpids[j]=head->pids[j];
            if(head->pids[j]!=-1){
            cout << "Job wake up: " << head->command << "\n";
            if(kill(head->pids[j],SIGCONT)==-1){
                cout << "Error: Cannot send kill signal\n";
            }
            }
        }
        if(head->next==NULL){
            free(head);
        }else{
            previous->next=head->next;
        }
        numJob--;
        waitingFor(cCommand,cpids,cfd,cfd2);
    }else{
        cout << "fg: no such job\n";
    }
    }else{
        cout << "fg: wrong number of arguments\n";
    }
}
void BuildIn::handleJobs(command thisCommand){
    if(thisCommand.tokLen<2){
    if(numJob>0){
        Jobs* head=jobs;
        int count=1;
        while(head!=NULL && head->next!=NULL){
            head=head->next;
            cout << "[" << count++ << "] " << head->command << "\n";
        }
    }else{
        cout << "No suspended jobs\n";
    }
    }else{
        cout << "jobs: wrong number of arguments\n";
    }
}

int BuildIn::storeJob(string command, int pid[],int fd[],int fd2[]){
    int size;
    size=sizeof pid/sizeof(int);
    if(size>3){return -1;}
    Jobs* head=jobs;

    int count=0;
    while(head->next!=NULL){
        head=head->next;
    }
    Jobs* temp=new Jobs();
    temp->command=command;
    temp->next=NULL;
    temp->pids[0]=pid[0];
    temp->pids[1]=pid[1];
    temp->pids[2]=pid[2];
    temp->fd[0]=fd[0];
    temp->fd[1]=fd[1];
    temp->fd2[0]=fd2[0];
    temp->fd2[1]=fd2[1];
    head->next=temp;
    numJob++;
    return 0;
}
Jobs::Jobs(){
    for(int i=0;i<3;i++){
        pids[i]=0;
    }
    command="";
    fd[0]=-1;
    fd[1]=-1;
    fd2[0]=-1;
    fd2[1]=-1;
}

string Jobs::getCommand(){
    return command;
}
int Jobs::getPid(int index){
    if(index>2){return -1;}
    return pids[index];
}
<|endoftext|>


<commit_before>/*
    irceditaccountwidget.cpp - IRC Account Widget

    Copyright (c) 2003 by Olivier Goffart  <ogoffart@tiscalinet.be>
    Copyright (c) 2003 by Jason Keirstead  <jason@keirstead.org>

    Kopete    (c) 2003 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * 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.                                   *
    *                                                                       *
    *************************************************************************
*/
#include <kmessagebox.h>
#include <klocale.h>
#include <klistview.h>
#include <kdebug.h>
#include <kextsock.h>
#include <kconfig.h>
#include <kglobal.h>
#include <kcharsets.h>

#include <qlabel.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qcheckbox.h>
#include <qconnection.h>
#include <qvalidator.h>
#include <qcombobox.h>
#include <qlistbox.h>
#include <qlineedit.h>

#include "kirc.h"
#include "ircaccount.h"
#include "ircprotocol.h"
#include "irceditaccountwidget.h"

IRCEditAccountWidget::IRCEditAccountWidget(IRCProtocol *proto, IRCAccount *ident, QWidget *parent, const char * )
				  : IRCEditAccountBase(parent), KopeteEditAccountWidget(ident)
{
	mProtocol = proto;

	m_IRCAccount = (IRCAccount *)ident;
	int currentCodec = 4;

	if( m_IRCAccount )
	{
		QString nickName = m_IRCAccount->accountId().section( '@', 0, 0);
		QString serverInfo = m_IRCAccount->accountId().section( '@', 1);

		mNickName->setText( nickName );

		mUserName->setText( m_IRCAccount->userName() );
		mAltNickname->setText( m_IRCAccount->altNick() );
		partMessage->setText( m_IRCAccount->defaultPart() );
		quitMessage->setText( m_IRCAccount->defaultQuit() );
		if( m_IRCAccount->codec() )
			currentCodec = m_IRCAccount->codec()->mibEnum();

		//if(account()->rememberPassword()) mPassword->setText( m_IRCAccount->password() );

		QStringList cmds = m_IRCAccount->connectCommands();
		for( QStringList::Iterator i = cmds.begin(); i != cmds.end(); ++i )
			new QListViewItem( commandList, *i );

		const QMap< QString, QString > replies = m_IRCAccount->customCtcpReplies();
		for( QMap< QString, QString >::ConstIterator it = replies.begin(); it != replies.end(); ++it )
			new QListViewItem( ctcpList, it.key(), it.data() );
	}

	mUserName->setValidator( new QRegExpValidator( QString::fromLatin1("^[^\\s]*$"), mUserName ) );
	mNickName->setValidator( new QRegExpValidator( QString::fromLatin1("^[^#+&][^\\s]*$"), mUserName ) );
	mAltNickname->setValidator( new QRegExpValidator( QString::fromLatin1("^[^#+&][^\\s]*$"), mUserName ) );

	KCharsets *c = KGlobal::charsets();
	charset->insertStringList( c->availableEncodingNames() );

	for( int i = 0; i < charset->count(); ++i )
	{
		if( c->codecForName( charset->text(i) )->mibEnum() == currentCodec )
		{
			charset->setCurrentItem( i );
			break;
		}
	}

	connect( commandList, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ),
		this, SLOT( slotCommandContextMenu( KListView *, QListViewItem *, const QPoint & ) ) );

	connect( ctcpList, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ),
		this, SLOT( slotCtcpContextMenu( KListView *, QListViewItem *, const QPoint & ) ) );

	connect( addButton, SIGNAL( clicked() ), this, SLOT( slotAddCommand() ) );
	connect( editButton, SIGNAL( clicked() ), this, SLOT(slotEditNetworks() ) );
	connect( addReply, SIGNAL( clicked() ), this, SLOT( slotAddCtcp() ) );

	connect( network, SIGNAL( activated( const QString & ) ),
		this, SLOT( slotUpdateNetworkDescription( const QString &) ) );

	connect( IRCProtocol::protocol(), SIGNAL( networkConfigUpdated() ),
		this, SLOT( slotUpdateNetworks() ) );

	slotUpdateNetworks();
}

IRCEditAccountWidget::~IRCEditAccountWidget()
{
}

void IRCEditAccountWidget::slotUpdateNetworks()
{
	network->clear();

	uint i = 0;
	for( QDictIterator<IRCNetwork> it( IRCProtocol::protocol()->networks() ); it.current(); ++it )
	{
		network->insertItem( it.current()->name );
		if( m_IRCAccount && m_IRCAccount->networkName() == it.current()->name )
		{
			network->setCurrentItem( i );
			description->setText( it.current()->description );
		}
		++i;
	}
}

void IRCEditAccountWidget::slotEditNetworks()
{
	IRCProtocol::protocol()->editNetworks( network->currentText() );
}

void IRCEditAccountWidget::slotUpdateNetworkDescription( const QString &network )
{
	description->setText(
		IRCProtocol::protocol()->networks()[ network ]->description
	);
}

void IRCEditAccountWidget::slotCommandContextMenu( KListView *, QListViewItem *item, const QPoint &p )
{
	QPopupMenu popup;
	popup.insertItem( i18n("Remove Command"), 1 );
	if( popup.exec( p ) == 1 )
		delete item;
}

void IRCEditAccountWidget::slotCtcpContextMenu( KListView *, QListViewItem *item, const QPoint &p )
{
	QPopupMenu popup;
	popup.insertItem( i18n("Remove CTCP Reply"), 1 );
	if( popup.exec( p ) == 1 )
		delete item;
}

void IRCEditAccountWidget::slotAddCommand()
{
    if ( !commandEdit->text().isEmpty() )
    {
	new QListViewItem( commandList, commandEdit->text() );
	commandEdit->clear();
    }
}

void IRCEditAccountWidget::slotAddCtcp()
{
    if (  !newCTCP->text().isEmpty() && !newReply->text().isEmpty() )
    {
	new QListViewItem( ctcpList, newCTCP->text(), newReply->text() );
	newCTCP->clear();
	newReply->clear();
    }
}

QString IRCEditAccountWidget::generateAccountId( const QString &network )
{
	KConfig *config = KGlobal::config();
	QString nextId = network;

	uint accountNumber = 1;
	while( config->hasGroup( nextId ) )
	{
		nextId = QString::fromLatin1("%1_%2").arg(network).arg(++accountNumber);
		accountNumber++;
	}

	return nextId;
}

KopeteAccount *IRCEditAccountWidget::apply()
{
	QString nickName = mNickName->text();
	QString networkName = network->currentText();

	if( !m_IRCAccount )
	{
		m_IRCAccount = new IRCAccount( mProtocol, generateAccountId(networkName) );

		m_IRCAccount->setNickName( nickName );
		m_IRCAccount->setNetwork( networkName );
		m_IRCAccount->setUserName( mUserName->text() );
		m_IRCAccount->setDefaultPart( partMessage->text() );
		m_IRCAccount->setDefaultQuit( quitMessage->text() );
		m_IRCAccount->setAutoLogin( autoConnect->isChecked() );
		m_IRCAccount->setAltNick( mAltNickname->text() );

		m_IRCAccount->loaded();
	}

	QStringList cmds;
	for( QListViewItem *i = commandList->firstChild(); i; i = i->nextSibling() )
		cmds.append( i->text(0) );

	QMap< QString, QString > replies;
	for( QListViewItem *i = ctcpList->firstChild(); i; i = i->nextSibling() )
		replies[ i->text(0) ] = i->text(1);

	m_IRCAccount->setCustomCtcpReplies( replies );
	m_IRCAccount->setConnectCommands( cmds );

	KCharsets *c = KGlobal::charsets();
	m_IRCAccount->setCodec( c->codecForName( c->encodingForName( charset->currentText() ) ) );

	return m_IRCAccount;
}

bool IRCEditAccountWidget::validateData()
{
	if( mNickName->text().isEmpty() )
		KMessageBox::sorry(this, i18n("<qt>You must enter a nickname.</qt>"), i18n("Kopete"));
	else
		return true;

	return false;
}

#include "irceditaccountwidget.moc"
<commit_msg>Fix network order and save a few more settings. More to come.<commit_after>/*
    irceditaccountwidget.cpp - IRC Account Widget

    Copyright (c) 2003 by Olivier Goffart  <ogoffart@tiscalinet.be>
    Copyright (c) 2003 by Jason Keirstead  <jason@keirstead.org>

    Kopete    (c) 2003 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * 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.                                   *
    *                                                                       *
    *************************************************************************
*/
#include <kmessagebox.h>
#include <klocale.h>
#include <klistview.h>
#include <kdebug.h>
#include <kextsock.h>
#include <kconfig.h>
#include <kglobal.h>
#include <kcharsets.h>

#include <qlabel.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qcheckbox.h>
#include <qconnection.h>
#include <qvalidator.h>
#include <qcombobox.h>
#include <qlistbox.h>
#include <qlineedit.h>

#include "kirc.h"
#include "ircaccount.h"
#include "ircusercontact.h"
#include "ircprotocol.h"
#include "irceditaccountwidget.h"

IRCEditAccountWidget::IRCEditAccountWidget(IRCProtocol *proto, IRCAccount *ident, QWidget *parent, const char * )
				  : IRCEditAccountBase(parent), KopeteEditAccountWidget(ident)
{
	mProtocol = proto;

	m_IRCAccount = (IRCAccount *)ident;
	int currentCodec = 4;

	if( m_IRCAccount )
	{
		QString nickName = m_IRCAccount->mySelf()->nickName();
		QString serverInfo = m_IRCAccount->accountId();

		mNickName->setText( nickName );

		mUserName->setText( m_IRCAccount->userName() );
		mAltNickname->setText( m_IRCAccount->altNick() );
		partMessage->setText( m_IRCAccount->defaultPart() );
		quitMessage->setText( m_IRCAccount->defaultQuit() );
		if( m_IRCAccount->codec() )
			currentCodec = m_IRCAccount->codec()->mibEnum();

// 		mPass->load ( &m_IRCAccount->password() );
//
// 		cbUseSSL->setChecked (account()->pluginData (m_protocol, "UseSSL") == QString::fromLatin1("true"));

		//if(account()->rememberPassword()) mPassword->setText( m_IRCAccount->password() );

		QStringList cmds = m_IRCAccount->connectCommands();
		for( QStringList::Iterator i = cmds.begin(); i != cmds.end(); ++i )
			new QListViewItem( commandList, *i );

		const QMap< QString, QString > replies = m_IRCAccount->customCtcpReplies();
		for( QMap< QString, QString >::ConstIterator it = replies.begin(); it != replies.end(); ++it )
			new QListViewItem( ctcpList, it.key(), it.data() );
	}

	mUserName->setValidator( new QRegExpValidator( QString::fromLatin1("^[^\\s]*$"), mUserName ) );
	mNickName->setValidator( new QRegExpValidator( QString::fromLatin1("^[^#+&][^\\s]*$"), mUserName ) );
	mAltNickname->setValidator( new QRegExpValidator( QString::fromLatin1("^[^#+&][^\\s]*$"), mUserName ) );

	KCharsets *c = KGlobal::charsets();
	charset->insertStringList( c->availableEncodingNames() );

	for( int i = 0; i < charset->count(); ++i )
	{
		if( c->codecForName( charset->text(i) )->mibEnum() == currentCodec )
		{
			charset->setCurrentItem( i );
			break;
		}
	}

	connect( commandList, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ),
		this, SLOT( slotCommandContextMenu( KListView *, QListViewItem *, const QPoint & ) ) );

	connect( ctcpList, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ),
		this, SLOT( slotCtcpContextMenu( KListView *, QListViewItem *, const QPoint & ) ) );

	connect( addButton, SIGNAL( clicked() ), this, SLOT( slotAddCommand() ) );
	connect( editButton, SIGNAL( clicked() ), this, SLOT(slotEditNetworks() ) );
	connect( addReply, SIGNAL( clicked() ), this, SLOT( slotAddCtcp() ) );

	connect( network, SIGNAL( activated( const QString & ) ),
		this, SLOT( slotUpdateNetworkDescription( const QString &) ) );

	connect( IRCProtocol::protocol(), SIGNAL( networkConfigUpdated() ),
		this, SLOT( slotUpdateNetworks() ) );

	slotUpdateNetworks();
}

IRCEditAccountWidget::~IRCEditAccountWidget()
{
}

void IRCEditAccountWidget::slotUpdateNetworks()
{
	network->clear();

	uint i = 0;
	QStringList keys;
	for( QDictIterator<IRCNetwork> it( IRCProtocol::protocol()->networks() ); it.current(); ++it )
		keys.append( it.currentKey() );

	keys.sort();

	QStringList::Iterator end = keys.end();
	for( QStringList::Iterator it = keys.begin(); it != end; ++it )
	{
		IRCNetwork * current = IRCProtocol::protocol()->networks()[*it];
		network->insertItem( current->name );
		if( m_IRCAccount && m_IRCAccount->networkName() == current->name )
		{
			network->setCurrentItem( i );
			description->setText( current->description );
		}
		++i;
	}
}

void IRCEditAccountWidget::slotEditNetworks()
{
	IRCProtocol::protocol()->editNetworks( network->currentText() );
}

void IRCEditAccountWidget::slotUpdateNetworkDescription( const QString &network )
{
	description->setText(
		IRCProtocol::protocol()->networks()[ network ]->description
	);
}

void IRCEditAccountWidget::slotCommandContextMenu( KListView *, QListViewItem *item, const QPoint &p )
{
	QPopupMenu popup;
	popup.insertItem( i18n("Remove Command"), 1 );
	if( popup.exec( p ) == 1 )
		delete item;
}

void IRCEditAccountWidget::slotCtcpContextMenu( KListView *, QListViewItem *item, const QPoint &p )
{
	QPopupMenu popup;
	popup.insertItem( i18n("Remove CTCP Reply"), 1 );
	if( popup.exec( p ) == 1 )
		delete item;
}

void IRCEditAccountWidget::slotAddCommand()
{
    if ( !commandEdit->text().isEmpty() )
    {
	new QListViewItem( commandList, commandEdit->text() );
	commandEdit->clear();
    }
}

void IRCEditAccountWidget::slotAddCtcp()
{
    if (  !newCTCP->text().isEmpty() && !newReply->text().isEmpty() )
    {
	new QListViewItem( ctcpList, newCTCP->text(), newReply->text() );
	newCTCP->clear();
	newReply->clear();
    }
}

QString IRCEditAccountWidget::generateAccountId( const QString &network )
{
	KConfig *config = KGlobal::config();
	QString nextId = network;

	uint accountNumber = 1;
	while( config->hasGroup( nextId ) )
	{
		nextId = QString::fromLatin1("%1_%2").arg(network).arg(++accountNumber);
		accountNumber++;
	}

	return nextId;
}

KopeteAccount *IRCEditAccountWidget::apply()
{
	QString nickName = mNickName->text();
	QString networkName = network->currentText();

	if( !m_IRCAccount )
	{
		m_IRCAccount = new IRCAccount( mProtocol, generateAccountId(networkName) );

		m_IRCAccount->setNetwork( networkName );

		m_IRCAccount->loaded();
	}

//	mPass->save( &m_IRCAccount->password() );

	m_IRCAccount->setNickName( nickName );
	m_IRCAccount->setUserName( mUserName->text() );
	m_IRCAccount->setAltNick( mAltNickname->text() );
	m_IRCAccount->setDefaultPart( partMessage->text() );
	m_IRCAccount->setDefaultQuit( quitMessage->text() );
	// Doesn't work
	//m_IRCAccount->setAutoLogin( autoConnect->isChecked() );
	// what about?:
	// password - No time to sort out the password handling or move to KopetePasswordedAccount before 3.3
	// remember password cb - disabling the UI for this.
	// prefer SSL
	// default charset

	QStringList cmds;
	for( QListViewItem *i = commandList->firstChild(); i; i = i->nextSibling() )
		cmds.append( i->text(0) );

	QMap< QString, QString > replies;
	for( QListViewItem *i = ctcpList->firstChild(); i; i = i->nextSibling() )
		replies[ i->text(0) ] = i->text(1);

	m_IRCAccount->setCustomCtcpReplies( replies );
	m_IRCAccount->setConnectCommands( cmds );

	KCharsets *c = KGlobal::charsets();
	m_IRCAccount->setCodec( c->codecForName( c->encodingForName( charset->currentText() ) ) );

	return m_IRCAccount;
}

bool IRCEditAccountWidget::validateData()
{
	if( mNickName->text().isEmpty() )
		KMessageBox::sorry(this, i18n("<qt>You must enter a nickname.</qt>"), i18n("Kopete"));
	else
		return true;

	return false;
}

#include "irceditaccountwidget.moc"
<|endoftext|>


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

#pragma once

#include <atomic>
#include <deque>
#include <iostream>
#include <memory>
#include <set>
#include <string>
#include <typeindex>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#include "ngraph/autodiff/adjoints.hpp"
#include "ngraph/descriptor/input.hpp"
#include "ngraph/descriptor/output.hpp"
#include "ngraph/descriptor/tensor.hpp"
#include "ngraph/node_vector.hpp"
#include "ngraph/placement.hpp"
#include "ngraph/types/type.hpp"

namespace ngraph
{
    namespace op
    {
        class Parameter;
    }

    void replace_node_users_arguments(std::shared_ptr<Node> target,
                                      std::shared_ptr<Node> replacement);

    void insert_parameter_split_between(std::shared_ptr<Node> src_node,
                                        std::shared_ptr<Node> dst_node,
                                        std::shared_ptr<op::Parameter> p_node);

    /// Nodes are the backbone of the graph of Value dataflow. Every node has
    /// zero or more nodes as arguments and one value, which is either a tensor
    /// view or a (possibly empty) tuple of values.
    class Node : public std::enable_shared_from_this<Node>
    {
        // So Adjoints can call generate_adjoints
        friend class autodiff::Adjoints;
        friend class descriptor::Input;
        friend void replace_node_users_arguments(std::shared_ptr<Node> target,
                                                 std::shared_ptr<Node> replacement);
        friend void insert_parameter_split_between(std::shared_ptr<Node> src_node,
                                                   std::shared_ptr<Node> dst_node,
                                                   std::shared_ptr<op::Parameter> p_node);

    protected:
        Node(const std::string& node_type, const NodeVector& arguments);
        virtual ~Node()
        {
            for (auto arg : m_arguments)
            {
                arg->m_users.erase(this);
            }
        }
        virtual void generate_adjoints(autodiff::Adjoints& adjoints,
                                       const std::shared_ptr<Node>& delta)
        {
        }

    public:
        /// The class name, must not contain spaces
        std::string description() const { return m_node_type; }
        const std::string& get_friendly_name() const;
        const std::string& get_name() const;
        void set_name(const std::string& name);
        void clear_arguments() { m_arguments.clear(); }
        const std::multiset<Node*>& users() const { return m_users; }
        /// Return true if this has the same implementing class as node. This
        /// will be used by the pattern matcher when comparing a pattern
        /// graph against the graph.
        bool is_same_op_type(const std::shared_ptr<Node>& node) const
        {
            Node* n = node.get();
            return std::type_index(typeid(*this)) == std::type_index(typeid(*n));
        }

        // Set the value type if it has not already been set; otherwise, ensure that
        // value_type agrees with the value type that was set.
        // This is used when the framework specifies a value type for the value, and we
        // independently compute what we thing the value type should be from the arguments.
        void set_value_type_checked(const std::shared_ptr<const TensorViewType>& value_type);
        void set_value_type_checked(const element::Type& element_type, const Shape& shape);

        bool is_parameter() const;
        virtual bool is_output() const;
        virtual bool is_constant() const;
        virtual bool is_commutative() { return false; }
        size_t get_instance_id() const { return m_instance_id; }
        friend std::ostream& operator<<(std::ostream&, const Node&);

        // TODO: Deprecate
        std::deque<descriptor::Input>& get_inputs() { return m_inputs; }
        // TODO: Deprecate
        const std::deque<descriptor::Input>& get_inputs() const { return m_inputs; }
        // Deprecated
        // TODO: Remove from unit tests.
        std::deque<descriptor::Output>& get_outputs();
        // Deprecated
        // TODO: Remove from unit tests.
        const std::deque<descriptor::Output>& get_outputs() const;

        /// Returns the number of outputs on the for the node.
        size_t get_output_size() const;

        /// Returns the element type for output i
        const element::Type& get_output_element_type(size_t i) const;

        /// Checks that there is exactly one output and returns its element type
        const element::Type& get_element_type() const;

        /// Returns the shape for output i
        const Shape& get_output_shape(size_t i) const;

        /// Checks that there is exactly one output and returns its shape
        const Shape& get_shape() const;

        /// Returns the tensor for output i
        descriptor::Tensor& get_output_tensor(size_t i) const;

        /// Checks that there is exactly one output and returns its tensor.
        descriptor::Tensor& get_output_tensor() const;

        /// Returns the tensor view of output i
        std::shared_ptr<descriptor::TensorView> get_output_tensor_view(size_t i) const;

        /// Checks that there is exactly one output and returns its tensor view.
        std::shared_ptr<descriptor::TensorView> get_output_tensor_view() const;

        /// Returns the set of inputs using output i
        const std::set<descriptor::Input*>& get_output_inputs(size_t i) const;

        /// Returns the number of inputs for the op
        size_t get_input_size() const;

        /// Returns the element type of input i
        const element::Type& get_input_element_type(size_t i) const;

        /// Returns the shape of input i
        const Shape& get_input_shape(size_t i) const;

        std::unordered_set<descriptor::Tensor*> liveness_live_list;
        std::unordered_set<descriptor::Tensor*> liveness_new_list;
        std::unordered_set<descriptor::Tensor*> liveness_free_list;

        std::shared_ptr<Node> backprop_node(const std::shared_ptr<Node>& x,
                                            const std::shared_ptr<Node>& c);

        virtual NodeVector get_input_ops(); //const;

        std::shared_ptr<Node> get_input_op(size_t index);

        virtual std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const = 0;

        virtual std::vector<std::shared_ptr<Function>> get_functions() const;

        /// True if this and node have one output with same element type and shape
        bool has_same_type(std::shared_ptr<const Node> node) const;

        /// Get device placement
        Placement get_placement() const;

        /// Set device placement
        void set_placement(Placement placement);

        /// Get input descriptor that is connected to src
        descriptor::Input* get_input_from(const std::shared_ptr<Node>& src);

        /// Get ouput descriptor that outputs to dst
        descriptor::Output* get_output_to(const std::shared_ptr<Node>& dst);

    protected:
        void add_output(const element::Type& element_type, const Shape& shape);

        std::string m_node_type;
        std::multiset<Node*> m_users;
        size_t m_instance_id;
        std::string m_name;
        const std::string m_unique_name;
        static std::atomic<size_t> m_next_instance_id;
        std::deque<descriptor::Input> m_inputs;
        std::deque<descriptor::Output> m_outputs;
        std::unordered_map<Node*, autodiff::Adjoints> m_adjoint_map;
        Placement m_placement = Placement::DEFAULT;

    private:
        NodeVector m_arguments;
        //m_arguments still needs to be kept in sync with i/o since get_input_ops
        //is pretty ubiquitous and might be called after the original graph was modified.
        //get_input_ops uses m_arguments to check if a node view reconstruction from i/o
        //is correct.
        NodeVector& get_arguments_FOR_GRAPH_REWRITE_ONLY() { return m_arguments; }
    };
}
<commit_msg>Cleanup the output descriptor of node arguments (#639)<commit_after>/*******************************************************************************
* Copyright 2017-2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/

#pragma once

#include <atomic>
#include <deque>
#include <iostream>
#include <memory>
#include <set>
#include <string>
#include <typeindex>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#include "ngraph/autodiff/adjoints.hpp"
#include "ngraph/descriptor/input.hpp"
#include "ngraph/descriptor/output.hpp"
#include "ngraph/descriptor/tensor.hpp"
#include "ngraph/node_vector.hpp"
#include "ngraph/placement.hpp"
#include "ngraph/types/type.hpp"

namespace ngraph
{
    namespace op
    {
        class Parameter;
    }

    void replace_node_users_arguments(std::shared_ptr<Node> target,
                                      std::shared_ptr<Node> replacement);

    void insert_parameter_split_between(std::shared_ptr<Node> src_node,
                                        std::shared_ptr<Node> dst_node,
                                        std::shared_ptr<op::Parameter> p_node);

    /// Nodes are the backbone of the graph of Value dataflow. Every node has
    /// zero or more nodes as arguments and one value, which is either a tensor
    /// view or a (possibly empty) tuple of values.
    class Node : public std::enable_shared_from_this<Node>
    {
        // So Adjoints can call generate_adjoints
        friend class autodiff::Adjoints;
        friend class descriptor::Input;
        friend void replace_node_users_arguments(std::shared_ptr<Node> target,
                                                 std::shared_ptr<Node> replacement);
        friend void insert_parameter_split_between(std::shared_ptr<Node> src_node,
                                                   std::shared_ptr<Node> dst_node,
                                                   std::shared_ptr<op::Parameter> p_node);

    protected:
        Node(const std::string& node_type, const NodeVector& arguments);
        virtual ~Node()
        {
            for (auto arg : m_arguments)
            {
                arg->m_users.erase(this);
            }
            for (auto& input : m_inputs)
            {
                input.get_output().remove_input(&input);
            }
        }
        virtual void generate_adjoints(autodiff::Adjoints& adjoints,
                                       const std::shared_ptr<Node>& delta)
        {
        }

    public:
        /// The class name, must not contain spaces
        std::string description() const { return m_node_type; }
        const std::string& get_friendly_name() const;
        const std::string& get_name() const;
        void set_name(const std::string& name);
        void clear_arguments() { m_arguments.clear(); }
        const std::multiset<Node*>& users() const { return m_users; }
        /// Return true if this has the same implementing class as node. This
        /// will be used by the pattern matcher when comparing a pattern
        /// graph against the graph.
        bool is_same_op_type(const std::shared_ptr<Node>& node) const
        {
            Node* n = node.get();
            return std::type_index(typeid(*this)) == std::type_index(typeid(*n));
        }

        // Set the value type if it has not already been set; otherwise, ensure that
        // value_type agrees with the value type that was set.
        // This is used when the framework specifies a value type for the value, and we
        // independently compute what we thing the value type should be from the arguments.
        void set_value_type_checked(const std::shared_ptr<const TensorViewType>& value_type);
        void set_value_type_checked(const element::Type& element_type, const Shape& shape);

        bool is_parameter() const;
        virtual bool is_output() const;
        virtual bool is_constant() const;
        virtual bool is_commutative() { return false; }
        size_t get_instance_id() const { return m_instance_id; }
        friend std::ostream& operator<<(std::ostream&, const Node&);

        // TODO: Deprecate
        std::deque<descriptor::Input>& get_inputs() { return m_inputs; }
        // TODO: Deprecate
        const std::deque<descriptor::Input>& get_inputs() const { return m_inputs; }
        // Deprecated
        // TODO: Remove from unit tests.
        std::deque<descriptor::Output>& get_outputs();
        // Deprecated
        // TODO: Remove from unit tests.
        const std::deque<descriptor::Output>& get_outputs() const;

        /// Returns the number of outputs on the for the node.
        size_t get_output_size() const;

        /// Returns the element type for output i
        const element::Type& get_output_element_type(size_t i) const;

        /// Checks that there is exactly one output and returns its element type
        const element::Type& get_element_type() const;

        /// Returns the shape for output i
        const Shape& get_output_shape(size_t i) const;

        /// Checks that there is exactly one output and returns its shape
        const Shape& get_shape() const;

        /// Returns the tensor for output i
        descriptor::Tensor& get_output_tensor(size_t i) const;

        /// Checks that there is exactly one output and returns its tensor.
        descriptor::Tensor& get_output_tensor() const;

        /// Returns the tensor view of output i
        std::shared_ptr<descriptor::TensorView> get_output_tensor_view(size_t i) const;

        /// Checks that there is exactly one output and returns its tensor view.
        std::shared_ptr<descriptor::TensorView> get_output_tensor_view() const;

        /// Returns the set of inputs using output i
        const std::set<descriptor::Input*>& get_output_inputs(size_t i) const;

        /// Returns the number of inputs for the op
        size_t get_input_size() const;

        /// Returns the element type of input i
        const element::Type& get_input_element_type(size_t i) const;

        /// Returns the shape of input i
        const Shape& get_input_shape(size_t i) const;

        std::unordered_set<descriptor::Tensor*> liveness_live_list;
        std::unordered_set<descriptor::Tensor*> liveness_new_list;
        std::unordered_set<descriptor::Tensor*> liveness_free_list;

        std::shared_ptr<Node> backprop_node(const std::shared_ptr<Node>& x,
                                            const std::shared_ptr<Node>& c);

        virtual NodeVector get_input_ops(); //const;

        std::shared_ptr<Node> get_input_op(size_t index);

        virtual std::shared_ptr<Node> copy_with_new_args(const NodeVector& new_args) const = 0;

        virtual std::vector<std::shared_ptr<Function>> get_functions() const;

        /// True if this and node have one output with same element type and shape
        bool has_same_type(std::shared_ptr<const Node> node) const;

        /// Get device placement
        Placement get_placement() const;

        /// Set device placement
        void set_placement(Placement placement);

        /// Get input descriptor that is connected to src
        descriptor::Input* get_input_from(const std::shared_ptr<Node>& src);

        /// Get ouput descriptor that outputs to dst
        descriptor::Output* get_output_to(const std::shared_ptr<Node>& dst);

    protected:
        void add_output(const element::Type& element_type, const Shape& shape);

        std::string m_node_type;
        std::multiset<Node*> m_users;
        size_t m_instance_id;
        std::string m_name;
        const std::string m_unique_name;
        static std::atomic<size_t> m_next_instance_id;
        std::deque<descriptor::Input> m_inputs;
        std::deque<descriptor::Output> m_outputs;
        std::unordered_map<Node*, autodiff::Adjoints> m_adjoint_map;
        Placement m_placement = Placement::DEFAULT;

    private:
        NodeVector m_arguments;
        //m_arguments still needs to be kept in sync with i/o since get_input_ops
        //is pretty ubiquitous and might be called after the original graph was modified.
        //get_input_ops uses m_arguments to check if a node view reconstruction from i/o
        //is correct.
        NodeVector& get_arguments_FOR_GRAPH_REWRITE_ONLY() { return m_arguments; }
    };
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MutableAttrList.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:48:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/

#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#define _XMLOFF_MUTABLEATTRLIST_HXX

#ifndef _COM_SUN_STAR_UTIL_XCLONEABLE_HPP_
#include <com/sun/star/util/XCloneable.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif

#include <cppuhelper/implbase3.hxx>

class SvXMLAttributeList;

class XMLMutableAttributeList : public ::cppu::WeakImplHelper3<
        ::com::sun::star::xml::sax::XAttributeList,
        ::com::sun::star::util::XCloneable,
        ::com::sun::star::lang::XUnoTunnel>
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XAttributeList> m_xAttrList;

    SvXMLAttributeList *m_pMutableAttrList;

    SvXMLAttributeList *GetMutableAttrList();

public:
    XMLMutableAttributeList();
    XMLMutableAttributeList( const ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XAttributeList> & rAttrList,
           sal_Bool bClone=sal_False );
    ~XMLMutableAttributeList();

    static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId() throw();
    static XMLMutableAttributeList* getImplementation( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > ) throw();

    // XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::xml::sax::XAttributeList
    virtual sal_Int16 SAL_CALL getLength(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::rtl::OUString SAL_CALL getNameByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::rtl::OUString SAL_CALL getTypeByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::rtl::OUString SAL_CALL getTypeByName(const ::rtl::OUString& aName) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::rtl::OUString SAL_CALL getValueByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::rtl::OUString SAL_CALL getValueByName(const ::rtl::OUString& aName) throw( ::com::sun::star::uno::RuntimeException );

    // ::com::sun::star::util::XCloneable
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone()   throw( ::com::sun::star::uno::RuntimeException );

    // methods that are not contained in any interface
    void SetValueByIndex( sal_Int16 i, const ::rtl::OUString& rValue );
    void AddAttribute( const ::rtl::OUString &sName , const ::rtl::OUString &sValue );
//  void Clear();
    void RemoveAttributeByIndex( sal_Int16 i );
    void RenameAttributeByIndex( sal_Int16 i, const ::rtl::OUString& rNewName );
//  void SetAttributeList( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & );
    void AppendAttributeList( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & );

    sal_Int16 GetIndexByName( const ::rtl::OUString& rName ) const;
};

#endif  //  _XMLOFF_MUTABLEATTRLIST_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.3.450); FILE MERGED 2008/04/01 13:05:47 thb 1.3.450.2: #i85898# Stripping all external header guards 2008/03/31 16:28:51 rt 1.3.450.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: MutableAttrList.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#define _XMLOFF_MUTABLEATTRLIST_HXX

#include <com/sun/star/util/XCloneable.hpp>
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#include <com/sun/star/lang/XUnoTunnel.hpp>

#include <cppuhelper/implbase3.hxx>

class SvXMLAttributeList;

class XMLMutableAttributeList : public ::cppu::WeakImplHelper3<
        ::com::sun::star::xml::sax::XAttributeList,
        ::com::sun::star::util::XCloneable,
        ::com::sun::star::lang::XUnoTunnel>
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XAttributeList> m_xAttrList;

    SvXMLAttributeList *m_pMutableAttrList;

    SvXMLAttributeList *GetMutableAttrList();

public:
    XMLMutableAttributeList();
    XMLMutableAttributeList( const ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XAttributeList> & rAttrList,
           sal_Bool bClone=sal_False );
    ~XMLMutableAttributeList();

    static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId() throw();
    static XMLMutableAttributeList* getImplementation( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > ) throw();

    // XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::xml::sax::XAttributeList
    virtual sal_Int16 SAL_CALL getLength(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::rtl::OUString SAL_CALL getNameByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::rtl::OUString SAL_CALL getTypeByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::rtl::OUString SAL_CALL getTypeByName(const ::rtl::OUString& aName) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::rtl::OUString SAL_CALL getValueByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::rtl::OUString SAL_CALL getValueByName(const ::rtl::OUString& aName) throw( ::com::sun::star::uno::RuntimeException );

    // ::com::sun::star::util::XCloneable
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone()   throw( ::com::sun::star::uno::RuntimeException );

    // methods that are not contained in any interface
    void SetValueByIndex( sal_Int16 i, const ::rtl::OUString& rValue );
    void AddAttribute( const ::rtl::OUString &sName , const ::rtl::OUString &sValue );
//  void Clear();
    void RemoveAttributeByIndex( sal_Int16 i );
    void RenameAttributeByIndex( sal_Int16 i, const ::rtl::OUString& rNewName );
//  void SetAttributeList( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & );
    void AppendAttributeList( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & );

    sal_Int16 GetIndexByName( const ::rtl::OUString& rName ) const;
};

#endif  //  _XMLOFF_MUTABLEATTRLIST_HXX
<|endoftext|>


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

/*!
 * Copyright (c) 2015 by Contributors
 * \file rnn.cc
 * \brief
 * \author Sebastian Bodenstein
*/
#include "./rnn-inl.h"

namespace mxnet {
namespace op {
template<>
Operator *CreateOp<cpu>(RNNParam param, int dtype) {
  Operator *op = NULL;
  MSHADOW_REAL_TYPE_SWITCH(dtype, DType, {
    op = new RNNOp<DType>(param);
  });
  return op;
}

Operator *RNNProp::CreateOperatorEx(Context ctx,
                                  std::vector<TShape> *in_shape,
                                  std::vector<int> *in_type) const {
  DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0]);
}

DMLC_REGISTER_PARAMETER(RNNParam);

MXNET_REGISTER_OP_PROPERTY(RNN, RNNProp)
.describe(R"code(Applies recurrent layers to input.
Currently, vanilla RNN, LSTM and GRU are implemented, with
 both multi-layer and bidirectional support.
**Vanilla RNN**
Applies a single-gate recurrent layer to input X. Two kinds of
 activation function are supported: ReLU and tanh.

ReLU activation function:

.. math::
    $h_t = relu(w_{ih} * x_t + b_{ih}  +  w_{hh} * h_{(t-1)} + b_{hh})$

Tanh activtion function:

.. math::
   $h_t = \tanh(w_{ih} * x_t + b_{ih}  +  w_{hh} * h_{(t-1)} + b_{hh})$

Reference paper: Finding structure in time - Elman, 1988.
 https://crl.ucsd.edu/~elman/Papers/fsit.pdf

**LSTM**
Long Short-Term Memory - Hochreiter, 1997.

.. math::
  \begin{array}{ll}
            i_t = \mathrm{sigmoid}(W_{ii} x_t + b_{ii} + W_{hi} h_{(t-1)} + b_{hi}) \\
            f_t = \mathrm{sigmoid}(W_{if} x_t + b_{if} + W_{hf} h_{(t-1)} + b_{hf}) \\
            g_t = \tanh(W_{ig} x_t + b_{ig} + W_{hc} h_{(t-1)} + b_{hg}) \\
            o_t = \mathrm{sigmoid}(W_{io} x_t + b_{io} + W_{ho} h_{(t-1)} + b_{ho}) \\
            c_t = f_t * c_{(t-1)} + i_t * g_t \\
            h_t = o_t * \tanh(c_t)
            \end{array}

**GRU**
Gated Recurrent Unit - Cho et al. 2014.
http://arxiv.org/abs/1406.1078

.. math::
\begin{array}{ll}
            r_t = \mathrm{sigmoid}(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\
            z_t = \mathrm{sigmoid}(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\
            n_t = \tanh(W_{in} x_t + b_{in} + r_t * (W_{hn} h_{(t-1)}+ b_{hn})) \\
            h_t = (1 - z_t) * n_t + z_t * h_{(t-1)} \\
            \end{array})code")
.add_argument("data", "NDArray-or-Symbol", "Input data to RNN")
.add_argument("parameters", "NDArray-or-Symbol",
              "Vector of all RNN trainable parameters concatenated")
.add_argument("state", "NDArray-or-Symbol", "initial hidden state of the RNN")
.add_argument("state_cell", "NDArray-or-Symbol",
              "initial cell state for LSTM networks (only for LSTM)")
.add_arguments(RNNParam::__FIELDS__());
}  // namespace op
}  // namespace mxnet
<commit_msg>fix doc of sym.RNN (#11135)<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*!
 * Copyright (c) 2015 by Contributors
 * \file rnn.cc
 * \brief
 * \author Sebastian Bodenstein
*/
#include "./rnn-inl.h"

namespace mxnet {
namespace op {
template<>
Operator *CreateOp<cpu>(RNNParam param, int dtype) {
  Operator *op = NULL;
  MSHADOW_REAL_TYPE_SWITCH(dtype, DType, {
    op = new RNNOp<DType>(param);
  });
  return op;
}

Operator *RNNProp::CreateOperatorEx(Context ctx,
                                  std::vector<TShape> *in_shape,
                                  std::vector<int> *in_type) const {
  DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0]);
}

DMLC_REGISTER_PARAMETER(RNNParam);

MXNET_REGISTER_OP_PROPERTY(RNN, RNNProp)
.describe(R"code(Applies recurrent layers to input data. Currently, vanilla RNN, LSTM and GRU are
implemented, with both multi-layer and bidirectional support.

**Vanilla RNN**

Applies a single-gate recurrent layer to input X. Two kinds of activation function are supported:
ReLU and Tanh.

With ReLU activation function:

.. math::
    h_t = relu(W_{ih} * x_t + b_{ih}  +  W_{hh} * h_{(t-1)} + b_{hh})

With Tanh activtion function:

.. math::
    h_t = \tanh(W_{ih} * x_t + b_{ih}  +  W_{hh} * h_{(t-1)} + b_{hh})

Reference paper: Finding structure in time - Elman, 1988.
https://crl.ucsd.edu/~elman/Papers/fsit.pdf

**LSTM**

Long Short-Term Memory - Hochreiter, 1997. http://www.bioinf.jku.at/publications/older/2604.pdf

.. math::
  \begin{array}{ll}
            i_t = \mathrm{sigmoid}(W_{ii} x_t + b_{ii} + W_{hi} h_{(t-1)} + b_{hi}) \\
            f_t = \mathrm{sigmoid}(W_{if} x_t + b_{if} + W_{hf} h_{(t-1)} + b_{hf}) \\
            g_t = \tanh(W_{ig} x_t + b_{ig} + W_{hc} h_{(t-1)} + b_{hg}) \\
            o_t = \mathrm{sigmoid}(W_{io} x_t + b_{io} + W_{ho} h_{(t-1)} + b_{ho}) \\
            c_t = f_t * c_{(t-1)} + i_t * g_t \\
            h_t = o_t * \tanh(c_t)
            \end{array}

**GRU**

Gated Recurrent Unit - Cho et al. 2014. http://arxiv.org/abs/1406.1078

The definition of GRU here is slightly different from paper but compatible with CUDNN.

.. math::
  \begin{array}{ll}
            r_t = \mathrm{sigmoid}(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\
            z_t = \mathrm{sigmoid}(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\
            n_t = \tanh(W_{in} x_t + b_{in} + r_t * (W_{hn} h_{(t-1)}+ b_{hn})) \\
            h_t = (1 - z_t) * n_t + z_t * h_{(t-1)} \\
            \end{array})code")
.add_argument("data", "NDArray-or-Symbol", "Input data to RNN")
.add_argument("parameters", "NDArray-or-Symbol",
              "Vector of all RNN trainable parameters concatenated")
.add_argument("state", "NDArray-or-Symbol", "initial hidden state of the RNN")
.add_argument("state_cell", "NDArray-or-Symbol",
              "initial cell state for LSTM networks (only for LSTM)")
.add_arguments(RNNParam::__FIELDS__());
}  // namespace op
}  // namespace mxnet
<|endoftext|>


<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* based on the Null Theme Engine for Gtk+.
* Copyright (c) 2008 Robert Staudinger <robert.staudinger@gmail.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., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "config.h"
#include "oxygenstylewrapper.h"
#include "oxygenrcstyle.h"
#include "oxygenstyle.h"
#include "oxygenwindecooptions.h"

#include <gmodule.h>
#include <gtk/gtk.h>

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

//_________________________________________________
extern "C" G_MODULE_EXPORT void theme_init( GTypeModule* );
extern "C" G_MODULE_EXPORT void theme_exit( void );
extern "C" G_MODULE_EXPORT GtkRcStyle* theme_create_rc_style( void );
extern "C" G_MODULE_EXPORT const gchar* g_module_check_init( GModule* );

// exports for WM theming
extern "C" G_MODULE_EXPORT void drawWindowDecoration(cairo_t*, unsigned long,gint,gint,gint,gint);
extern "C" G_MODULE_EXPORT void drawWindecoButton(cairo_t*, unsigned long,unsigned long, unsigned long,gint,gint,gint,gint);
extern "C" G_MODULE_EXPORT void drawWindecoShapeMask(cairo_t*, unsigned long,gint,gint,gint,gint);

//_________________________________________________
void theme_init( GTypeModule* module )
{
    oxygen_rc_style_register_type( module );
    oxygen_style_register_type( module );

    // read blacklist
    const std::string configFile( std::string( GTK_THEME_DIR ) + "/argb-apps.conf" );
    std::ifstream in( configFile.c_str() );
    if( !in )
    {
        #if OXYGEN_DEBUG
        std::cout << "Oxygen::theme_init - ARGB config file \"" << configFile << "\" not found" << std::endl;
        #endif

        return;
    }

    const char* appName = g_get_prgname();
    if( !appName ) return;

    // by default argb support is enabled
    bool useRgba( true );

    // load options into a string
    std::string contents;
    std::vector<std::string> lines;
    while( std::getline( in, contents, '\n' ) )
    {
        if( contents.empty() || contents[0] == '#' ) continue;
        lines.push_back( contents );
    }

    // true if application was found in one of the lines
    bool found( false );
    for( std::vector<std::string>::const_reverse_iterator iter = lines.rbegin(); iter != lines.rend() && !found; iter++ )
    {

        // store line locally
        std::string contents( *iter );

        // split string using ":" as a delimiter
        std::vector<std::string> appNames;
        size_t position( std::string::npos );
        while( ( position = contents.find( ':' ) ) != std::string::npos )
        {
            std::string appName( contents.substr(0, position ) );
            if( !appName.empty() ) { appNames.push_back( appName ); }
            contents = contents.substr( position+1 );
        }

        if( !contents.empty() ) appNames.push_back( contents );
        if( appNames.empty() ) continue;

        // check line type
        bool enabled( true );
        if( appNames[0] == "enable" ) enabled = true;
        else if( appNames[0] == "disable" ) enabled = false;
        else continue;

        // compare application names to this application
        for( unsigned int i = 1; i < appNames.size(); i++ )
        {
            if( appNames[i] == "all" || appNames[i] == appName )
            {
                found = true;
                useRgba = enabled;
                break;
            }
        }

    }

    #if OXYGEN_DEBUG
    std::cout << "Oxygen::init_theme - program: " << appName << " ARGB visual is " << (useRgba ? "":"not ") << "used" << std::endl;
    #endif

    if(useRgba)
    {
        GdkColormap* cmap=gdk_screen_get_rgba_colormap(gdk_screen_get_default());
        gtk_widget_push_colormap(cmap);
        gtk_widget_set_default_colormap(cmap);
    }

}

//_________________________________________________
G_MODULE_EXPORT void theme_exit( void )
{}

//_________________________________________________
G_MODULE_EXPORT GtkRcStyle* theme_create_rc_style( void )
{ return GTK_RC_STYLE( g_object_new( OXYGEN_TYPE_RC_STYLE, NULL ) ); }

//_________________________________________________
G_MODULE_EXPORT const gchar* g_module_check_init( GModule *module )
{
    return gtk_check_version(
        GTK_MAJOR_VERSION,
        GTK_MINOR_VERSION,
        GTK_MICRO_VERSION - GTK_INTERFACE_AGE );
}

//_________________________________________________
G_MODULE_EXPORT void drawWindowDecoration(cairo_t* context, unsigned long options, gint x,gint y,gint w,gint h)
{
    Oxygen::Style::instance().drawWindowDecoration( context, (Oxygen::WinDeco::Options) options, x, y, w, h);
}
G_MODULE_EXPORT void drawWindecoButton(cairo_t* context, unsigned long buttonType,unsigned long buttonState, unsigned long windowState, gint x,gint y,gint w,gint h)
{
    Oxygen::Style::instance().drawWindecoButton( context, (Oxygen::WinDeco::ButtonType)buttonType,
            (Oxygen::WinDeco::ButtonStatus)buttonState, (Oxygen::WinDeco::Options) windowState, x, y, w, h);
}
G_MODULE_EXPORT void drawWindecoShapeMask(cairo_t* context, unsigned long options, gint x,gint y,gint w,gint h)
{
    Oxygen::Style::instance().drawWindecoShapeMask( context, (Oxygen::WinDeco::Options) options, x, y, w, h);
}

<commit_msg>removed unnecessary G_MODULE_EXPORT calls fixed coding style.<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* based on the Null Theme Engine for Gtk+.
* Copyright (c) 2008 Robert Staudinger <robert.staudinger@gmail.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., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "config.h"
#include "oxygenstylewrapper.h"
#include "oxygenrcstyle.h"
#include "oxygenstyle.h"
#include "oxygenwindecooptions.h"

#include <gmodule.h>
#include <gtk/gtk.h>

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

//_________________________________________________
extern "C" G_MODULE_EXPORT void theme_init( GTypeModule* );
extern "C" G_MODULE_EXPORT void theme_exit( void );
extern "C" G_MODULE_EXPORT GtkRcStyle* theme_create_rc_style( void );
extern "C" G_MODULE_EXPORT const gchar* g_module_check_init( GModule* );

// exports for WM theming
extern "C" G_MODULE_EXPORT void drawWindowDecoration(cairo_t*, unsigned long,gint,gint,gint,gint);
extern "C" G_MODULE_EXPORT void drawWindecoButton(cairo_t*, unsigned long,unsigned long, unsigned long,gint,gint,gint,gint);
extern "C" G_MODULE_EXPORT void drawWindecoShapeMask(cairo_t*, unsigned long,gint,gint,gint,gint);

//_________________________________________________
void theme_init( GTypeModule* module )
{
    oxygen_rc_style_register_type( module );
    oxygen_style_register_type( module );

    // read blacklist
    const std::string configFile( std::string( GTK_THEME_DIR ) + "/argb-apps.conf" );
    std::ifstream in( configFile.c_str() );
    if( !in )
    {
        #if OXYGEN_DEBUG
        std::cout << "Oxygen::theme_init - ARGB config file \"" << configFile << "\" not found" << std::endl;
        #endif

        return;
    }

    const char* appName = g_get_prgname();
    if( !appName ) return;

    // by default argb support is enabled
    bool useRgba( true );

    // load options into a string
    std::string contents;
    std::vector<std::string> lines;
    while( std::getline( in, contents, '\n' ) )
    {
        if( contents.empty() || contents[0] == '#' ) continue;
        lines.push_back( contents );
    }

    // true if application was found in one of the lines
    bool found( false );
    for( std::vector<std::string>::const_reverse_iterator iter = lines.rbegin(); iter != lines.rend() && !found; iter++ )
    {

        // store line locally
        std::string contents( *iter );

        // split string using ":" as a delimiter
        std::vector<std::string> appNames;
        size_t position( std::string::npos );
        while( ( position = contents.find( ':' ) ) != std::string::npos )
        {
            std::string appName( contents.substr(0, position ) );
            if( !appName.empty() ) { appNames.push_back( appName ); }
            contents = contents.substr( position+1 );
        }

        if( !contents.empty() ) appNames.push_back( contents );
        if( appNames.empty() ) continue;

        // check line type
        bool enabled( true );
        if( appNames[0] == "enable" ) enabled = true;
        else if( appNames[0] == "disable" ) enabled = false;
        else continue;

        // compare application names to this application
        for( unsigned int i = 1; i < appNames.size(); i++ )
        {
            if( appNames[i] == "all" || appNames[i] == appName )
            {
                found = true;
                useRgba = enabled;
                break;
            }
        }

    }

    #if OXYGEN_DEBUG
    std::cout << "Oxygen::init_theme - program: " << appName << " ARGB visual is " << (useRgba ? "":"not ") << "used" << std::endl;
    #endif

    if(useRgba)
    {
        GdkColormap* cmap=gdk_screen_get_rgba_colormap(gdk_screen_get_default());
        gtk_widget_push_colormap(cmap);
        gtk_widget_set_default_colormap(cmap);
    }

}

//_________________________________________________
void theme_exit( void )
{}

//_________________________________________________
GtkRcStyle* theme_create_rc_style( void )
{ return GTK_RC_STYLE( g_object_new( OXYGEN_TYPE_RC_STYLE, NULL ) ); }

//_________________________________________________
const gchar* g_module_check_init( GModule *module )
{
    return gtk_check_version(
        GTK_MAJOR_VERSION,
        GTK_MINOR_VERSION,
        GTK_MICRO_VERSION - GTK_INTERFACE_AGE );
}

//_________________________________________________
void drawWindowDecoration(cairo_t* context, unsigned long options, gint x,gint y,gint w,gint h)
{
    Oxygen::Style::instance().drawWindowDecoration( context, (Oxygen::WinDeco::Options) options, x, y, w, h);
}

//_________________________________________________
void drawWindecoButton(cairo_t* context, unsigned long buttonType,unsigned long buttonState, unsigned long windowState, gint x,gint y,gint w,gint h)
{
    Oxygen::Style::instance().drawWindecoButton(
        context, (Oxygen::WinDeco::ButtonType)buttonType,
        (Oxygen::WinDeco::ButtonStatus)buttonState, (Oxygen::WinDeco::Options) windowState, x, y, w, h);
}

//_________________________________________________
void drawWindecoShapeMask(cairo_t* context, unsigned long options, gint x,gint y,gint w,gint h)
{
    Oxygen::Style::instance().drawWindecoShapeMask( context, (Oxygen::WinDeco::Options) options, x, y, w, h);
}

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#include "combine.h"

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>

#include <boost/algorithm/string.hpp>
#include <boost/noncopyable.hpp>
#include <boost/scoped_array.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "db/bridge-loader.h"
#include "db/driver.h"
#include "db/name_loader.h"

using std::atoi;
using std::cerr;
using std::cin;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::ios;
using std::make_pair;
using std::map;
using std::string;
using std::sscanf;
using std::strlen;
using std::strcmp;

namespace {

typedef map<string, string> BridgeMap;

BridgeMap *GetBridgeMap()
{
	static boost::scoped_ptr<BridgeMap> bm(new BridgeMap);
	return bm.get();
}

class LineWriter : boost::noncopyable {
public:
	LineWriter() : uuid_(NULL), ofs_() {}

    ~LineWriter() {
		ofs_.close();
	}

	void set_uuid(const char *uuid) {uuid_ = uuid;}

	bool OpenFile(const char *file) {
		ofs_.open(file, ios::out|ios::app|ios::binary);
		return ofs_.is_open();
	}

protected:
	const char *uuid_;
	ofstream ofs_;
};

class NameWriter : public LineWriter {
public:
	NameWriter() : LineWriter(), pq_id_() {}

	void set_pq_id(int pq_id) {pq_id_ = pq_id;}

	void Write(char c, const string &name) {
		ofs_ << uuid_ << " " << c << " " << ++pq_id_ << " " << name << endl;
	}

private:
	int pq_id_;
};

NameWriter *GetNameWriter()
{
	static boost::scoped_ptr<NameWriter> writer(new NameWriter);
	return writer.get();
}

class ValueWriter : public LineWriter {
public:
	ValueWriter() : LineWriter() {}

	template<typename TNumber>
	void Write(const string &name, TNumber x) {
		ofs_ << uuid_ << " " << "(eq %" << name << " " << x << ")" << endl;
	}
};

ValueWriter *GetValueWriter()
{
	static boost::scoped_ptr<ValueWriter> writer(new ValueWriter);
	return writer.get();
}

class FunctionWriter : public LineWriter {
public:
	FunctionWriter() : LineWriter() {}

	void WriteFunction(const string &name, const string &sexp) {
		ofs_ << uuid_ << " (eq %" << name << sexp << ')' << endl;
	}

	void WriteSet(const string &name, const string &pq_name) {
		ofs_ << uuid_ << " (eq %" << name << " %" << pq_name << ")" << endl;
	}

	void WriteGet(const string &pq_name, const string &name) {
		ofs_ << uuid_ << " (eq %" << pq_name << " %sbml:" << name << ")" << endl;
	}
};

FunctionWriter *GetFunctionWriter()
{
	static boost::scoped_ptr<FunctionWriter> writer(new FunctionWriter);
	return writer.get();
}

class OdeWriter : public LineWriter {
public:
	OdeWriter() : LineWriter() {}

	void WriteOde(const string &name, const string &sexp) {
		ofs_ << uuid_ << ' ' << "(eq (diff (bvar %time) %" << name << ')'
			 << sexp << ')' << endl;
	}
};

OdeWriter *GetOdeWriter()
{
	static boost::scoped_ptr<OdeWriter> writer(new OdeWriter);
	return writer.get();
}

template<typename TNumber>
void AddOde(const string &name, TNumber x, const string &sexp)
{
	const BridgeMap *bm = GetBridgeMap();
	BridgeMap::const_iterator it = bm->find(name);
	if (it == bm->end()) {
		GetNameWriter()->Write('x', name);
		GetValueWriter()->Write(name, x);
		GetOdeWriter()->WriteOde(name, sexp);
	} else {
		GetNameWriter()->Write('v', name);
		GetFunctionWriter()->WriteSet(name, it->second);
	}
}

void AddAssignment(const string &name, const string &sexp)
{
	const BridgeMap *bm = GetBridgeMap();
	BridgeMap::const_iterator it = bm->find(name);
	if (it == bm->end()) {
		GetNameWriter()->Write('v', name);
		GetFunctionWriter()->WriteFunction(name, sexp);
	} else {
		GetNameWriter()->Write('v', name);
		GetFunctionWriter()->WriteSet(name, it->second);
	}
}

template<typename TNumber>
void AddConstant(const string &name, TNumber x)
{
	const BridgeMap *bm = GetBridgeMap();
	BridgeMap::const_iterator it = bm->find(name);
	if (it == bm->end()) {
		GetNameWriter()->Write('s', name);
		GetValueWriter()->Write(name, x);
	} else {
		GetNameWriter()->Write('v', name);
		GetFunctionWriter()->WriteSet(name, it->second);
	}
}

typedef map<int, string> PhysicalQuantityMap;

class PhysicalQuantityHandler : boost::noncopyable {
public:
	PhysicalQuantityHandler(boost::uuids::uuid uuid, PhysicalQuantityMap *pqm) : uuid_(uuid), pqm_(pqm), max_pq_id_() {}

	bool Handle(boost::uuids::uuid u, char /*type*/, int pq_id, const char *name, const char * /*unit*/, double /*capacity*/) {
		if (uuid_ != u) return true; // skip this entry
		pqm_->insert(make_pair(pq_id, string(name)));
		max_pq_id_ = std::max(pq_id, max_pq_id_);
		return true;
	}

	int max_pq_id() const {return max_pq_id_;}

private:
	boost::uuids::uuid uuid_;
	PhysicalQuantityMap *pqm_;
	int max_pq_id_;
};

class BridgeHandler : boost::noncopyable {
public:
	BridgeHandler(boost::uuids::uuid uuid, PhysicalQuantityMap *pqm)
		: uuid_(uuid),
		  pqm_(pqm)
	{}

	bool Handle(boost::uuids::uuid uuid, int pq_id, const char *direction, const char * /*sub_type*/, const char *connector)
	{
		if (uuid_ != uuid) return true;
		if (strcmp(direction, "get") == 0) {
			PhysicalQuantityMap::const_iterator it = pqm_->find(pq_id);
			if (it == pqm_->end()) {
				cerr << "failed to find physical-quantity: " << pq_id << endl;
				return false;
			}
			GetFunctionWriter()->WriteGet(it->second, connector);
		} else if (strcmp(direction, "set") == 0) {
			PhysicalQuantityMap::const_iterator it = pqm_->find(pq_id);
			if (it == pqm_->end()) {
				cerr << "failed to find physical-quantity: " << pq_id << endl;
				return false;
			}
			GetBridgeMap()->insert(make_pair("sbml:" + string(connector), it->second));
		} else {
			cerr << "invalid bridge: " << uuid << ":" << pq_id << endl;
			return false;
		}
		return true;
	}

private:
	boost::uuids::uuid uuid_;
	PhysicalQuantityMap *pqm_;
};

int ProcessAssignment(void *data, int argc, char **argv, char **names)
{
	(void)data;
	(void)names;
	assert(argc == 2);
	AddAssignment(argv[0], argv[1]);
	return 0;
}

int ProcessConstant(void *data, int argc, char **argv, char **names)
{
	(void)data;
	(void)names;
	assert(argc == 2);
	AddConstant(argv[0], argv[1]);
	return 0;
}

int ProcessOde(void *data, int argc, char **argv, char **names)
{
	(void)data;
	(void)names;
	assert(argc == 3);
	AddOde(argv[0], argv[1], argv[2]);
	return 0;
}

class Loader : public db::Driver {
public:
	explicit Loader(const char *db_file)
		: db::Driver(db_file)
	{
	}

	bool Load() {
		int e;
		char *em;
		e = sqlite3_exec(db(), "SELECT * FROM assignments", ProcessAssignment, NULL, &em);
		if (e != SQLITE_OK) {
			cerr << e << ": " << em << endl;
			sqlite3_free(em);
			return false;
		}
		e = sqlite3_exec(db(), "SELECT * FROM constants", ProcessConstant, NULL, &em);
		if (e != SQLITE_OK) {
			cerr << e << ": " << em << endl;
			sqlite3_free(em);
			return false;
		}
		e = sqlite3_exec(db(), "SELECT * FROM odes", ProcessOde, NULL, &em);
		if (e != SQLITE_OK) {
			cerr << e << ": " << em << endl;
			sqlite3_free(em);
			return false;
		}
		return true;
	}

private:
	sqlite3 *db_;
};

} // namespace

bool Combine(const char *uuid,
			 const char *db_file,
			 const char *name_file,
			 const char *value_file,
			 const char *function_file,
			 const char *ode_file)
{
	boost::uuids::string_generator gen;
	boost::uuids::uuid u = gen(uuid);

	boost::scoped_ptr<db::Driver> driver(new db::Driver(db_file));

	boost::scoped_ptr<PhysicalQuantityMap> pqm(new PhysicalQuantityMap);
	int max_pq_id = 0;
	{
		boost::scoped_ptr<db::NameLoader> loader(new db::NameLoader(driver->db()));
		boost::scoped_ptr<PhysicalQuantityHandler> handler(new PhysicalQuantityHandler(u, pqm.get()));
		if (!loader->Load(handler.get())) {
			return false;
		}
		max_pq_id = handler->max_pq_id();
	}

	GetNameWriter()->set_pq_id(max_pq_id);
	GetNameWriter()->set_uuid(uuid);
	GetNameWriter()->OpenFile(name_file);
	GetValueWriter()->set_uuid(uuid);
	GetValueWriter()->OpenFile(value_file);
	GetFunctionWriter()->set_uuid(uuid);
	GetFunctionWriter()->OpenFile(function_file);
	GetOdeWriter()->set_uuid(uuid);
	GetOdeWriter()->OpenFile(ode_file);

	boost::scoped_ptr<BridgeMap> sm(new BridgeMap);
	{
		boost::scoped_ptr<db::BridgeLoader> loader(new db::BridgeLoader(driver->db()));
		boost::scoped_ptr<BridgeHandler> handler(new BridgeHandler(u, pqm.get()));
		if (!loader->Load(handler.get())) {
			return false;
		}
	}

	boost::scoped_array<char> uuid_db(new char[strlen(uuid)+4]);
	std::sprintf(uuid_db.get(), "%s.db", uuid);
	Loader loader(uuid_db.get());
	return loader.Load();
}
<commit_msg>remove useless code<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#include "combine.h"

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <map>

#include <boost/noncopyable.hpp>
#include <boost/scoped_array.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "db/bridge-loader.h"
#include "db/driver.h"
#include "db/name_loader.h"

using std::cerr;
using std::endl;
using std::ofstream;
using std::ios;
using std::make_pair;
using std::map;
using std::string;
using std::strlen;
using std::strcmp;

namespace {

typedef map<string, string> BridgeMap;

BridgeMap *GetBridgeMap()
{
	static boost::scoped_ptr<BridgeMap> bm(new BridgeMap);
	return bm.get();
}

class LineWriter : boost::noncopyable {
public:
	LineWriter() : uuid_(NULL), ofs_() {}

    ~LineWriter() {
		ofs_.close();
	}

	void set_uuid(const char *uuid) {uuid_ = uuid;}

	bool OpenFile(const char *file) {
		ofs_.open(file, ios::out|ios::app|ios::binary);
		return ofs_.is_open();
	}

protected:
	const char *uuid_;
	ofstream ofs_;
};

class NameWriter : public LineWriter {
public:
	NameWriter() : LineWriter(), pq_id_() {}

	void set_pq_id(int pq_id) {pq_id_ = pq_id;}

	void Write(char c, const string &name) {
		ofs_ << uuid_ << " " << c << " " << ++pq_id_ << " " << name << endl;
	}

private:
	int pq_id_;
};

NameWriter *GetNameWriter()
{
	static boost::scoped_ptr<NameWriter> writer(new NameWriter);
	return writer.get();
}

class ValueWriter : public LineWriter {
public:
	ValueWriter() : LineWriter() {}

	template<typename TNumber>
	void Write(const string &name, TNumber x) {
		ofs_ << uuid_ << " " << "(eq %" << name << " " << x << ")" << endl;
	}
};

ValueWriter *GetValueWriter()
{
	static boost::scoped_ptr<ValueWriter> writer(new ValueWriter);
	return writer.get();
}

class FunctionWriter : public LineWriter {
public:
	FunctionWriter() : LineWriter() {}

	void WriteFunction(const string &name, const string &sexp) {
		ofs_ << uuid_ << " (eq %" << name << sexp << ')' << endl;
	}

	void WriteSet(const string &name, const string &pq_name) {
		ofs_ << uuid_ << " (eq %" << name << " %" << pq_name << ")" << endl;
	}

	void WriteGet(const string &pq_name, const string &name) {
		ofs_ << uuid_ << " (eq %" << pq_name << " %sbml:" << name << ")" << endl;
	}
};

FunctionWriter *GetFunctionWriter()
{
	static boost::scoped_ptr<FunctionWriter> writer(new FunctionWriter);
	return writer.get();
}

class OdeWriter : public LineWriter {
public:
	OdeWriter() : LineWriter() {}

	void WriteOde(const string &name, const string &sexp) {
		ofs_ << uuid_ << ' ' << "(eq (diff (bvar %time) %" << name << ')'
			 << sexp << ')' << endl;
	}
};

OdeWriter *GetOdeWriter()
{
	static boost::scoped_ptr<OdeWriter> writer(new OdeWriter);
	return writer.get();
}

template<typename TNumber>
void AddOde(const string &name, TNumber x, const string &sexp)
{
	const BridgeMap *bm = GetBridgeMap();
	BridgeMap::const_iterator it = bm->find(name);
	if (it == bm->end()) {
		GetNameWriter()->Write('x', name);
		GetValueWriter()->Write(name, x);
		GetOdeWriter()->WriteOde(name, sexp);
	} else {
		GetNameWriter()->Write('v', name);
		GetFunctionWriter()->WriteSet(name, it->second);
	}
}

void AddAssignment(const string &name, const string &sexp)
{
	const BridgeMap *bm = GetBridgeMap();
	BridgeMap::const_iterator it = bm->find(name);
	if (it == bm->end()) {
		GetNameWriter()->Write('v', name);
		GetFunctionWriter()->WriteFunction(name, sexp);
	} else {
		GetNameWriter()->Write('v', name);
		GetFunctionWriter()->WriteSet(name, it->second);
	}
}

template<typename TNumber>
void AddConstant(const string &name, TNumber x)
{
	const BridgeMap *bm = GetBridgeMap();
	BridgeMap::const_iterator it = bm->find(name);
	if (it == bm->end()) {
		GetNameWriter()->Write('s', name);
		GetValueWriter()->Write(name, x);
	} else {
		GetNameWriter()->Write('v', name);
		GetFunctionWriter()->WriteSet(name, it->second);
	}
}

typedef map<int, string> PhysicalQuantityMap;

class PhysicalQuantityHandler : boost::noncopyable {
public:
	PhysicalQuantityHandler(boost::uuids::uuid uuid, PhysicalQuantityMap *pqm) : uuid_(uuid), pqm_(pqm), max_pq_id_() {}

	bool Handle(boost::uuids::uuid u, char /*type*/, int pq_id, const char *name, const char * /*unit*/, double /*capacity*/) {
		if (uuid_ != u) return true; // skip this entry
		pqm_->insert(make_pair(pq_id, string(name)));
		max_pq_id_ = std::max(pq_id, max_pq_id_);
		return true;
	}

	int max_pq_id() const {return max_pq_id_;}

private:
	boost::uuids::uuid uuid_;
	PhysicalQuantityMap *pqm_;
	int max_pq_id_;
};

class BridgeHandler : boost::noncopyable {
public:
	BridgeHandler(boost::uuids::uuid uuid, PhysicalQuantityMap *pqm)
		: uuid_(uuid),
		  pqm_(pqm)
	{}

	bool Handle(boost::uuids::uuid uuid, int pq_id, const char *direction, const char * /*sub_type*/, const char *connector)
	{
		if (uuid_ != uuid) return true;
		if (strcmp(direction, "get") == 0) {
			PhysicalQuantityMap::const_iterator it = pqm_->find(pq_id);
			if (it == pqm_->end()) {
				cerr << "failed to find physical-quantity: " << pq_id << endl;
				return false;
			}
			GetFunctionWriter()->WriteGet(it->second, connector);
		} else if (strcmp(direction, "set") == 0) {
			PhysicalQuantityMap::const_iterator it = pqm_->find(pq_id);
			if (it == pqm_->end()) {
				cerr << "failed to find physical-quantity: " << pq_id << endl;
				return false;
			}
			GetBridgeMap()->insert(make_pair("sbml:" + string(connector), it->second));
		} else {
			cerr << "invalid bridge: " << uuid << ":" << pq_id << endl;
			return false;
		}
		return true;
	}

private:
	boost::uuids::uuid uuid_;
	PhysicalQuantityMap *pqm_;
};

int ProcessAssignment(void *data, int argc, char **argv, char **names)
{
	(void)data;
	(void)names;
	assert(argc == 2);
	AddAssignment(argv[0], argv[1]);
	return 0;
}

int ProcessConstant(void *data, int argc, char **argv, char **names)
{
	(void)data;
	(void)names;
	assert(argc == 2);
	AddConstant(argv[0], argv[1]);
	return 0;
}

int ProcessOde(void *data, int argc, char **argv, char **names)
{
	(void)data;
	(void)names;
	assert(argc == 3);
	AddOde(argv[0], argv[1], argv[2]);
	return 0;
}

class Loader : public db::Driver {
public:
	explicit Loader(const char *db_file)
		: db::Driver(db_file)
	{
	}

	bool Load() {
		int e;
		char *em;
		e = sqlite3_exec(db(), "SELECT * FROM assignments", ProcessAssignment, NULL, &em);
		if (e != SQLITE_OK) {
			cerr << e << ": " << em << endl;
			sqlite3_free(em);
			return false;
		}
		e = sqlite3_exec(db(), "SELECT * FROM constants", ProcessConstant, NULL, &em);
		if (e != SQLITE_OK) {
			cerr << e << ": " << em << endl;
			sqlite3_free(em);
			return false;
		}
		e = sqlite3_exec(db(), "SELECT * FROM odes", ProcessOde, NULL, &em);
		if (e != SQLITE_OK) {
			cerr << e << ": " << em << endl;
			sqlite3_free(em);
			return false;
		}
		return true;
	}

private:
	sqlite3 *db_;
};

} // namespace

bool Combine(const char *uuid,
			 const char *db_file,
			 const char *name_file,
			 const char *value_file,
			 const char *function_file,
			 const char *ode_file)
{
	boost::uuids::string_generator gen;
	boost::uuids::uuid u = gen(uuid);

	boost::scoped_ptr<db::Driver> driver(new db::Driver(db_file));

	boost::scoped_ptr<PhysicalQuantityMap> pqm(new PhysicalQuantityMap);
	int max_pq_id = 0;
	{
		boost::scoped_ptr<db::NameLoader> loader(new db::NameLoader(driver->db()));
		boost::scoped_ptr<PhysicalQuantityHandler> handler(new PhysicalQuantityHandler(u, pqm.get()));
		if (!loader->Load(handler.get())) {
			return false;
		}
		max_pq_id = handler->max_pq_id();
	}

	GetNameWriter()->set_pq_id(max_pq_id);
	GetNameWriter()->set_uuid(uuid);
	GetNameWriter()->OpenFile(name_file);
	GetValueWriter()->set_uuid(uuid);
	GetValueWriter()->OpenFile(value_file);
	GetFunctionWriter()->set_uuid(uuid);
	GetFunctionWriter()->OpenFile(function_file);
	GetOdeWriter()->set_uuid(uuid);
	GetOdeWriter()->OpenFile(ode_file);

	boost::scoped_ptr<BridgeMap> sm(new BridgeMap);
	{
		boost::scoped_ptr<db::BridgeLoader> loader(new db::BridgeLoader(driver->db()));
		boost::scoped_ptr<BridgeHandler> handler(new BridgeHandler(u, pqm.get()));
		if (!loader->Load(handler.get())) {
			return false;
		}
	}

	boost::scoped_array<char> uuid_db(new char[strlen(uuid)+4]);
	std::sprintf(uuid_db.get(), "%s.db", uuid);
	Loader loader(uuid_db.get());
	return loader.Load();
}
<|endoftext|>