<commit_before>/*************************************************************************
 *
 *  $RCSfile: Numeric.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2004-05-10 12:46:45 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _FORMS_NUMERIC_HXX_
#include "Numeric.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

//.........................................................................
namespace frm
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::form::binding;

//==================================================================
// ONumericControl
//==================================================================

//------------------------------------------------------------------
ONumericControl::ONumericControl(const Reference<XMultiServiceFactory>& _rxFactory)
    :OBoundControl(_rxFactory, VCL_CONTROL_NUMERICFIELD)
{
}

//------------------------------------------------------------------------------
StringSequence ONumericControl::getSupportedServiceNames() throw()
{
    StringSequence aSupported = OBoundControl::getSupportedServiceNames();
    aSupported.realloc(aSupported.getLength() + 1);

    ::rtl::OUString*pArray = aSupported.getArray();
    pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_NUMERICFIELD;
    return aSupported;
}

//------------------------------------------------------------------
InterfaceRef SAL_CALL ONumericControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
    return *(new ONumericControl(_rxFactory));
}

//------------------------------------------------------------------------------
Sequence<Type> ONumericControl::_getTypes()
{
    return OBoundControl::_getTypes();
}

//==================================================================
// ONumericModel
//==================================================================
//------------------------------------------------------------------
InterfaceRef SAL_CALL ONumericModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
    return *(new ONumericModel(_rxFactory));
}

//------------------------------------------------------------------------------
Sequence<Type> ONumericModel::_getTypes()
{
    return OEditBaseModel::_getTypes();
}

//------------------------------------------------------------------
DBG_NAME( ONumericModel )
//------------------------------------------------------------------
ONumericModel::ONumericModel(const Reference<XMultiServiceFactory>& _rxFactory)
                :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_NUMERICFIELD, FRM_SUN_CONTROL_NUMERICFIELD, sal_True, sal_True )
                                    // use the old control name for compytibility reasons
{
    DBG_CTOR( ONumericModel, NULL );

    m_nClassId = FormComponentType::NUMERICFIELD;
    initValueProperty( PROPERTY_VALUE, PROPERTY_ID_VALUE );
}

//------------------------------------------------------------------
ONumericModel::ONumericModel( const ONumericModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )
    :OEditBaseModel( _pOriginal, _rxFactory )
{
    DBG_CTOR( ONumericModel, NULL );
}

//------------------------------------------------------------------
ONumericModel::~ONumericModel()
{
    DBG_DTOR( ONumericModel, NULL );
}

// XCloneable
//------------------------------------------------------------------------------
IMPLEMENT_DEFAULT_CLONING( ONumericModel )

// XServiceInfo
//------------------------------------------------------------------------------
StringSequence ONumericModel::getSupportedServiceNames() throw()
{
    StringSequence aSupported = OBoundControlModel::getSupportedServiceNames();

    sal_Int32 nOldLen = aSupported.getLength();
    aSupported.realloc( nOldLen + 8 );
    ::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen;

    *pStoreTo++ = BINDABLE_CONTROL_MODEL;
    *pStoreTo++ = DATA_AWARE_CONTROL_MODEL;
    *pStoreTo++ = VALIDATABLE_CONTROL_MODEL;

    *pStoreTo++ = BINDABLE_DATA_AWARE_CONTROL_MODEL;
    *pStoreTo++ = VALIDATABLE_BINDABLE_CONTROL_MODEL;

    *pStoreTo++ = FRM_SUN_COMPONENT_NUMERICFIELD;
    *pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_NUMERICFIELD;
    *pStoreTo++ = BINDABLE_DATABASE_NUMERIC_FIELD;

    return aSupported;
}

//------------------------------------------------------------------------------
Reference<XPropertySetInfo> SAL_CALL ONumericModel::getPropertySetInfo() throw( RuntimeException )
{
    Reference<XPropertySetInfo>  xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}

//------------------------------------------------------------------------------
void ONumericModel::fillProperties(
        Sequence< Property >& _rProps,
        Sequence< Property >& _rAggregateProps ) const
{
    BEGIN_DESCRIBE_PROPERTIES( 2, OEditBaseModel )
        DECL_PROP3(DEFAULT_VALUE,   double,             BOUND, MAYBEDEFAULT, MAYBEVOID);
        DECL_PROP1(TABINDEX,        sal_Int16,          BOUND);
    END_DESCRIBE_PROPERTIES();
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& ONumericModel::getInfoHelper()
{
    return *const_cast<ONumericModel*>(this)->getArrayHelper();
}

//------------------------------------------------------------------------------
::rtl::OUString SAL_CALL ONumericModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException)
{
    return FRM_COMPONENT_NUMERICFIELD;  // old (non-sun) name for compatibility !
}

//------------------------------------------------------------------------------
sal_Bool ONumericModel::commitControlValueToDbColumn( bool _bPostReset )
{
    Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) );
    if ( !compare( aControlValue, m_aSaveValue ) )
    {
        if ( !aControlValue.hasValue() )
            m_xColumnUpdate->updateNull();
        else
        {
            try
            {
                m_xColumnUpdate->updateDouble( getDouble( aControlValue ) );
            }
            catch(Exception&)
            {
                return sal_False;
            }
        }
        m_aSaveValue = aControlValue;
    }
    return sal_True;
}

//------------------------------------------------------------------------------
Any ONumericModel::translateDbColumnToControlValue()
{
    m_aSaveValue <<= (double)m_xColumn->getDouble();
    if ( m_xColumn->wasNull() )
        m_aSaveValue.clear();

    return m_aSaveValue;
}

//------------------------------------------------------------------------------
Any ONumericModel::getDefaultForReset() const
{
    Any aValue;
    if (m_aDefault.getValueType().getTypeClass() == TypeClass_DOUBLE)
        aValue = m_aDefault;

    return aValue;
}

//------------------------------------------------------------------------------
sal_Bool ONumericModel::approveValueBinding( const Reference< XValueBinding >& _rxBinding )
{
    OSL_PRECOND( _rxBinding.is(), "ONumericModel::approveValueBinding: invalid binding!" );

    // only strings are accepted for simplicity
    return  _rxBinding.is()
        &&  _rxBinding->supportsType( ::getCppuType( static_cast< double* >( NULL ) ) );
}

//.........................................................................
}   // namespace frm
//.........................................................................

<commit_msg>INTEGRATION: CWS ooo19126 (1.11.146); FILE MERGED 2005/09/05 13:50:25 rt 1.11.146.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Numeric.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 22:45:33 $
 *
 *  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 _FORMS_NUMERIC_HXX_
#include "Numeric.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

//.........................................................................
namespace frm
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::form::binding;

//==================================================================
// ONumericControl
//==================================================================

//------------------------------------------------------------------
ONumericControl::ONumericControl(const Reference<XMultiServiceFactory>& _rxFactory)
    :OBoundControl(_rxFactory, VCL_CONTROL_NUMERICFIELD)
{
}

//------------------------------------------------------------------------------
StringSequence ONumericControl::getSupportedServiceNames() throw()
{
    StringSequence aSupported = OBoundControl::getSupportedServiceNames();
    aSupported.realloc(aSupported.getLength() + 1);

    ::rtl::OUString*pArray = aSupported.getArray();
    pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_NUMERICFIELD;
    return aSupported;
}

//------------------------------------------------------------------
InterfaceRef SAL_CALL ONumericControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
    return *(new ONumericControl(_rxFactory));
}

//------------------------------------------------------------------------------
Sequence<Type> ONumericControl::_getTypes()
{
    return OBoundControl::_getTypes();
}

//==================================================================
// ONumericModel
//==================================================================
//------------------------------------------------------------------
InterfaceRef SAL_CALL ONumericModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory)
{
    return *(new ONumericModel(_rxFactory));
}

//------------------------------------------------------------------------------
Sequence<Type> ONumericModel::_getTypes()
{
    return OEditBaseModel::_getTypes();
}

//------------------------------------------------------------------
DBG_NAME( ONumericModel )
//------------------------------------------------------------------
ONumericModel::ONumericModel(const Reference<XMultiServiceFactory>& _rxFactory)
                :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_NUMERICFIELD, FRM_SUN_CONTROL_NUMERICFIELD, sal_True, sal_True )
                                    // use the old control name for compytibility reasons
{
    DBG_CTOR( ONumericModel, NULL );

    m_nClassId = FormComponentType::NUMERICFIELD;
    initValueProperty( PROPERTY_VALUE, PROPERTY_ID_VALUE );
}

//------------------------------------------------------------------
ONumericModel::ONumericModel( const ONumericModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )
    :OEditBaseModel( _pOriginal, _rxFactory )
{
    DBG_CTOR( ONumericModel, NULL );
}

//------------------------------------------------------------------
ONumericModel::~ONumericModel()
{
    DBG_DTOR( ONumericModel, NULL );
}

// XCloneable
//------------------------------------------------------------------------------
IMPLEMENT_DEFAULT_CLONING( ONumericModel )

// XServiceInfo
//------------------------------------------------------------------------------
StringSequence ONumericModel::getSupportedServiceNames() throw()
{
    StringSequence aSupported = OBoundControlModel::getSupportedServiceNames();

    sal_Int32 nOldLen = aSupported.getLength();
    aSupported.realloc( nOldLen + 8 );
    ::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen;

    *pStoreTo++ = BINDABLE_CONTROL_MODEL;
    *pStoreTo++ = DATA_AWARE_CONTROL_MODEL;
    *pStoreTo++ = VALIDATABLE_CONTROL_MODEL;

    *pStoreTo++ = BINDABLE_DATA_AWARE_CONTROL_MODEL;
    *pStoreTo++ = VALIDATABLE_BINDABLE_CONTROL_MODEL;

    *pStoreTo++ = FRM_SUN_COMPONENT_NUMERICFIELD;
    *pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_NUMERICFIELD;
    *pStoreTo++ = BINDABLE_DATABASE_NUMERIC_FIELD;

    return aSupported;
}

//------------------------------------------------------------------------------
Reference<XPropertySetInfo> SAL_CALL ONumericModel::getPropertySetInfo() throw( RuntimeException )
{
    Reference<XPropertySetInfo>  xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}

//------------------------------------------------------------------------------
void ONumericModel::fillProperties(
        Sequence< Property >& _rProps,
        Sequence< Property >& _rAggregateProps ) const
{
    BEGIN_DESCRIBE_PROPERTIES( 2, OEditBaseModel )
        DECL_PROP3(DEFAULT_VALUE,   double,             BOUND, MAYBEDEFAULT, MAYBEVOID);
        DECL_PROP1(TABINDEX,        sal_Int16,          BOUND);
    END_DESCRIBE_PROPERTIES();
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& ONumericModel::getInfoHelper()
{
    return *const_cast<ONumericModel*>(this)->getArrayHelper();
}

//------------------------------------------------------------------------------
::rtl::OUString SAL_CALL ONumericModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException)
{
    return FRM_COMPONENT_NUMERICFIELD;  // old (non-sun) name for compatibility !
}

//------------------------------------------------------------------------------
sal_Bool ONumericModel::commitControlValueToDbColumn( bool _bPostReset )
{
    Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) );
    if ( !compare( aControlValue, m_aSaveValue ) )
    {
        if ( !aControlValue.hasValue() )
            m_xColumnUpdate->updateNull();
        else
        {
            try
            {
                m_xColumnUpdate->updateDouble( getDouble( aControlValue ) );
            }
            catch(Exception&)
            {
                return sal_False;
            }
        }
        m_aSaveValue = aControlValue;
    }
    return sal_True;
}

//------------------------------------------------------------------------------
Any ONumericModel::translateDbColumnToControlValue()
{
    m_aSaveValue <<= (double)m_xColumn->getDouble();
    if ( m_xColumn->wasNull() )
        m_aSaveValue.clear();

    return m_aSaveValue;
}

//------------------------------------------------------------------------------
Any ONumericModel::getDefaultForReset() const
{
    Any aValue;
    if (m_aDefault.getValueType().getTypeClass() == TypeClass_DOUBLE)
        aValue = m_aDefault;

    return aValue;
}

//------------------------------------------------------------------------------
sal_Bool ONumericModel::approveValueBinding( const Reference< XValueBinding >& _rxBinding )
{
    OSL_PRECOND( _rxBinding.is(), "ONumericModel::approveValueBinding: invalid binding!" );

    // only strings are accepted for simplicity
    return  _rxBinding.is()
        &&  _rxBinding->supportsType( ::getCppuType( static_cast< double* >( NULL ) ) );
}

//.........................................................................
}   // namespace frm
//.........................................................................

<|endoftext|>


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

// Buffer.cpp: Implements the gl::Buffer class, representing storage of vertex and/or
// index data. Implements GL buffer objects and related functionality.
// [OpenGL ES 2.0.24] section 2.9 page 21.

#include "libGLESv2/Buffer.h"

#include <cstdlib>
#include <limits>
#include <utility>

#include "common/debug.h"

#include "libGLESv2/geometry/backend.h"

namespace gl
{

Buffer::Buffer(BufferBackEnd *backEnd)
    : mBackEnd(backEnd), mIdentityTranslation(NULL)
{
}

Buffer::~Buffer()
{
    delete mIdentityTranslation;
}

GLenum Buffer::bufferData(const void* data, GLsizeiptr size, GLenum usage)
{
    if (size < 0) return GL_INVALID_VALUE;

    const GLubyte* newdata = static_cast<const GLubyte*>(data);

    if (size != mContents.size())
    {
        // vector::resize only provides the basic exception guarantee, so use temporaries & swap to get the strong exception guarantee.
        // We don't want to risk having mContents and mIdentityTranslation that have different contents or even different sizes.
        std::vector<GLubyte> newContents;

        if (newdata != NULL)
        {
            newContents.assign(newdata, newdata + size);
        }
        else
        {
            newContents.assign(size, 0);
        }

        TranslatedVertexBuffer *newIdentityTranslation = mBackEnd->createVertexBuffer(size);

        // No exceptions allowed after this point.

        mContents.swap(newContents);

        delete mIdentityTranslation;
        mIdentityTranslation = newIdentityTranslation;
    }
    else if (newdata != NULL)
    {
        mContents.assign(newdata, newdata + size);
    }

    mUsage = usage;

    return copyToIdentityBuffer(0, size);
}

GLenum Buffer::bufferSubData(const void* data, GLsizeiptr size, GLintptr offset)
{
    if (size < 0 || offset < 0) return GL_INVALID_VALUE;
    if (std::numeric_limits<GLsizeiptr>::max() - offset < size) return GL_INVALID_VALUE;
    if (size + offset > static_cast<GLsizeiptr>(mContents.size())) return GL_INVALID_VALUE;

    const GLubyte *newdata = static_cast<const GLubyte*>(data);
    copy(newdata, newdata + size, mContents.begin() + offset);

    return copyToIdentityBuffer(offset, size);
}

GLenum Buffer::copyToIdentityBuffer(GLintptr offset, GLsizeiptr length)
{
    ASSERT(offset >= 0 && length >= 0);

    // This is a stalling map. Not great for performance.
    GLubyte *p = static_cast<GLubyte*>(mIdentityTranslation->map());

    memcpy(p + offset, &mContents[0] + offset, length);
    mIdentityTranslation->unmap();

    return GL_NO_ERROR;
}

}
<commit_msg>Support BufferData with size zero.<commit_after>//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

// Buffer.cpp: Implements the gl::Buffer class, representing storage of vertex and/or
// index data. Implements GL buffer objects and related functionality.
// [OpenGL ES 2.0.24] section 2.9 page 21.

#include "libGLESv2/Buffer.h"

#include <cstdlib>
#include <limits>
#include <utility>

#include "common/debug.h"

#include "libGLESv2/geometry/backend.h"

namespace gl
{

Buffer::Buffer(BufferBackEnd *backEnd)
    : mBackEnd(backEnd), mIdentityTranslation(NULL)
{
}

Buffer::~Buffer()
{
    delete mIdentityTranslation;
}

GLenum Buffer::bufferData(const void* data, GLsizeiptr size, GLenum usage)
{
    if (size < 0) return GL_INVALID_VALUE;

    const GLubyte* newdata = static_cast<const GLubyte*>(data);

    if (size == 0)
    {
        mContents.clear();

        delete mIdentityTranslation;
        mIdentityTranslation = NULL;
    }
    else if (size != mContents.size())
    {
        // vector::resize only provides the basic exception guarantee, so use temporaries & swap to get the strong exception guarantee.
        // We don't want to risk having mContents and mIdentityTranslation that have different contents or even different sizes.
        std::vector<GLubyte> newContents;

        if (newdata != NULL)
        {
            newContents.assign(newdata, newdata + size);
        }
        else
        {
            newContents.assign(size, 0);
        }

        TranslatedVertexBuffer *newIdentityTranslation = mBackEnd->createVertexBuffer(size);

        // No exceptions allowed after this point.

        mContents.swap(newContents);

        delete mIdentityTranslation;
        mIdentityTranslation = newIdentityTranslation;
    }
    else if (newdata != NULL)
    {
        mContents.assign(newdata, newdata + size);
    }

    mUsage = usage;

    return copyToIdentityBuffer(0, size);
}

GLenum Buffer::bufferSubData(const void* data, GLsizeiptr size, GLintptr offset)
{
    if (size < 0 || offset < 0) return GL_INVALID_VALUE;
    if (std::numeric_limits<GLsizeiptr>::max() - offset < size) return GL_INVALID_VALUE;
    if (size + offset > static_cast<GLsizeiptr>(mContents.size())) return GL_INVALID_VALUE;

    const GLubyte *newdata = static_cast<const GLubyte*>(data);
    copy(newdata, newdata + size, mContents.begin() + offset);

    return copyToIdentityBuffer(offset, size);
}

GLenum Buffer::copyToIdentityBuffer(GLintptr offset, GLsizeiptr length)
{
    ASSERT(offset >= 0 && length >= 0);

    if (length > 0) // If length == 0 mIdentityTranslation might be NULL.
    {
        // This is a stalling map. Not great for performance.
        GLubyte *p = static_cast<GLubyte*>(mIdentityTranslation->map());

        memcpy(p + offset, &mContents[0] + offset, length);
        mIdentityTranslation->unmap();
    }

    return GL_NO_ERROR;
}

}
<|endoftext|>


<commit_before><commit_msg>missing break (I suppose)<commit_after><|endoftext|>


<commit_before>// //===----------------------------------------------------------------------===//
// //
// //                         PelotonDB
// //
// // transaction_manager.cpp
// //
// // Identification: src/backend/concurrency/pessimistic_transaction_manager.cpp
// //
// // Copyright (c) 2015, Carnegie Mellon University Database Group
// //
// //===----------------------------------------------------------------------===//

#include "pessimistic_transaction_manager.h"

#include "backend/common/platform.h"
#include "backend/logging/log_manager.h"
#include "backend/logging/records/transaction_record.h"
#include "backend/concurrency/transaction.h"
#include "backend/catalog/manager.h"
#include "backend/common/exception.h"
#include "backend/common/logger.h"
#include "backend/storage/data_table.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/tile_group_header.h"

namespace peloton {
namespace concurrency {
PessimisticTransactionManager &PessimisticTransactionManager::GetInstance() {
  static PessimisticTransactionManager txn_manager;
  return txn_manager;
}

// // Visibility check
bool PessimisticTransactionManager::IsVisible(const txn_id_t &tuple_txn_id,
                                              const cid_t &tuple_begin_cid,
                                              const cid_t &tuple_end_cid) {

  if (EXTRACT_TXNID(tuple_txn_id) == EXTRACT_TXNID(INVALID_TXN_ID)) {
    // the tuple is not available.
    return false;
  }
  bool own = (EXTRACT_TXNID(current_txn->GetTransactionId()) == tuple_txn_id);

  // there are exactly two versions that can be owned by a transaction.
  if (own == true) {
    if (tuple_begin_cid == MAX_CID && tuple_end_cid != INVALID_CID) {
      assert(tuple_end_cid == MAX_CID);
      // the only version that is visible is the newly inserted one.
      return true;
    } else {
      // the older version is not visible.
      return false;
    }
  } else {
    bool activated = (current_txn->GetStartCommitId() >= tuple_begin_cid);
    bool invalidated = (current_txn->GetStartCommitId() >= tuple_end_cid);
    if (tuple_txn_id != INITIAL_TXN_ID) {
      // if the tuple is owned by other transactions.
      if (tuple_begin_cid == MAX_CID) {
        // currently, we do not handle cascading abort. so never read an
        // uncommitted version.
        return false;
      } else {
        // the older version may be visible.
        if (activated && !invalidated) {
          return true;
        } else {
          return false;
        }
      }
    } else {
      // if the tuple is not owned by any transaction.
      if (activated && !invalidated) {
        return true;
      } else {
        return false;
      }
    }
  }
}

bool PessimisticTransactionManager::AcquireTuple(storage::TileGroup *tile_group, const oid_t &tuple_id) {
  // acquire write lock.
  auto tile_group_header = tile_group->GetHeader();

  auto old_txn_id = tile_group_header->GetTransactionId(tuple_id);

  // No writer
  // Decrease read count
  if (EXTRACT_TXNID(old_txn_id) == INITIAL_TXN_ID) {
    while (true) {
      auto new_read_count = EXTRACT_READ_COUNT(old_txn_id) - 1;
      auto new_txn_id = PACK_TXNID(INITIAL_TXN_ID, new_read_count);
      auto res = tile_group_header->CASTxnId(tuple_id, new_txn_id, old_txn_id, &old_txn_id);
      if (!res) {
        // Assert there's no other writer
        assert(EXTRACT_TXNID(old_txn_id) == INITIAL_TXN_ID);
      } else {
        break;
      }
    }
  } else {
    // Has other writer
    return false;
  }

  // Try get write lock
  auto new_txn_id = current_txn->GetTransactionId();
  auto res = tile_group_header->CASTxnId(tuple_id, new_txn_id, INITIAL_TXN_ID, &old_txn_id);

  if (res) {
    return true;
  } else {
    LOG_INFO("Fail to insert new tuple. Set txn failure.");
    SetTransactionResult(Result::RESULT_FAILURE);
    return false;
  }
}

bool PessimisticTransactionManager::IsOwner(storage::TileGroup *tile_group, const oid_t &tuple_id) {
  auto tuple_txn_id = tile_group->GetHeader()->GetTransactionId(tuple_id);
  return tuple_txn_id == current_txn->GetTransactionId();
}

// No others own the tuple
bool PessimisticTransactionManager::IsAccessable(storage::TileGroup *tile_group,
                          const oid_t &tuple_id) {
  auto tile_group_header = tile_group->GetHeader();
  auto tuple_txn_id = tile_group_header->GetTransactionId(tuple_id);
  auto tuple_end_cid = tile_group_header->GetEndCommitId(tuple_id);
  return tuple_txn_id == INITIAL_TXN_ID && tuple_end_cid == MAX_CID;
}

bool PessimisticTransactionManager::PerformRead(const oid_t &tile_group_id, const oid_t &tuple_id) {
  // acquire read lock.
  auto &manager = catalog::Manager::GetInstance();
  auto tile_group_header = manager.GetTileGroup(tile_group_id)->GetHeader();

  auto old_txn_id = tile_group_header->GetTransactionId(tuple_id);

  // No one is holding the write lock
  if (EXTRACT_TXNID(old_txn_id) == INITIAL_TXN_ID) {
    while (true) {
      auto new_read_count = EXTRACT_READ_COUNT(old_txn_id) + 1;
      // Try add read count
      auto new_txn_id = PACK_TXNID(INITIAL_TXN_ID, new_read_count);
      auto res = tile_group_header->CASTxnId(tuple_id, new_txn_id, old_txn_id, &old_txn_id);
      if (!res) {
        // See if there's writer
        if (EXTRACT_TXNID(old_txn_id) != INITIAL_TXN_ID)
          return false;
      } else {
        break;
      }
    }
  } else {
    // Has writer
    return false;
  }

  current_txn->RecordRead(tile_group_id, tuple_id);
  return true;
}

bool PessimisticTransactionManager::PerformWrite(const oid_t &tile_group_id, const oid_t &tuple_id, const ItemPointer &new_location) {
  // acquire write lock.
  auto &manager = catalog::Manager::GetInstance();
  auto tile_group_header = manager.GetTileGroup(tile_group_id)->GetHeader();

  auto old_txn_id = tile_group_header->GetTransactionId(tuple_id);

  // No writer
  // Decrease read count
  if (EXTRACT_TXNID(old_txn_id) == INITIAL_TXN_ID) {
    while (true) {
      auto new_read_count = EXTRACT_READ_COUNT(old_txn_id) - 1;
      auto new_txn_id = PACK_TXNID(INITIAL_TXN_ID, new_read_count);
      auto res = tile_group_header->CASTxnId(tuple_id, new_txn_id, old_txn_id, &old_txn_id);
      if (!res) {
        // Assert there's no other writer
        assert(EXTRACT_TXNID(old_txn_id) == INITIAL_TXN_ID);
      } else {
        break;
      }
    }
  } else {
    // Has other writer
    return false;
  }

  // Try get write lock
  auto new_txn_id = current_txn->GetTransactionId();
  auto res = tile_group_header->CASTxnId(tuple_id, new_txn_id, INITIAL_TXN_ID, &old_txn_id);

  if (res) {
    SetUpdateVisibility(new_location.block, new_location.offset);
    tile_group_header->SetNextItemPointer(tuple_id, new_location);
    current_txn->RecordWrite(tile_group_id, tuple_id);
    return true;
  } else {
    return false;
  }
}

bool PessimisticTransactionManager::PerformInsert(const oid_t &tile_group_id, const oid_t &tuple_id) {
  current_txn->RecordInsert(tile_group_id, tuple_id);
  return true;
}

bool PessimisticTransactionManager::PerformDelete(const oid_t &tile_group_id, const oid_t &tuple_id, const ItemPointer &new_location) {
  auto tile_group_header = catalog::Manager::GetInstance().GetTileGroup(tile_group_id)->GetHeader();
  SetDeleteVisibility(new_location.block, new_location.offset);
  tile_group_header->SetNextItemPointer(tuple_id, new_location);
  current_txn->RecordDelete(tile_group_id, tuple_id);
  return true;
}

Result PessimisticTransactionManager::CommitTransaction() {
  delete current_txn;
  current_txn = nullptr;
  return Result::RESULT_ABORTED;
}

Result PessimisticTransactionManager::AbortTransaction() {
  delete current_txn;
  current_txn = nullptr;
  return Result::RESULT_ABORTED;
}

void PessimisticTransactionManager::SetDeleteVisibility(__attribute__((unused)) const oid_t &tile_group_id, __attribute__((unused))  const oid_t &tuple_id) {
    ;
}

void PessimisticTransactionManager::SetUpdateVisibility(__attribute__((unused))  const oid_t &tile_group_id, __attribute__((unused))  const oid_t &tuple_id) {

}

void PessimisticTransactionManager::SetInsertVisibility(__attribute__((unused))  const oid_t &tile_group_id, __attribute__((unused))  const oid_t &tuple_id) {

}

}
}<commit_msg>2PL AcquireTuple<commit_after>// //===----------------------------------------------------------------------===//
// //
// //                         PelotonDB
// //
// // transaction_manager.cpp
// //
// // Identification: src/backend/concurrency/pessimistic_transaction_manager.cpp
// //
// // Copyright (c) 2015, Carnegie Mellon University Database Group
// //
// //===----------------------------------------------------------------------===//

#include "pessimistic_transaction_manager.h"

#include "backend/common/platform.h"
#include "backend/logging/log_manager.h"
#include "backend/logging/records/transaction_record.h"
#include "backend/concurrency/transaction.h"
#include "backend/catalog/manager.h"
#include "backend/common/exception.h"
#include "backend/common/logger.h"
#include "backend/storage/data_table.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/tile_group_header.h"

namespace peloton {
namespace concurrency {
PessimisticTransactionManager &PessimisticTransactionManager::GetInstance() {
  static PessimisticTransactionManager txn_manager;
  return txn_manager;
}

// // Visibility check
bool PessimisticTransactionManager::IsVisible(const txn_id_t &tuple_txn_id,
                                              const cid_t &tuple_begin_cid,
                                              const cid_t &tuple_end_cid) {

  if (EXTRACT_TXNID(tuple_txn_id) == EXTRACT_TXNID(INVALID_TXN_ID)) {
    // the tuple is not available.
    return false;
  }
  bool own = (EXTRACT_TXNID(current_txn->GetTransactionId()) == tuple_txn_id);

  // there are exactly two versions that can be owned by a transaction.
  if (own == true) {
    if (tuple_begin_cid == MAX_CID && tuple_end_cid != INVALID_CID) {
      assert(tuple_end_cid == MAX_CID);
      // the only version that is visible is the newly inserted one.
      return true;
    } else {
      // the older version is not visible.
      return false;
    }
  } else {
    bool activated = (current_txn->GetStartCommitId() >= tuple_begin_cid);
    bool invalidated = (current_txn->GetStartCommitId() >= tuple_end_cid);
    if (tuple_txn_id != INITIAL_TXN_ID) {
      // if the tuple is owned by other transactions.
      if (tuple_begin_cid == MAX_CID) {
        // currently, we do not handle cascading abort. so never read an
        // uncommitted version.
        return false;
      } else {
        // the older version may be visible.
        if (activated && !invalidated) {
          return true;
        } else {
          return false;
        }
      }
    } else {
      // if the tuple is not owned by any transaction.
      if (activated && !invalidated) {
        return true;
      } else {
        return false;
      }
    }
  }
}

bool PessimisticTransactionManager::AcquireTuple(storage::TileGroup *tile_group, const oid_t &tuple_id) {
  // acquire write lock.
  auto tile_group_header = tile_group->GetHeader();

  auto old_txn_id = tile_group_header->GetTransactionId(tuple_id);

  // No writer
  // Decrease read count
  if (EXTRACT_TXNID(old_txn_id) == INITIAL_TXN_ID) {
    while (true) {
      auto new_read_count = EXTRACT_READ_COUNT(old_txn_id) - 1;
      auto new_txn_id = PACK_TXNID(INITIAL_TXN_ID, new_read_count);
      auto res = tile_group_header->CASTxnId(tuple_id, new_txn_id, old_txn_id, &old_txn_id);
      if (!res) {
        // Assert there's no other writer
        assert(EXTRACT_TXNID(old_txn_id) == INITIAL_TXN_ID);
      } else {
        break;
      }
    }
  } else {
    // Has other writer
    return false;
  }

  // Try get write lock
  auto new_txn_id = current_txn->GetTransactionId();
  auto res = tile_group_header->CASTxnId(tuple_id, new_txn_id, INITIAL_TXN_ID, &old_txn_id);

  if (res) {
    return true;
  } else {
    LOG_INFO("Fail to insert new tuple. Set txn failure.");
    // TODO: Don't set txn result here
    SetTransactionResult(Result::RESULT_FAILURE);
    return false;
  }
}

bool PessimisticTransactionManager::IsOwner(storage::TileGroup *tile_group, const oid_t &tuple_id) {
  auto tuple_txn_id = tile_group->GetHeader()->GetTransactionId(tuple_id);
  return tuple_txn_id == current_txn->GetTransactionId();
}

// No others own the tuple
bool PessimisticTransactionManager::IsAccessable(storage::TileGroup *tile_group,
                          const oid_t &tuple_id) {
  auto tile_group_header = tile_group->GetHeader();
  auto tuple_txn_id = tile_group_header->GetTransactionId(tuple_id);
  auto tuple_end_cid = tile_group_header->GetEndCommitId(tuple_id);
  return tuple_txn_id == INITIAL_TXN_ID && tuple_end_cid == MAX_CID;
}

bool PessimisticTransactionManager::PerformRead(const oid_t &tile_group_id, const oid_t &tuple_id) {
  // acquire read lock.
  auto &manager = catalog::Manager::GetInstance();
  auto tile_group_header = manager.GetTileGroup(tile_group_id)->GetHeader();

  auto old_txn_id = tile_group_header->GetTransactionId(tuple_id);

  // No one is holding the write lock
  if (EXTRACT_TXNID(old_txn_id) == INITIAL_TXN_ID) {
    while (true) {
      auto new_read_count = EXTRACT_READ_COUNT(old_txn_id) + 1;
      // Try add read count
      auto new_txn_id = PACK_TXNID(INITIAL_TXN_ID, new_read_count);
      auto res = tile_group_header->CASTxnId(tuple_id, new_txn_id, old_txn_id, &old_txn_id);
      if (!res) {
        // See if there's writer
        if (EXTRACT_TXNID(old_txn_id) != INITIAL_TXN_ID)
          return false;
      } else {
        break;
      }
    }
  } else {
    // Has writer
    return false;
  }

  current_txn->RecordRead(tile_group_id, tuple_id);
  return true;
}

bool PessimisticTransactionManager::PerformWrite(const oid_t &tile_group_id, const oid_t &tuple_id, const ItemPointer &new_location) {
  // acquire write lock.
  auto &manager = catalog::Manager::GetInstance();
  auto tile_group = manager.GetTileGroup(tile_group_id);
  auto tile_group_header = tile_group->GetHeader();
  bool res = AcquireTuple(tile_group.get(), tuple_id);

  if (res) {
    SetUpdateVisibility(new_location.block, new_location.offset);
    tile_group_header->SetNextItemPointer(tuple_id, new_location);
    current_txn->RecordWrite(tile_group_id, tuple_id);
    return true;
  } else {
    // AcquireTuple may have changed the txn's result
    return false;
  }
}

bool PessimisticTransactionManager::PerformInsert(const oid_t &tile_group_id, const oid_t &tuple_id) {
  SetInsertVisibility(tile_group_id, tuple_id);
  current_txn->RecordInsert(tile_group_id, tuple_id);
  return true;
}

bool PessimisticTransactionManager::PerformDelete(const oid_t &tile_group_id, const oid_t &tuple_id, const ItemPointer &new_location) {
  auto &manager = catalog::Manager::GetInstance();
  auto tile_group = manager.GetTileGroup(tile_group_id);
  auto tile_group_header = tile_group->GetHeader();
  auto res = AcquireTuple(tile_group.get(), tuple_id);

  if (res) {
    SetDeleteVisibility(new_location.block, new_location.offset);
    tile_group_header->SetNextItemPointer(tuple_id, new_location);
    current_txn->RecordDelete(tile_group_id, tuple_id);
    return true;
  } else {
    return false;
  }
}

Result PessimisticTransactionManager::CommitTransaction() {

  delete current_txn;
  current_txn = nullptr;
  return Result::RESULT_ABORTED;
}

Result PessimisticTransactionManager::AbortTransaction() {
  delete current_txn;
  current_txn = nullptr;
  return Result::RESULT_ABORTED;
}

void PessimisticTransactionManager::SetDeleteVisibility(__attribute__((unused)) const oid_t &tile_group_id, __attribute__((unused))  const oid_t &tuple_id) {
    ;
}

void PessimisticTransactionManager::SetUpdateVisibility(__attribute__((unused))  const oid_t &tile_group_id, __attribute__((unused))  const oid_t &tuple_id) {

}

void PessimisticTransactionManager::SetInsertVisibility(__attribute__((unused))  const oid_t &tile_group_id, __attribute__((unused))  const oid_t &tuple_id) {

}

}
}<|endoftext|>


<commit_before>#include "clientwindow.h"
#include "ui_clientwindow.h"

ClientWindow::ClientWindow(int Port, QString address, QWidget *parent)
    :QMainWindow(parent)
    ,ServerIP(address)
    ,ServerPort(Port)
    ,ui(new Ui::ClientWindow)
    ,ServerSocket (new QTcpSocket(this))
    ,MyListenSocket(new QTcpServer(this))
{
    ui->setupUi(this);
    if(!MyListenSocket->listen())
    {
        ui->DebugWindow->append("ListenSocket unavailable");
    }
    connect(MyListenSocket, SIGNAL(newConnection()), this, SLOT(ConnDetector()));
}

ClientWindow::~ClientWindow()
{
    delete ui;
}
int ClientWindow::Resolver(QString Data)
{
    if(Data.startsWith("!S!"))   //server response (success search)
    {
        return 0;
    }
    else if(Data.startsWith("!C!"))  //new connection request (from peer)
    {
        return 1;
    }
    else if(Data.startsWith("!M!"))  //message
    {
        return 2;
    }
    else if(Data.startsWith("!SMESS!")) //server message
    {
        return 9;
    }
    return -1;
    //add more flags
}
void ClientWindow::SendMessageToPeer(QString PeerName)
{
    QDataStream PeerStream(Peers[PeerName]);
    QString Message = "!M!" + NickName + ':'+ ui->MsgInput->text() ;
    PeerStream << Message;
}
void ClientWindow::ConnDetector()
{
    ui->DebugWindow->append("Someone connected!... ");
    QTcpSocket* LSocket = MyListenSocket->nextPendingConnection();
    connect(LSocket,SIGNAL(readyRead()),this, SLOT(onRead()));
}
void ClientWindow::ConnectToPeer(QString IP, int Port, QString UserName)
{
    QHostAddress addr(IP);
    QTcpSocket* NewSocket = new QTcpSocket();
    NewSocket->connectToHost(addr,Port);
    QDataStream Stream (NewSocket);
    //sending this peer's nickname
    QString ConnectStr("!C!New connection from " +  NickName + " .For chat with this user search him! ");
    Stream << ConnectStr;
    connect(NewSocket,  SIGNAL(readyRead()), this, SLOT(onRead()));
    ui->DebugWindow->append("ConnectRequest sended");
    Peers[UserName] = NewSocket;
}
//SEARCH
void ClientWindow::on_SearchLine_returnPressed()
{
    if(ConnectedToServer)
    {
        QString Request = ui->SearchLine->text();
        Request = "!2!" + Request; //search request
        QDataStream ServStream(ServerSocket);
        ServStream << Request;
    }
    else
    {
        ui->DebugWindow->append("Can't connect to server!");
    }
}
//REGISTRATION
void ClientWindow::on_NameInput_returnPressed()
{

    QString Name = ui->NameInput->text();
    NickName = Name;

    ServerSocket->connectToHost(ServerIP, ServerPort);
    QString RegStr = "!0!" + NickName + ',' + MyListenSocket->serverAddress().toString() +':' + QString::number(MyListenSocket->serverPort()); // +address
    QDataStream ServStream(ServerSocket);
    ServStream << RegStr;
    connect(ServerSocket, SIGNAL(readyRead()), this, SLOT(onRead()));
    ui->NameLabel->setText("You logged as " + NickName);
    ui->NameInput->setReadOnly(1);
    ConnectedToServer = true;
}

void ClientWindow::onRead()
{
    QTcpSocket* ListenSocket = (QTcpSocket*)sender();
    QDataStream LStream(ListenSocket);
    QString Response;
    LStream >> Response;
    if(Resolver(Response) == 0)
    {
        Response = Response.mid(3);
        ui->DebugWindow->append(ui->SearchLine->text() + " was founded!");
        ConnectToPeer(Response.split(':')[0], Response.split(':')[1].toInt(), ui->SearchLine->text());
        ui->FriendList->addItem(ui->SearchLine->text());

    }
    else if(Resolver(Response) == 1)
    {
        Response = Response.mid(3);
        ui->DebugWindow->append("New connect! " + Response);

    }
    else if(Resolver(Response) == 2)
    {
        Response = Response.mid(3);
        ui->MsgBrowser->append(Response);
    }
    else if(Resolver(Response) == 9)
    {
        Response = Response.mid(7);
        ui->DebugWindow->append("Server : " + Response);
    }
    else if(Resolver(Response) == -1)
    {
        ui->DebugWindow->append("Error! " + Response);
    }
}

void ClientWindow::on_SendMsg_clicked()
{
   QString Message = ui->MsgInput->text();
   ui->MsgBrowser->append ("Me: " + Message);
   SendMessageToPeer(Destination);
}

void ClientWindow::on_FriendList_itemDoubleClicked(QListWidgetItem *item)
{
    Destination = item->text();
}

void ClientWindow::on_MsgInput_returnPressed()
{
    on_SendMsg_clicked();
    ui->MsgInput->clear();
}
<commit_msg>some bug fixes<commit_after>#include "clientwindow.h"
#include "ui_clientwindow.h"

ClientWindow::ClientWindow(int Port, QString address, QWidget *parent)
    :QMainWindow(parent)
    ,ServerSocket (new QTcpSocket(this))
    ,MyListenSocket(new QTcpServer(this))
    ,ServerIP(address)
    ,ServerPort(Port)
    ,ui(new Ui::ClientWindow)
{
    ui->setupUi(this);
    if(!MyListenSocket->listen())
    {
        ui->DebugWindow->append("ListenSocket unavailable");
    }
    connect(MyListenSocket, SIGNAL(newConnection()), this, SLOT(ConnDetector()));
}

ClientWindow::~ClientWindow()
{
    delete ui;
}
int ClientWindow::Resolver(QString Data)
{
    if(Data.startsWith("!S!"))   //server response (success search)
    {
        return 0;
    }
    else if(Data.startsWith("!C!"))  //new connection request (from peer)
    {
        return 1;
    }
    else if(Data.startsWith("!M!"))  //message
    {
        return 2;
    }
    else if(Data.startsWith("!SMESS!")) //server message
    {
        return 9;
    }
    return -1;
    //add more flags
}
void ClientWindow::SendMessageToPeer(QString PeerName)
{
    QDataStream PeerStream(Peers[PeerName]);
    QString Message = "!M!" + NickName + ':'+ ui->MsgInput->text() ;
    PeerStream << Message;
}
void ClientWindow::ConnDetector()
{
    ui->DebugWindow->append("Someone connected!... ");
    QTcpSocket* LSocket = MyListenSocket->nextPendingConnection();
    connect(LSocket,SIGNAL(readyRead()),this, SLOT(onRead()));
}
void ClientWindow::ConnectToPeer(QString IP, int Port, QString UserName)
{
    QHostAddress addr(IP);
    QTcpSocket* NewSocket = new QTcpSocket();
    NewSocket->connectToHost(addr,Port);
    QDataStream Stream (NewSocket);
    //sending this peer's nickname
    QString ConnectStr("!C!New connection from " +  NickName + " .For chat with this user search him! ");
    Stream << ConnectStr;
    connect(NewSocket,  SIGNAL(readyRead()), this, SLOT(onRead()));
    ui->DebugWindow->append("ConnectRequest sended");
    Peers[UserName] = NewSocket;
}
//SEARCH
void ClientWindow::on_SearchLine_returnPressed()
{
    if(ConnectedToServer)
    {
        QString Request = ui->SearchLine->text();
        Request = "!2!" + Request; //search request
        QDataStream ServStream(ServerSocket);
        ServStream << Request;
    }
    else
    {
        ui->DebugWindow->append("Can't connect to server!");
    }
}
//REGISTRATION
void ClientWindow::on_NameInput_returnPressed()
{

    QString Name = ui->NameInput->text();
    NickName = Name;

    ServerSocket->connectToHost(ServerIP, ServerPort);
    QString RegStr = "!0!" + NickName + ',' + MyListenSocket->serverAddress().toString() +':' + QString::number(MyListenSocket->serverPort()); // +address
    QDataStream ServStream(ServerSocket);
    ServStream << RegStr;
    connect(ServerSocket, SIGNAL(readyRead()), this, SLOT(onRead()));
    ui->NameLabel->setText("You logged as " + NickName);
    ui->NameInput->setReadOnly(1);
    ConnectedToServer = true;
}

void ClientWindow::onRead()
{
    QTcpSocket* ListenSocket = (QTcpSocket*)sender();
    QDataStream LStream(ListenSocket);
    QString Response;
    LStream >> Response;
    if(Resolver(Response) == 0)
    {
        Response = Response.mid(3);
        ui->DebugWindow->append(ui->SearchLine->text() + " was founded!");
        ConnectToPeer(Response.split(':')[0], Response.split(':')[1].toInt(), ui->SearchLine->text());
        ui->FriendList->addItem(ui->SearchLine->text());

    }
    else if(Resolver(Response) == 1)
    {
        Response = Response.mid(3);
        ui->DebugWindow->append("New connect! " + Response);

    }
    else if(Resolver(Response) == 2)
    {
        Response = Response.mid(3);
        ui->MsgBrowser->append(Response);
    }
    else if(Resolver(Response) == 9)
    {
        Response = Response.mid(7);
        ui->DebugWindow->append("Server : " + Response);
    }
    else if(Resolver(Response) == -1)
    {
        ui->DebugWindow->append("Error! " + Response);
    }
}

void ClientWindow::on_SendMsg_clicked()
{
   QString Message = ui->MsgInput->text();
   ui->MsgBrowser->append ("Me: " + Message);
   SendMessageToPeer(Destination);
}

void ClientWindow::on_FriendList_itemDoubleClicked(QListWidgetItem *item)
{
    Destination = item->text();
}

void ClientWindow::on_MsgInput_returnPressed()
{
    on_SendMsg_clicked();
    ui->MsgInput->clear();
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkBlobSpatialObject.txx"
#include "itkEllipseSpatialObject.txx"
#include "itkGroupSpatialObject.txx"
#include "itkImageSpatialObject.txx"
#include "itkLandmarkSpatialObject.txx"
#include "itkLineSpatialObject.txx"
#include "itkLineSpatialObjectPoint.txx"
#include "itkNDimensionalSpatialObject.txx"
#include "itkPlaneSpatialObject.txx"
#include "itkScene.txx"
#include "itkSpatialObject.txx"
#include "itkSpatialObjectPoint.txx"
#include "itkSpatialObjectProperty.txx"
#include "itkSurfaceSpatialObject.txx"
#include "itkSurfaceSpatialObjectPoint.txx"
#include "itkTubeSpatialObject.txx"
#include "itkTubeSpatialObjectPoint.txx"

int main ( int , char*  )
{

  return 0;
}

<commit_msg>ENH: Removed NDimensionalSpatialObject<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkBlobSpatialObject.txx"
#include "itkEllipseSpatialObject.txx"
#include "itkGroupSpatialObject.txx"
#include "itkImageSpatialObject.txx"
#include "itkLandmarkSpatialObject.txx"
#include "itkLineSpatialObject.txx"
#include "itkLineSpatialObjectPoint.txx"
#include "itkPlaneSpatialObject.txx"
#include "itkScene.txx"
#include "itkSpatialObject.txx"
#include "itkSpatialObjectPoint.txx"
#include "itkSpatialObjectProperty.txx"
#include "itkSurfaceSpatialObject.txx"
#include "itkSurfaceSpatialObjectPoint.txx"
#include "itkTubeSpatialObject.txx"
#include "itkTubeSpatialObjectPoint.txx"

int main ( int , char*  )
{

  return 0;
}

<|endoftext|>


<commit_before>#include "CardiacFibresMaterial.h"

template<>
InputParameters validParams<CardiacFibresMaterial>()
{
  InputParameters params = validParams<Material>();
  params.addParam<RealTensorValue>("fixed_R", "Externally fixed fibre rotation matrix (unit vectors row-wise: e_f, e_s, e_n). Primarily meant for debugging purposes.");
  params.addCoupledVar("thickness_parameter", "Aux variable with the thickness parameter (normalized mural position), will most often be produced with a CardiacThicknessParameterAux kernel. Make sure that its distinguishLVRV==false.");

  // we restrict output to avoid warnings about KirchhoffStress being impossible to be used in output (and nobody wants to see R_fibre)
  std::vector<std::string> output_properties;
  output_properties.push_back("E_fibre");
  output_properties.push_back("E_sheet");
  output_properties.push_back("E_normal");
  params.set<std::vector<std::string> >("output_properties") = output_properties;

  return params;
}

CardiacFibresMaterial::CardiacFibresMaterial(const std::string & name,
                                 InputParameters parameters) :
  Material(name, parameters),
  _Ef(declareProperty<RealVectorValue>("E_fibre")),
  _Es(declareProperty<RealVectorValue>("E_sheet")),
  _En(declareProperty<RealVectorValue>("E_normal")),
  _Rf(declareProperty<RealTensorValue>("R_fibre")),
  _id(RealTensorValue(1,0,0,0,1,0,0,0,1)),
  _has_fixed_R(isParamValid("fixed_R")),
  _fixed_R(_has_fixed_R ? getParam<RealTensorValue>("fixed_R") : _id),
  _has_e(isCoupled("thickness_parameter")),
  _e(_has_e ? coupledValue("thickness_parameter") : _zero),
  _grad_e(_has_e ? coupledGradient("thickness_parameter") : _grad_zero)
{
  if ( !(_has_fixed_R ^ _has_e) )
    mooseError("CardiacFibresMaterial: Either fixed_R or thickness_parameter have to be given (neither both nor none of them).");

  if (_has_fixed_R && _fixed_R.det() != 1) // TODO: det[R]==1 is necessary but not sufficient for R being a rotation matrix
    mooseError("CardiacFibresMaterial: fixed_R has been given externally, but it is not a pure rotation matrix: det[fixed_R] != 1.");
}

void CardiacFibresMaterial::computeQpProperties()
{
  if (_has_fixed_R) {
    _Rf[_qp] = _fixed_R;
    _Ef[_qp] = _Rf[_qp].row(0);
    _Es[_qp] = _Rf[_qp].row(1);
    _En[_qp] = _Rf[_qp].row(2);
  } else if (_has_e) {
    // initial angle for fibre angle as stated by \ref Potse2006
    // We follow the notation from this paper. Our e is defined slightly different, though.
    const Real pi(3.141592653589);
    const Real R( _e[_qp] < 0 ? /* RV */ pi/4. : /* LV */ pi/3.); ///< @todo TODO: we would need to distinguish LV and RV here, but have to use distinguishLVRV==false in the CardiacThicknessParameterAux to prevent _grad_e from being wrong. --> Need another way of distinguishing...
    const Real bracket(2. * _e[_qp] - 1.);
    const Real alpha(R * bracket * bracket * bracket); // We avoid the pow() call here. - Might not make a real performance difference, though.
    // we already know the normal vector's direction (negative because of our e being (1-e) of \ref Potse2006)
    RealVectorValue en;
    if (_grad_e[_qp].size() > 0) {
      en = VectorNormalize( -_grad_e[_qp] );
    } else {
      // The gradient of the thickness parameter vanishes here.
      /// @todo TODO: can we find a better en in these cases than the spherical normal?
      en = VectorNormalize( RealVectorValue(_q_point[_qp]) );
    }

    const Real ez_en( en(2) ); ///< \f$\hat{e}_z\cdot\hat{e}_n\f$
    RealVectorValue ew;
    if (std::abs(ez_en) == 1.0) {
      // ez and en are (anti)parallel
      // for simplicity, we make ew the cylindrical normal vector here
      /// @todo TODO: can we find a better ew in these cases or average over neighbor cells, etc?
      ew = VectorNormalize(RealVectorValue(_q_point[_qp](0), _q_point[_qp](1), 0.));
    } else {
      const Real wz( 1./std::sqrt(1-ez_en*ez_en) );
      const Real wn(-wz*ez_en);
      ew = VectorNormalize( RealVectorValue(wn*en(0), wn*en(1), wn*en(2)+wz) );
    }
    // none of the VectorNormalize calls in the next lines should be necessary.
    // However, we want to avoid errors due to limited numeric precision.
    const RealVectorValue ev( VectorNormalize( ew.cross(en) ) );
    const RealVectorValue ef( VectorNormalize(std::cos(alpha)*ev + std::sin(alpha)*ew) );
    const RealVectorValue es( VectorNormalize( ef.cross(en) ) );

    _En[_qp] = en;
    _Ef[_qp] = ef;
    _Es[_qp] = es;

    // row-wise initialization of _Rf
    _Rf[_qp] = RealTensorValue(_Ef[_qp], _Es[_qp], _En[_qp]);
  } else {
    mooseError("CardiacFibresMaterial: should not be here");
  }
}
<commit_msg>minor correction to prev commit<commit_after>#include "CardiacFibresMaterial.h"

template<>
InputParameters validParams<CardiacFibresMaterial>()
{
  InputParameters params = validParams<Material>();
  params.addParam<RealTensorValue>("fixed_R", "Externally fixed fibre rotation matrix (unit vectors row-wise: e_f, e_s, e_n). Primarily meant for debugging purposes.");
  params.addCoupledVar("thickness_parameter", "Aux variable with the thickness parameter (normalized mural position), will most often be produced with a CardiacThicknessParameterAux kernel. Make sure that its distinguishLVRV==false.");

  // we restrict output to avoid warnings about KirchhoffStress being impossible to be used in output (and nobody wants to see R_fibre)
  std::vector<std::string> output_properties;
  output_properties.push_back("E_fibre_x");
  output_properties.push_back("E_fibre_y");
  output_properties.push_back("E_fibre_z");
  output_properties.push_back("E_sheet_x");
  output_properties.push_back("E_sheet_y");
  output_properties.push_back("E_sheet_z");
  output_properties.push_back("E_normal_x");
  output_properties.push_back("E_normal_y");
  output_properties.push_back("E_normal_z");
  params.set<std::vector<std::string> >("output_properties") = output_properties;

  return params;
}

CardiacFibresMaterial::CardiacFibresMaterial(const std::string & name,
                                 InputParameters parameters) :
  Material(name, parameters),
  _Ef(declareProperty<RealVectorValue>("E_fibre")),
  _Es(declareProperty<RealVectorValue>("E_sheet")),
  _En(declareProperty<RealVectorValue>("E_normal")),
  _Rf(declareProperty<RealTensorValue>("R_fibre")),
  _id(RealTensorValue(1,0,0,0,1,0,0,0,1)),
  _has_fixed_R(isParamValid("fixed_R")),
  _fixed_R(_has_fixed_R ? getParam<RealTensorValue>("fixed_R") : _id),
  _has_e(isCoupled("thickness_parameter")),
  _e(_has_e ? coupledValue("thickness_parameter") : _zero),
  _grad_e(_has_e ? coupledGradient("thickness_parameter") : _grad_zero)
{
  if ( !(_has_fixed_R ^ _has_e) )
    mooseError("CardiacFibresMaterial: Either fixed_R or thickness_parameter have to be given (neither both nor none of them).");

  if (_has_fixed_R && _fixed_R.det() != 1) // TODO: det[R]==1 is necessary but not sufficient for R being a rotation matrix
    mooseError("CardiacFibresMaterial: fixed_R has been given externally, but it is not a pure rotation matrix: det[fixed_R] != 1.");
}

void CardiacFibresMaterial::computeQpProperties()
{
  if (_has_fixed_R) {
    _Rf[_qp] = _fixed_R;
    _Ef[_qp] = _Rf[_qp].row(0);
    _Es[_qp] = _Rf[_qp].row(1);
    _En[_qp] = _Rf[_qp].row(2);
  } else if (_has_e) {
    // initial angle for fibre angle as stated by \ref Potse2006
    // We follow the notation from this paper. Our e is defined slightly different, though.
    const Real pi(3.141592653589);
    const Real R( _e[_qp] < 0 ? /* RV */ pi/4. : /* LV */ pi/3.); ///< @todo TODO: we would need to distinguish LV and RV here, but have to use distinguishLVRV==false in the CardiacThicknessParameterAux to prevent _grad_e from being wrong. --> Need another way of distinguishing...
    const Real bracket(2. * _e[_qp] - 1.);
    const Real alpha(R * bracket * bracket * bracket); // We avoid the pow() call here. - Might not make a real performance difference, though.
    // we already know the normal vector's direction (negative because of our e being (1-e) of \ref Potse2006)
    RealVectorValue en;
    if (_grad_e[_qp].size() > 0) {
      en = VectorNormalize( -_grad_e[_qp] );
    } else {
      // The gradient of the thickness parameter vanishes here.
      /// @todo TODO: can we find a better en in these cases than the spherical normal?
      en = VectorNormalize( RealVectorValue(_q_point[_qp]) );
    }

    const Real ez_en( en(2) ); ///< \f$\hat{e}_z\cdot\hat{e}_n\f$
    RealVectorValue ew;
    if (std::abs(ez_en) == 1.0) {
      // ez and en are (anti)parallel
      // for simplicity, we make ew the cylindrical normal vector here
      /// @todo TODO: can we find a better ew in these cases or average over neighbor cells, etc?
      ew = VectorNormalize(RealVectorValue(_q_point[_qp](0), _q_point[_qp](1), 0.));
    } else {
      const Real wz( 1./std::sqrt(1-ez_en*ez_en) );
      const Real wn(-wz*ez_en);
      ew = VectorNormalize( RealVectorValue(wn*en(0), wn*en(1), wn*en(2)+wz) );
    }
    // none of the VectorNormalize calls in the next lines should be necessary.
    // However, we want to avoid errors due to limited numeric precision.
    const RealVectorValue ev( VectorNormalize( ew.cross(en) ) );
    const RealVectorValue ef( VectorNormalize(std::cos(alpha)*ev + std::sin(alpha)*ew) );
    const RealVectorValue es( VectorNormalize( ef.cross(en) ) );

    _En[_qp] = en;
    _Ef[_qp] = ef;
    _Es[_qp] = es;

    // row-wise initialization of _Rf
    _Rf[_qp] = RealTensorValue(_Ef[_qp], _Es[_qp], _En[_qp]);
  } else {
    mooseError("CardiacFibresMaterial: should not be here");
  }
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2016 Nicola Del Gobbo
 * 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
 *
 * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
 * IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
 * MERCHANTABLITY OR NON-INFRINGEMENT.
 *
 * See the Apache Version 2.0 License for specific language governing
 * permissions and limitations under the License.
 *
 * Contributors - initial API implementation:
 * Nicola Del Gobbo <nicoladelgobbo@gmail.com>
 ******************************************************************************/

#include "ghostscript4js.h"

static int GSDLLCALL
gsdll_stdin(void *instance, char *buf, int len)
{
    int ch;
    int count = 0;
    while (count < len) {
	ch = fgetc(stdin);
	if (ch == EOF)
	    return 0;
	*buf++ = ch;
	count++;
	if (ch == '\n')
	    break;
    }
    return count;
}

static int GSDLLCALL
gsdll_stdout(void *instance, const char *str, int len)
{
    fwrite(str, 1, len, stdout);
    fflush(stdout);
    return len;
}

static int GSDLLCALL
gsdll_stderr(void *instance, const char *str, int len)
{
    fwrite(str, 1, len, stderr);
    fflush(stderr);
    return len;
}

void *minst;
const char start_string[] = "systemdict /start get exec\n";

void Version(const Nan::FunctionCallbackInfo<Value> &info)
{
    Nan::HandleScope();
    gsapi_revision_t r;
   gsapi_revision(&r, sizeof(r));
    info.GetReturnValue().Set(Nan::New<String>(r.product).ToLocalChecked());
}

void Execute(const Nan::FunctionCallbackInfo<Value> &info)
{
    Nan::HandleScope();

    info.GetReturnValue().Set(Nan::New<String>("Execute Ghostscript command").ToLocalChecked());
}

void ExecuteSync(const Nan::FunctionCallbackInfo<Value> &info)
{
    Nan::HandleScope();
    int code, code1;
    int exit_code;
    code = gsapi_new_instance(&minst, NULL);
    if (code < 0)
	    info.GetReturnValue().Set(Nan::New<String>("Error code < 0").ToLocalChecked());
    gsapi_set_stdio(minst, gsdll_stdin, gsdll_stdout, gsdll_stderr);
    code = gsapi_set_arg_encoding(minst, GS_ARG_ENCODING_UTF8);

    info.GetReturnValue().Set(Nan::New<String>("Sync exection of Ghostscript command").ToLocalChecked());
}

//////////////////////////// INIT & CONFIG MODULE //////////////////////////////

void Init(Local<Object> exports)
{

    exports->Set(Nan::New("version").ToLocalChecked(),
                 Nan::New<FunctionTemplate>(Version)->GetFunction());

    exports->Set(Nan::New("execute").ToLocalChecked(),
                 Nan::New<FunctionTemplate>(Version)->GetFunction());

    exports->Set(Nan::New("executeSync").ToLocalChecked(),
                 Nan::New<FunctionTemplate>(ExecuteSync)->GetFunction());
}

NODE_MODULE(ghostscript4js, Init)

////////////////////////////////////////////////////////////////////////////////
<commit_msg>Added method version in  c++ binding and imported in js<commit_after>/*******************************************************************************
 * Copyright (c) 2016 Nicola Del Gobbo
 * 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
 *
 * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
 * IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
 * MERCHANTABLITY OR NON-INFRINGEMENT.
 *
 * See the Apache Version 2.0 License for specific language governing
 * permissions and limitations under the License.
 *
 * Contributors - initial API implementation:
 * Nicola Del Gobbo <nicoladelgobbo@gmail.com>
 ******************************************************************************/

#include "ghostscript4js.h"

void Version(const Nan::FunctionCallbackInfo<Value> &info)
{
    Nan::HandleScope();
    Local<Object> obj  = Nan::New<Object>();
    gsapi_revision_t r;
    int res = gsapi_revision(&r, sizeof(r));
    if ( res == 0) {
        obj->Set(Nan::New<String>("product").ToLocalChecked(), Nan::New<String>(r.product).ToLocalChecked());
        obj->Set(Nan::New<String>("copyright").ToLocalChecked(), Nan::New<String>(r.copyright).ToLocalChecked());
        obj->Set(Nan::New<String>("revision").ToLocalChecked(), Nan::New<Number>(r.revision));
        obj->Set(Nan::New<String>("revisiondate").ToLocalChecked(), Nan::New<Number>(r.revisiondate));
    } else {
        std::stringstream msg;
        msg << "Error happened retrieving Ghostscript version info error code: " << res;
        return Nan::ThrowError(Nan::New<String>(msg.str()).ToLocalChecked());
    }
    info.GetReturnValue().Set(obj);
}

void Execute(const Nan::FunctionCallbackInfo<Value> &info)
{
    Nan::HandleScope();
    info.GetReturnValue().Set(Nan::New<String>("Execute Ghostscript command").ToLocalChecked());
}

void ExecuteSync(const Nan::FunctionCallbackInfo<Value> &info)
{
    Nan::HandleScope();
    info.GetReturnValue().Set(Nan::New<String>("Sync exection of Ghostscript command").ToLocalChecked());
}

//////////////////////////// INIT & CONFIG MODULE //////////////////////////////

void Init(Local<Object> exports)
{

    exports->Set(Nan::New("version").ToLocalChecked(),
                 Nan::New<FunctionTemplate>(Version)->GetFunction());

    exports->Set(Nan::New("execute").ToLocalChecked(),
                 Nan::New<FunctionTemplate>(Execute)->GetFunction());

    exports->Set(Nan::New("executeSync").ToLocalChecked(),
                 Nan::New<FunctionTemplate>(ExecuteSync)->GetFunction());
}

NODE_MODULE(ghostscript4js, Init)

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2016 Nicola Del Gobbo
 * 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
 *
 * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
 * IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
 * MERCHANTABLITY OR NON-INFRINGEMENT.
 *
 * See the Apache Version 2.0 License for specific language governing
 * permissions and limitations under the License.
 *
 * Contributors - initial API implementation:
 * Nicola Del Gobbo <nicoladelgobbo@gmail.com>
 ******************************************************************************/

#include "ghostscript4js.h"

void Version(const Nan::FunctionCallbackInfo<Value> &info)
{
    Nan::HandleScope();
    Local<Object> obj  = Nan::New<Object>();
    gsapi_revision_t r;
    int res = gsapi_revision(&r, sizeof(r));
    if ( res == 0) {
        obj->Set(Nan::New<String>("product").ToLocalChecked(), Nan::New<String>(r.product).ToLocalChecked());
        obj->Set(Nan::New<String>("copyright").ToLocalChecked(), Nan::New<String>(r.copyright).ToLocalChecked());
        obj->Set(Nan::New<String>("revision").ToLocalChecked(), Nan::New<Number>(r.revision));
        obj->Set(Nan::New<String>("revisiondate").ToLocalChecked(), Nan::New<Number>(r.revisiondate));
    } else {
        std::stringstream msg;
        msg << "Error happened retrieving Ghostscript version info error code: " << res;
        return Nan::ThrowError(Nan::New<String>(msg.str()).ToLocalChecked());
    }
    info.GetReturnValue().Set(obj);
}

void Execute(const Nan::FunctionCallbackInfo<Value> &info)
{
    Nan::HandleScope();
    info.GetReturnValue().Set(Nan::New<String>("Execute Ghostscript command").ToLocalChecked());
}

void ExecuteSync(const Nan::FunctionCallbackInfo<Value> &info)
{
    Nan::HandleScope();
    if (info.Length() < 1) {
        return Nan::ThrowError("Sorry executeSync method requires 1 argument that represent the Ghostscript command.");
    }
    if (!info[0]->IsString()) {
        return Nan::ThrowError("Sorry executeSync method's argument should be a string.");
    }
    Local<String> cmd = Local<String>::Cast(info[0]);
    info.GetReturnValue().Set(Nan::New<String>(cmd).ToLocalChecked());
}

//////////////////////////// INIT & CONFIG MODULE //////////////////////////////

void Init(Local<Object> exports)
{

    exports->Set(Nan::New("version").ToLocalChecked(),
                 Nan::New<FunctionTemplate>(Version)->GetFunction());

    exports->Set(Nan::New("execute").ToLocalChecked(),
                 Nan::New<FunctionTemplate>(Execute)->GetFunction());

    exports->Set(Nan::New("executeSync").ToLocalChecked(),
                 Nan::New<FunctionTemplate>(ExecuteSync)->GetFunction());
}

NODE_MODULE(ghostscript4js, Init)

////////////////////////////////////////////////////////////////////////////////
<commit_msg>Updated executeSync method return valjue<commit_after>/*******************************************************************************
 * Copyright (c) 2016 Nicola Del Gobbo
 * 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
 *
 * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
 * IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
 * MERCHANTABLITY OR NON-INFRINGEMENT.
 *
 * See the Apache Version 2.0 License for specific language governing
 * permissions and limitations under the License.
 *
 * Contributors - initial API implementation:
 * Nicola Del Gobbo <nicoladelgobbo@gmail.com>
 ******************************************************************************/

#include "ghostscript4js.h"

void Version(const Nan::FunctionCallbackInfo<Value> &info)
{
    Nan::HandleScope();
    Local<Object> obj  = Nan::New<Object>();
    gsapi_revision_t r;
    int res = gsapi_revision(&r, sizeof(r));
    if ( res == 0) {
        obj->Set(Nan::New<String>("product").ToLocalChecked(), Nan::New<String>(r.product).ToLocalChecked());
        obj->Set(Nan::New<String>("copyright").ToLocalChecked(), Nan::New<String>(r.copyright).ToLocalChecked());
        obj->Set(Nan::New<String>("revision").ToLocalChecked(), Nan::New<Number>(r.revision));
        obj->Set(Nan::New<String>("revisiondate").ToLocalChecked(), Nan::New<Number>(r.revisiondate));
    } else {
        std::stringstream msg;
        msg << "Error happened retrieving Ghostscript version info error code: " << res;
        return Nan::ThrowError(Nan::New<String>(msg.str()).ToLocalChecked());
    }
    info.GetReturnValue().Set(obj);
}

void Execute(const Nan::FunctionCallbackInfo<Value> &info)
{
    Nan::HandleScope();
    info.GetReturnValue().Set(Nan::New<String>("Execute Ghostscript command").ToLocalChecked());
}

void ExecuteSync(const Nan::FunctionCallbackInfo<Value> &info)
{
    Nan::HandleScope();
    if (info.Length() < 1) {
        return Nan::ThrowError("Sorry executeSync method requires 1 argument that represent the Ghostscript command.");
    }
    if (!info[0]->IsString()) {
        return Nan::ThrowError("Sorry executeSync method's argument should be a string.");
    }
    Local<String> cmd = Local<String>::Cast(info[0]);
    info.GetReturnValue();
}

//////////////////////////// INIT & CONFIG MODULE //////////////////////////////

void Init(Local<Object> exports)
{

    exports->Set(Nan::New("version").ToLocalChecked(),
                 Nan::New<FunctionTemplate>(Version)->GetFunction());

    exports->Set(Nan::New("execute").ToLocalChecked(),
                 Nan::New<FunctionTemplate>(Execute)->GetFunction());

    exports->Set(Nan::New("executeSync").ToLocalChecked(),
                 Nan::New<FunctionTemplate>(ExecuteSync)->GetFunction());
}

NODE_MODULE(ghostscript4js, Init)

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>// flippity.cpp - a simple game with flipping digits
//
// Uses CImg and Allegro libraries and xemacs sounds.

#include <chrono>
#include <iostream>
#include <random>

// #include <allegro/sound.h>
#include <allegro.h>

#include "CImg.h"

using namespace std;
using namespace cimg_library;

class RandomInt {
public:
    RandomInt(int low, int high) :dist{low, high} {}
    int operator()() { return dist(re); }
private:
    default_random_engine re;
    uniform_int_distribution<> dist;
};

class Sound {
public:
    Sound(const char *nam) :fnam{nam} { s = load_sample(nam); }
    int play() { return play_sample(s, 128, 128, 1000, false); }
    ~Sound() { destroy_sample(s); }
private:
    SAMPLE *s;
    const char *fnam;
};

void consequences(Sound &correct, Sound &wrong, int &n_remaining, bool is_correct)
{
    if (is_correct) {
	cout << "CORRECT.   ";
	correct.play();
	--n_remaining;
    } else {
	cout << "INCORRECT. ";
	wrong.play();
	++n_remaining;
    }
    cout << n_remaining << " to go!" << endl;
}

int encode(int character)
{
    if (character >= 'A' && character <= 'Z')
	return (character - 'A') + 10;
    return (character - 'a') + 10 + 26;
}

char next_alphanum(int &last_alphanum, RandomInt &ri_alphanumeric)
{
    int i;

    for (;;) {
	i = ri_alphanumeric();
	if (i == last_alphanum
	    || i == encode('A')
	    || i == encode('H')
	    || i == encode('I')
	    || i == encode('M')
	    || i == encode('O')
	    || i == encode('T')
	    || i == encode('U')
	    || i == encode('V')
	    || i == encode('W')
	    || i == encode('X')
	    || i == encode('Y')
	    || i == encode('i')
	    || i == encode('l')
	    || i == encode('o')
	    || i == encode('u')
	    || i == encode('v')
	    || i == encode('w')
	    || i == encode('x'))
	    continue;
	switch (i) {
	    default:
		goto out;
	    case 8:
	    case 0:
		break;
	}
    }
out:
    last_alphanum = i;

    if (i <= 9)
	return '0' + i;
    i -= 10;
    if (i < 26)
	return i + 'A';
    i -= 26;
    return 'a' + i;
}

const char *help(int alphanum)
{
    if (alphanum <= 9)
	return "0123456789";
    if (alphanum <= 9 + 26)
	return "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    return "abcdefghijklmnopqrstuvwxyz";
}

int main()
{
    CImg < unsigned char >image(150, 250);
    CImgDisplay main_disp(image, "Click Inside to Start");
    unsigned char purple[] { 255, 0, 255, };
    unsigned char black[] { 0, 0, 0, };
    RandomInt ri_flip {0, 1};
    RandomInt ri_alphanumeric {0, 9 + 26 * 2};
    int n_remaining = 15;

    allegro_init();
    if (install_sound(DIGI_AUTODETECT, MIDI_NONE, 0) == -1) {
	cerr << "allegro error" << endl;
	return 1;
    }
    Sound correct { "/usr/share/xemacs21/xemacs-packages/etc/sounds/ding.wav" };
    Sound wrong { "/usr/share/xemacs21/xemacs-packages/etc/sounds/cry.wav" };

    correct.play();
    auto start = chrono::high_resolution_clock::now();

    auto last_alphanum = -1;
    auto i = next_alphanum(last_alphanum, ri_alphanumeric);

    for (; !main_disp.is_closed() && !main_disp.is_key(cimg::keyESC); ) {
	bool flip = ri_flip();
	auto hoff = flip ? 30 : 20;

	main_disp.wait();
	if (main_disp.is_key(cimg::keySPACE)) {

	    if (flip)
		image.fill(0)
		    .draw_text(hoff, 10, "%c", purple, black, 1.0, 200, i)
		    .mirror('x')
		    .blur(4)
		    .display(main_disp);
	    else
		image.fill(0)
		    .draw_text(hoff, 10, "%c", purple, black, 1.0, 200, i)
		    .blur(4)
		    .display(main_disp);

	    // get the user response
	    for (;;) {
		main_disp.wait();
		if (main_disp.is_key(cimg::keyH)) {
		    image
			.draw_text(10, image.height() - 20, help(i),
				   purple, black, 1.0, 20)
			.display(main_disp);
		}
		if (main_disp.is_key(cimg::keyF)) {
                    consequences(correct, wrong, n_remaining, !flip);
		    break;
		}
		if (main_disp.is_key(cimg::keyB)) {
                    consequences(correct, wrong, n_remaining, flip);
		    break;
		}
		if (main_disp.is_key(cimg::keyESC)) {
		    cout << "ESC" << endl;
		    n_remaining = 0;
		    break;
		}
	    }
	    if (n_remaining == 0)
		break;
	    i = next_alphanum(last_alphanum, ri_alphanumeric);
	}
    }

    auto end = chrono::high_resolution_clock::now();
    auto duration = chrono::duration_cast<chrono::milliseconds>(end - start).count();
    cout << "You took " << (duration / 1000.0) << " seconds" << endl;

    return 0;
}
<commit_msg>Add sounds announcing new letters<commit_after>// flippity.cpp - a simple game with flipping digits
//
// Uses CImg and Allegro libraries and xemacs sounds.

#include <chrono>
#include <iostream>
#include <random>
#include <map>

// #include <allegro/sound.h>
#include <allegro.h>

#include "CImg.h"

using namespace std;
using namespace cimg_library;

class RandomInt {
public:
    RandomInt(int low, int high) :dist{low, high} {}
    int operator()() { return dist(re); }
private:
    default_random_engine re;
    uniform_int_distribution<> dist;
};

class Sound {
public:
    Sound(const char *nam) :fnam{nam} { s = load_sample(nam); }
    int play() { return play_sample(s, 128, 128, 1000, false); }
    ~Sound() { destroy_sample(s); }
private:
    SAMPLE *s;
    string fnam;
};

void consequences(Sound &correct, Sound &wrong, int &n_remaining, bool is_correct)
{
    if (is_correct) {
	cout << "CORRECT.   ";
	correct.play();
	--n_remaining;
    } else {
	cout << "INCORRECT. ";
	wrong.play();
	++n_remaining;
    }
    cout << n_remaining << " to go!" << endl;
}

int encode(int character)
{
    if (character >= 'A' && character <= 'Z')
	return (character - 'A') + 10;
    return (character - 'a') + 10 + 26;
}

char next_alphanum(int &last_alphanum, RandomInt &ri_alphanumeric)
{
    int i;

    for (;;) {
	i = ri_alphanumeric();
	if (i == last_alphanum
	    || i == encode('A')
	    || i == encode('H')
	    || i == encode('I')
	    || i == encode('M')
	    || i == encode('O')
	    || i == encode('T')
	    || i == encode('U')
	    || i == encode('V')
	    || i == encode('W')
	    || i == encode('X')
	    || i == encode('Y')
	    || i == encode('i')
	    || i == encode('l')
	    || i == encode('o')
	    || i == encode('u')
	    || i == encode('v')
	    || i == encode('w')
	    || i == encode('x'))
	    continue;
	switch (i) {
	    default:
		goto out;
	    case 8:
	    case 0:
		break;
	}
    }
out:
    last_alphanum = i;

    if (i <= 9)
	return '0' + i;
    i -= 10;
    if (i < 26)
	return i + 'A';
    i -= 26;
    return 'a' + i;
}

const char *help(int alphanum)
{
    if (alphanum <= 9)
	return "0123456789";
    if (alphanum <= 9 + 26)
	return "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    return "abcdefghijklmnopqrstuvwxyz";
}

void sndmap_destroy(map<char,Sound *> &sndmap)
{
    for (auto i = 'a'; i < 'z'; ++i)
	delete sndmap[i];
}

void sndmap_init(map<char,Sound *> &sndmap)
{
    for (auto i = 'a'; i < 'z'; ++i) {
	auto uc = 'A' + (i - 'a');
	string fnam = string("original_sounds/") + i + ".wav";

	sndmap[i] = sndmap[uc] = new Sound(fnam.c_str());
    }
}

int main()
{
    CImg < unsigned char >image(150, 250);
    CImgDisplay main_disp(image, "Click Inside to Start");
    unsigned char purple[] { 255, 0, 255, };
    unsigned char black[] { 0, 0, 0, };
    RandomInt ri_flip {0, 1};
    RandomInt ri_alphanumeric {0, 9 + 26 * 2};
    int n_remaining = 15;
    map<char,Sound *> sndmap;

    allegro_init();
    if (install_sound(DIGI_AUTODETECT, MIDI_NONE, 0) == -1) {
	cerr << "allegro error" << endl;
	return 1;
    }
    Sound correct { "/usr/share/xemacs21/xemacs-packages/etc/sounds/ding.wav" };
    Sound wrong { "/usr/share/xemacs21/xemacs-packages/etc/sounds/cry.wav" };
    sndmap_init(sndmap);

    correct.play();
    auto start = chrono::high_resolution_clock::now();

    auto last_alphanum = -1;
    auto i = next_alphanum(last_alphanum, ri_alphanumeric);

    for (; !main_disp.is_closed() && !main_disp.is_key(cimg::keyESC); ) {
	bool flip = ri_flip();
	auto hoff = flip ? 30 : 20;

	main_disp.wait();
	if (main_disp.is_key(cimg::keySPACE)) {
	    auto snd = sndmap.find(i);
	    if (snd != sndmap.end())
		snd->second->play();

	    if (flip)
		image.fill(0)
		    .draw_text(hoff, 10, "%c", purple, black, 1.0, 200, i)
		    .mirror('x')
		    .blur(4)
		    .display(main_disp);
	    else
		image.fill(0)
		    .draw_text(hoff, 10, "%c", purple, black, 1.0, 200, i)
		    .blur(4)
		    .display(main_disp);

	    // get the user response
	    for (;;) {
		main_disp.wait();
		if (main_disp.is_key(cimg::keyH)) {
		    image
			.draw_text(10, image.height() - 20, help(i),
				   purple, black, 1.0, 20)
			.display(main_disp);
		}
		if (main_disp.is_key(cimg::keyF)) {
                    consequences(correct, wrong, n_remaining, !flip);
		    break;
		}
		if (main_disp.is_key(cimg::keyB)) {
                    consequences(correct, wrong, n_remaining, flip);
		    break;
		}
		if (main_disp.is_key(cimg::keyESC)) {
		    cout << "ESC" << endl;
		    n_remaining = 0;
		    break;
		}
	    }
	    if (n_remaining == 0)
		break;
	    i = next_alphanum(last_alphanum, ri_alphanumeric);
	}
    }

    auto end = chrono::high_resolution_clock::now();
    auto duration = chrono::duration_cast<chrono::milliseconds>(end - start).count();
    cout << "You took " << (duration / 1000.0) << " seconds" << endl;

    sndmap_destroy(sndmap);
    return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <unistd.h>

using namespace std;

extern "C" {
#include "iniparser.h"
}

char* base_path;
char* tester;
char* vm_name;

int  parse_ini_files(char * ini_instance,char* ini_v_machines,char* conf);
int get_archives(char* source,char* destination,char* username,char* ip);

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

	if (argc==2) {
		status = parse_ini_files(argv[1],(char*)"checker.ini",argv[1]);
	}
	return status ;
}

int parse_ini_files(char *ini_instance,char* ini_v_machines,char* conf)
{
	string temp;

	dictionary* instance; //instanta tema
	dictionary* v_machines; //fisier de configurare vms

	char* base_path;
	char* vm_name;
	char* jobs_path;
	char* username;
	char* ip;
	char* job_id;
	char* user_id;
	char* deadline;
	char* upload_time;
	char* penalty;
	char* kernel_msg;
	char* local_ip;
	char* vm_path;
	char* guest_user;
	char* guest_pass;
	char* guest_base_path;
	char* guest_shell_path;
	char* guest_home_in_bash;

	instance = iniparser_load(ini_instance);
	if (instance==NULL) {
		fprintf(stderr, "cannot parse file: %s\n", ini_instance);
		return -1 ;
	}

	v_machines=iniparser_load(ini_v_machines);
	if (v_machines==NULL){
		fprintf(stderr,"cannot parse file: %s\n",ini_v_machines);
		return -1;
	}

//	iniparser_dump(instance, stderr);
//	iniparser_dump(v_machines,stderr);

	//extrag din instanta de tema
	base_path=iniparser_getstring(instance,"Global:BasePath",NULL);
	vm_name=iniparser_getstring(instance,"Global:VMName",NULL);
	job_id=iniparser_getstring(instance,"Global:Job",NULL);
	user_id=iniparser_getstring(instance,"Global:UserId",NULL);
	deadline=iniparser_getstring(instance,"Global:Deadline",NULL);
	upload_time=iniparser_getstring(instance,"Global:UploadTime",NULL);
	penalty=iniparser_getstring(instance,"Global:Penalty",NULL);
	kernel_msg=iniparser_getstring(instance,"Global:KernelMsg",NULL);
	//jobs_path=iniparser_getstring(v_machines,"Global:JobsPath",NULL);
	//username=iniparser_getstring(v_machines,"Global:TesterUsername",NULL);
	ip=iniparser_getstring(instance,"Global:UploadIP",NULL);

	temp=vm_name;

	//extrag din fisierul de masini virtuale
	local_ip=iniparser_getstring(v_machines,"Global:LocalAddress",NULL);
	jobs_path=iniparser_getstring(v_machines,"Global:JobsPath",NULL);
	username=iniparser_getstring(v_machines,"Global:TesterUsername",NULL);
	vm_path=iniparser_getstring(v_machines,(temp+":VMPath").c_str(),NULL);
	guest_user=iniparser_getstring(v_machines,(temp+":GuestUser").c_str(),NULL);
	guest_pass=iniparser_getstring(v_machines,(temp+":GuestPassword").c_str(),NULL);
	guest_base_path=iniparser_getstring(v_machines,(temp+":GuestBasePath").c_str(),NULL);
	guest_shell_path=iniparser_getstring(v_machines,(temp+":GuestShellPath").c_str(),NULL);
//	guest_home_in_bash=iniparser_getstring(v_machines,(temp+"GuestHomeInBash").c_str());

	//get archives
	system((temp+"scp "+username+"@"+ip+":"+base_path+"/"+job_id+"/"+user_id+"/"+upload_time+"file.zip "+jobs_path+"/"+"file.zip").c_str());
	system((temp+"scp "+username+"@"+ip+":"+base_path+"/"+"tests"+"/"+job_id+".zip "+jobs_path+"/"+"tests.zip").c_str());

	//apelez executorul

	temp="bash -c \"";
	system((temp+"./executor "+vm_name+" "+ vm_path+" "+local_ip+" "+guest_user+" "+guest_pass+" "+guest_base_path+" "+guest_shell_path+"\"").c_str());

	//verific deadline + warninguri
	//din jobs_path am job_build si job_run

	//pun pe sistemul de upload rezultatele

	temp="";
	system((temp+"scp "+jobs_path+"/"+"job_build "+username+"@"+ip+":"+base_path+"/"+"checked"+"/"+job_id+"/"+user_id+"/"+upload_time+"/"+"job_build" ).c_str());
	system((temp+"scp "+jobs_path+"/"+"job_run "+username+"@"+ip+":"+base_path+"/"+"checked"+"/"+job_id+"/"+user_id+"/"+upload_time+"/"+"job_run").c_str());

	//sterg fisierul de configurare
	system((temp+"ssh "+username+"@"+ip+" "+"\"rm -f "+base_path+"uncheked"+"/"+conf+"\"").c_str());

	iniparser_freedict(instance);
	iniparser_freedict(v_machines);
	return 0 ;
}

/*int get_archives(char* base_path,char* upload_time,char* user_id,char* job_id char* destination,char* username,char* ip)
{
	string temp;

	system((temp+"scp "+base_path+"/"+"file.zip"+" "+username+"@"+ip+":"+destination+"file.zip").c_str());
	system((temp+"scp "+source+"tests.zip"+" "+username+"@"+ip+":"+destination+"tests.zip").c_str());
}*/

<commit_msg>commander: unfinished<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <unistd.h>

using namespace std;

extern "C" {
#include "iniparser.h"
}

char* base_path;
char* tester;
char* vm_name;

int  parse_ini_files(char * ini_instance,char* ini_v_machines,char* conf);
int get_archives(char* source,char* destination,char* username,char* ip);

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

	if (argc==2) {
		status = parse_ini_files(argv[1],(char*)"checker.ini",argv[1]);
	}
	return status ;
}

int parse_ini_files(char *ini_instance,char* ini_v_machines,char* conf)
{
	string temp;

	dictionary* instance; //instanta tema
	dictionary* v_machines; //fisier de configurare vms

	char* base_path;
	char* vm_name;
	char* jobs_path;
	char* username;
	char* ip;
	char* job_id;
	char* user_id;
	char* deadline;
	char* upload_time;
	char* penalty;
	char* kernel_msg;
	char* local_ip;
	char* vm_path;
	char* guest_user;
	char* guest_pass;
	char* guest_base_path;
	char* guest_shell_path;
	char* guest_home_in_bash;

	instance = iniparser_load(ini_instance);
	if (instance==NULL) {
		fprintf(stderr, "cannot parse file: %s\n", ini_instance);
		return -1 ;
	}

	v_machines=iniparser_load(ini_v_machines);
	if (v_machines==NULL){
		fprintf(stderr,"cannot parse file: %s\n",ini_v_machines);
		return -1;
	}

//	iniparser_dump(instance, stderr);
//	iniparser_dump(v_machines,stderr);

	//extrag din instanta de tema
	base_path=iniparser_getstring(instance,"Global:BasePath",NULL);
	vm_name=iniparser_getstring(instance,"Global:VMName",NULL);
	job_id=iniparser_getstring(instance,"Global:Job",NULL);
	user_id=iniparser_getstring(instance,"Global:UserId",NULL);
	deadline=iniparser_getstring(instance,"Global:Deadline",NULL);
	upload_time=iniparser_getstring(instance,"Global:UploadTime",NULL);
	penalty=iniparser_getstring(instance,"Global:Penalty",NULL);
	kernel_msg=iniparser_getstring(instance,"Global:KernelMsg",NULL);
	//jobs_path=iniparser_getstring(v_machines,"Global:JobsPath",NULL);
	//username=iniparser_getstring(v_machines,"Global:TesterUsername",NULL);
	ip=iniparser_getstring(instance,"Global:UploadIP",NULL);

	temp=vm_name;

	//extrag din fisierul de masini virtuale
	local_ip=iniparser_getstring(v_machines,"Global:LocalAddress",NULL);
	jobs_path=iniparser_getstring(v_machines,"Global:JobsPath",NULL);
	username=iniparser_getstring(v_machines,"Global:TesterUsername",NULL);
	vm_path=iniparser_getstring(v_machines,(temp+":VMPath").c_str(),NULL);
	guest_user=iniparser_getstring(v_machines,(temp+":GuestUser").c_str(),NULL);
	guest_pass=iniparser_getstring(v_machines,(temp+":GuestPassword").c_str(),NULL);
	guest_base_path=iniparser_getstring(v_machines,(temp+":GuestBasePath").c_str(),NULL);
	guest_shell_path=iniparser_getstring(v_machines,(temp+":GuestShellPath").c_str(),NULL);
//	guest_home_in_bash=iniparser_getstring(v_machines,(temp+"GuestHomeInBash").c_str());

	//get archives
	system((temp+"scp "+username+"@"+ip+":"+base_path+"/"+job_id+"/"+user_id+"/"+upload_time+"file.zip "+jobs_path+"/"+"file.zip").c_str());
	system((temp+"scp "+username+"@"+ip+":"+base_path+"/"+"tests"+"/"+job_id+".zip "+jobs_path+"/"+"tests.zip").c_str());

	//apelez executorul

	temp="bash -c \"";
	system((temp+"./executor "+vm_name+" "+ vm_path+" "+local_ip+" "+guest_user+" "+guest_pass+" "+guest_base_path+" "+guest_shell_path+"\"").c_str());

	//verific deadline + warninguri
	//din jobs_path am job_build si job_run

	//pun pe sistemul de upload rezultatele

	temp="";
	system((temp+"scp "+jobs_path+"/"+"job_build "+username+"@"+ip+":"+base_path+"/"+"checked"+"/"+job_id+"/"+user_id+"/"+upload_time+"/"+"job_build" ).c_str());
	system((temp+"scp "+jobs_path+"/"+"job_run "+username+"@"+ip+":"+base_path+"/"+"checked"+"/"+job_id+"/"+user_id+"/"+upload_time+"/"+"job_run").c_str());

	//pun arhiva si o dezarhivez
	system((temp+"scp "+jobs_path+"/"+"file.zip "+username+"@"+ip+":"+base_path+"/"+"checked"+"/"+job_id+"/"+user_id+"/"+upload_time+"/"+"file.zip" ).c_str());
	system((temp+"ssh "+username+"@"+ip+" "+"\"unzip "+base_path+"uncheked"+"/"+"file.zip"+"\"").c_str());
	system((temp+"ssh "+username+"@"+ip+" "+"\"rm -f "+base_path+"uncheked"+"/"+"file.zip"+"\"").c_str());

	//sterg fisierul de configurare
	system((temp+"ssh "+username+"@"+ip+" "+"\"rm -f "+base_path+"uncheked"+"/"+conf+"\"").c_str());

	iniparser_freedict(instance);
	iniparser_freedict(v_machines);
	return 0 ;
}

/*int get_archives(char* base_path,char* upload_time,char* user_id,char* job_id char* destination,char* username,char* ip)
{
	string temp;

	system((temp+"scp "+base_path+"/"+"file.zip"+" "+username+"@"+ip+":"+destination+"file.zip").c_str());
	system((temp+"scp "+source+"tests.zip"+" "+username+"@"+ip+":"+destination+"tests.zip").c_str());
}*/

<|endoftext|>