<commit_before>//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// See LICENSE file in the project root for full license information.
//

#include "corlib_native.h"
#include <ctype.h>

HRESULT Library_corlib_native_System_Convert::NativeToInt64___STATIC__I8__STRING__BOOLEAN__I8__I8__I4( CLR_RT_StackFrame& stack )
{
    NANOCLR_HEADER();
    {
        int64_t result = 0;

		char* str = (char*)stack.Arg0().RecoverString();
        signed int radix = stack.Arg4().NumericByRef().s4;

      #if (SUPPORT_ANY_BASE_CONVERSION == TRUE)
        // suport for conversion from any base

        int64_t zero = 0;

        bool isSigned = (bool)stack.Arg1().NumericByRef().u1;
        long long minValue = stack.Arg2().NumericByRef().s8;
        long long maxValue = stack.Arg3().NumericByRef().s8;

        result = isSigned ? strtoll(str, nullptr, radix) : (long long) strtoull(str, nullptr, radix);

        stack.SetResult_I8 ((result > maxValue || result < minValue) ? zero : result);

      #else
        // support for conversion from base 10 and 16 (partial)

        if(radix == 10)
        {
            // conversion from base 10

            // check for minus sign
            if(*str == '-')
            {
                // call GetIntegerPart() in 'guess' mode by throwing a crazy number for the length
                result = GetIntegerPart((str + 1), 99);

                // is negative
                result *= -1;
            }
            // check for plus sign
            else if(*str == '+')
            {
                // call GetIntegerPart() in 'guess' mode by throwing a crazy number for the length
                result = GetIntegerPart((str + 1), 99);
            }
            else
            {
                // call GetIntegerPart() in 'guess' mode by throwing a crazy number for the length
                result = GetIntegerPart(str, 99);
            }

        }
        else if(radix == 16)
        {
            // conversion from base 16
            result = GetIntegerFromHexString(str);
        }
        else
        {
            // all other bases are not supported
            return stack.NotImplementedStub();
        }

        stack.SetResult_I8(result);

      #endif // defined(SUPPORT_ANY_BASE_CONVERSION)
	}
    NANOCLR_NOCLEANUP_NOLABEL();
}

HRESULT Library_corlib_native_System_Convert::NativeToDouble___STATIC__R8__STRING( CLR_RT_StackFrame& stack )
{
    NANOCLR_HEADER();
    {
        char* str = (char*)stack.Arg0().RecoverString();

  #if (SUPPORT_ANY_BASE_CONVERSION == TRUE)
        // suport for conversion from any base

        stack.SetResult_R8 (strtod(str, nullptr));
    }
    NANOCLR_NOCLEANUP_NOLABEL();

  #else
        // support for conversion from base 10 and 16 (partial)
        // in this particular function the base isn't relevant

        int length = 0;
        bool hasMinusSign = false;
        bool hasPlusSign = false;
        int decimalPoint = -1;
        double returnValue = 0.0;

        // first pass, get count of decimal places, integer part and check for valid chars
        char* temp  = str;
        while (*temp != '\0')
        {
            switch (*temp)
            {
                case '-':
                    if (length == 0)
                    {
                        hasMinusSign = true;
                    }
                    else
                    {
                        // found a minus signal NOT at the start of the string
                        NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
                    }
                    break;

                case '+':
                    if (length == 0)
                    {
                        hasPlusSign = true;
                    }
                    else
                    {
                        // found a plus signal NOT at the start of the string
                        NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
                    }
                    break;

                case '.':
                    if (decimalPoint == -1)
                    {
                        decimalPoint = length;
                    }
                    else
                    {
                        // already found a decimal point, can't have another
                        NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
                    }
                    break;

                default:
                    if (*temp < '0' && *temp > '9')
                    {
                        // there is an invalid char in the string
                        NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
                    }
            }
            length++;
            temp++;
        }

        //  now parse the string according to it's format
        if (decimalPoint == -1)
        {
            // string doesn't have fractional part, treat as integer
            returnValue = GetIntegerPart(str, length);
        }
        else if (decimalPoint == 0)
        {
            // string starts with the decimal point, only has fractional part
            returnValue = GetDoubleFractionalPart((str+decimalPoint+1), (length-decimalPoint-1));
        }
        else if (hasMinusSign || hasPlusSign)
        {
            // string starts with sign and...

            if(decimalPoint == 1)
            {
                // ... is followed by a decimal point, only has fractional part
                returnValue = GetDoubleFractionalPart((str+decimalPoint+1), (length-decimalPoint-1));
            }
            else
            {
                // ... has integer and fractional parts
                returnValue = GetIntegerPart(str+1, decimalPoint-1);
                returnValue = (returnValue + GetDoubleFractionalPart((str+decimalPoint+1), (length-decimalPoint-1)));
            }

            if (hasMinusSign)
            {
                returnValue *= -1;
            }
        }
        else
        {
            // string has integer and fractional parts
            returnValue = GetIntegerPart(str, decimalPoint);
            returnValue = returnValue + GetDoubleFractionalPart((str+decimalPoint+1), (length-decimalPoint-1));
        }

        stack.SetResult_R8(returnValue);
	}
    NANOCLR_NOCLEANUP();

  #endif // defined(SUPPORT_ANY_BASE_CONVERSION)

}

HRESULT Library_corlib_native_System_Convert::ToBase64String___STATIC__STRING__SZARRAY_U1__I4__I4__BOOLEAN( CLR_RT_StackFrame& stack )
{
    NANOCLR_HEADER();

    NANOCLR_SET_AND_LEAVE(stack.NotImplementedStub());

    NANOCLR_NOCLEANUP();
}

HRESULT Library_corlib_native_System_Convert::FromBase64CharArray___STATIC__SZARRAY_U1__SZARRAY_CHAR__I4( CLR_RT_StackFrame& stack )
{
    NANOCLR_HEADER();

    NANOCLR_SET_AND_LEAVE(stack.NotImplementedStub());

    NANOCLR_NOCLEANUP();
}

double Library_corlib_native_System_Convert::GetDoubleFractionalPart(char* str, int length)
{
    double place = 1;
    double returnValue = 0.0;

    for (int i = 0; i < length; i++)
    {
        // move decimal place to the right
        place /= 10.0;

        returnValue += ((int)(*str++) - '0') * place;
    }

    return returnValue;
}

int64_t Library_corlib_native_System_Convert::GetIntegerPart(char* str, int length)
{
    int64_t returnValue = 0;

    for (int i = 0; i < length; i++)
    {
        returnValue = returnValue * 10 + (*str - '0');
        str++;

        // check for terminator, in case this is being called in 'guess' mode
        if(*str == '\0')
        {
            break;
        }
    }

    return returnValue;
}

int64_t Library_corlib_native_System_Convert::GetIntegerFromHexString(char* str)
{
    int64_t returnValue = 0;

	if ((*str == '0') && (*(str+1) == 'x'))
    {
        // there a 0x at the begining of the string, so move pointer forward 2 notches
        str += 2;
    }

	while (*str != '\0')
	{
		char c = toupper(*str++);

		if ((c < '0') || (c > 'F') || ((c > '9') && (c < 'A')))
        {
            // there is an invalid char in the string
            break;
        }

		c -= '0';

		if (c > 9)
        {
			c -= 7;
        }

		returnValue = (returnValue << 4) + c;
	}

	return returnValue;
}
<commit_msg>Fix for issue #409: NativeToDouble doesn't support the "e"/"E" exponential char (#850)<commit_after>//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// See LICENSE file in the project root for full license information.
//

#include "corlib_native.h"
#include <ctype.h>

HRESULT Library_corlib_native_System_Convert::NativeToInt64___STATIC__I8__STRING__BOOLEAN__I8__I8__I4( CLR_RT_StackFrame& stack )
{
    NANOCLR_HEADER();
    {
        int64_t result = 0;

		char* str = (char*)stack.Arg0().RecoverString();
        signed int radix = stack.Arg4().NumericByRef().s4;

      #if (SUPPORT_ANY_BASE_CONVERSION == TRUE)
        // suport for conversion from any base

        int64_t zero = 0;

        bool isSigned = (bool)stack.Arg1().NumericByRef().u1;
        long long minValue = stack.Arg2().NumericByRef().s8;
        long long maxValue = stack.Arg3().NumericByRef().s8;

        result = isSigned ? strtoll(str, nullptr, radix) : (long long) strtoull(str, nullptr, radix);

        stack.SetResult_I8 ((result > maxValue || result < minValue) ? zero : result);

      #else
        // support for conversion from base 10 and 16 (partial)

        if(radix == 10)
        {
            // conversion from base 10

            // check for minus sign
            if(*str == '-')
            {
                // call GetIntegerPart() in 'guess' mode by throwing a crazy number for the length
                result = GetIntegerPart((str + 1), 99);

                // is negative
                result *= -1;
            }
            // check for plus sign
            else if(*str == '+')
            {
                // call GetIntegerPart() in 'guess' mode by throwing a crazy number for the length
                result = GetIntegerPart((str + 1), 99);
            }
            else
            {
                // call GetIntegerPart() in 'guess' mode by throwing a crazy number for the length
                result = GetIntegerPart(str, 99);
            }

        }
        else if(radix == 16)
        {
            // conversion from base 16
            result = GetIntegerFromHexString(str);
        }
        else
        {
            // all other bases are not supported
            return stack.NotImplementedStub();
        }

        stack.SetResult_I8(result);

      #endif // defined(SUPPORT_ANY_BASE_CONVERSION)
	}
    NANOCLR_NOCLEANUP_NOLABEL();
}

HRESULT Library_corlib_native_System_Convert::NativeToDouble___STATIC__R8__STRING( CLR_RT_StackFrame& stack )
{
    NANOCLR_HEADER();
    {
        char* str = (char*)stack.Arg0().RecoverString();

  #if (SUPPORT_ANY_BASE_CONVERSION == TRUE)
        // suport for conversion from any base

        stack.SetResult_R8 (strtod(str, nullptr));
    }
    NANOCLR_NOCLEANUP_NOLABEL();

  #else
        // support for conversion from base 10 and 16 (partial)
        // in this particular function the base isn't relevant

        int length = 0;
        bool hasMinusSign = false;
        bool hasPlusSign = false;
        int decimalPoint = -1;
        int exponentialSign = -1;
        bool hasMinusExponentialSign = false;
        bool hasPlusExponentialSign = false;
        double returnValue = 0.0;

        // first pass, get count of decimal places, integer part and check for valid chars
        char* temp  = str;
        while (*temp != '\0')
        {
            switch (*temp)
            {
                case '-':
                    if (exponentialSign == -1)
                    {
                        if (length == 0)
                        {
                            hasMinusSign = true;
                        }
                        else
                        {
                            // found a minus signal NOT at the start of the string
                            NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
                        }
                    }
                    else
                    {
                        if (length == exponentialSign + 1)
                        {
                            hasMinusExponentialSign = true;
                        }
                        else
                        {
                            // found a minus signal NOT at the start of the exponent
                            NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
                        }
                    }
                    break;

                case '+':
                    if (exponentialSign == -1)
                    {
                        if (length == 0)
                        {
                            hasPlusSign = true;
                        }
                        else
                        {
                            // found a plus signal NOT at the start of the string
                            NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
                        }
                    }
                    else
                    {
                        if (length == exponentialSign + 1)
                        {
                            hasPlusExponentialSign = true;
                        }
                        else
                        {
                            // found a plus signal NOT at the start of the exponent
                            NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
                        }
                    }
                    break;

                case '.':
                    if (decimalPoint == -1)
                    {
                        decimalPoint = length;
                    }
                    else
                    {
                        // already found a decimal point, can't have another
                        NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
                    }
                    break;

                case 'e':
                case 'E':
                    if (exponentialSign == -1)
                    {
                        exponentialSign = length;
                    }
                    else
                    {
                        // already found a exponential sign, can't have another
                        NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
                    }
                    break;

                default:
                    if (*temp < '0' && *temp > '9')
                    {
                        // there is an invalid char in the string
                        NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);
                    }
            }
            length++;
            temp++;
        }

        //  now parse the string according to it's format
        int endOrExponentialPart = exponentialSign == -1 ? length : exponentialSign;
        if (decimalPoint == -1)
        {
            // string doesn't have fractional part, treat as integer
            returnValue = GetIntegerPart(str, endOrExponentialPart);
        }
        else if (decimalPoint == 0)
        {
            // string starts with the decimal point, only has fractional part
            returnValue = GetDoubleFractionalPart((str+decimalPoint+1), (endOrExponentialPart-decimalPoint-1));
        }
        else if (hasMinusSign || hasPlusSign)
        {
            // string starts with sign and...

            if(decimalPoint == 1)
            {
                // ... is followed by a decimal point, only has fractional part
                returnValue = GetDoubleFractionalPart((str+decimalPoint+1), (endOrExponentialPart-decimalPoint-1));
            }
            else
            {
                // ... has integer and fractional parts
                returnValue = GetIntegerPart(str+1, decimalPoint-1);
                returnValue = (returnValue + GetDoubleFractionalPart((str+decimalPoint+1), (endOrExponentialPart-decimalPoint-1)));
            }

            if (hasMinusSign)
            {
                returnValue *= -1;
            }
        }
        else
        {
            // string has integer and fractional parts
            returnValue = GetIntegerPart(str, decimalPoint);
            returnValue = returnValue + GetDoubleFractionalPart((str+decimalPoint+1), (endOrExponentialPart-decimalPoint-1));
        }

        // exponential part found?
        if (exponentialSign != -1)
        {
            // advance by one if a sign (+ or -) is after the exponential sign
            if (hasMinusExponentialSign || hasPlusExponentialSign) exponentialSign++;
            // get the exponential part
            int exponent = GetIntegerPart((str+exponentialSign+1), (length-exponentialSign-1));
            // each time multiply or divide by 10
            for (int i = 0; i < exponent; i++)
            {
                if (hasMinusExponentialSign)
                {
                    returnValue /= 10;
                }
                else
                {
                    returnValue *= 10;
                }
            }
        }

        stack.SetResult_R8(returnValue);
	}
    NANOCLR_NOCLEANUP();

  #endif // defined(SUPPORT_ANY_BASE_CONVERSION)

}

HRESULT Library_corlib_native_System_Convert::ToBase64String___STATIC__STRING__SZARRAY_U1__I4__I4__BOOLEAN( CLR_RT_StackFrame& stack )
{
    NANOCLR_HEADER();

    NANOCLR_SET_AND_LEAVE(stack.NotImplementedStub());

    NANOCLR_NOCLEANUP();
}

HRESULT Library_corlib_native_System_Convert::FromBase64CharArray___STATIC__SZARRAY_U1__SZARRAY_CHAR__I4( CLR_RT_StackFrame& stack )
{
    NANOCLR_HEADER();

    NANOCLR_SET_AND_LEAVE(stack.NotImplementedStub());

    NANOCLR_NOCLEANUP();
}

double Library_corlib_native_System_Convert::GetDoubleFractionalPart(char* str, int length)
{
    double place = 1;
    double returnValue = 0.0;

    for (int i = 0; i < length; i++)
    {
        // move decimal place to the right
        place /= 10.0;

        returnValue += ((int)(*str++) - '0') * place;
    }

    return returnValue;
}

int64_t Library_corlib_native_System_Convert::GetIntegerPart(char* str, int length)
{
    int64_t returnValue = 0;

    for (int i = 0; i < length; i++)
    {
        returnValue = returnValue * 10 + (*str - '0');
        str++;

        // check for terminator, in case this is being called in 'guess' mode
        if(*str == '\0')
        {
            break;
        }
    }

    return returnValue;
}

int64_t Library_corlib_native_System_Convert::GetIntegerFromHexString(char* str)
{
    int64_t returnValue = 0;

	if ((*str == '0') && (*(str+1) == 'x'))
    {
        // there a 0x at the begining of the string, so move pointer forward 2 notches
        str += 2;
    }

	while (*str != '\0')
	{
		char c = toupper(*str++);

		if ((c < '0') || (c > 'F') || ((c > '9') && (c < 'A')))
        {
            // there is an invalid char in the string
            break;
        }

		c -= '0';

		if (c > 9)
        {
			c -= 7;
        }

		returnValue = (returnValue << 4) + c;
	}

	return returnValue;
}
<|endoftext|>


<commit_before>// Copyright 2009 Minor Gordon.
// This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions).

#include "org/xtreemfs/client/dir_proxy.h"
#include "org/xtreemfs/interfaces/exceptions.h"
#include "policy_container.h"
using namespace org::xtreemfs::client;

DIRProxy::DIRProxy( const YIELD::URI& uri, YIELD::SSLContext* ssl_context, YIELD::Log* log )
  : YIELD::ONCRPCProxy( uri, ssl_context, log )
{
  dir_interface.registerObjectFactories( object_factories );
  org::xtreemfs::interfaces::Exceptions().registerObjectFactories( object_factories );
  policies = new PolicyContainer;
}

DIRProxy::~DIRProxy()
{
  delete policies;
  for ( std::map<std::string, CachedAddressMappingURI*>::iterator uuid_to_uri_i = uuid_to_uri_cache.begin(); uuid_to_uri_i != uuid_to_uri_cache.end(); uuid_to_uri_i++ )
    delete uuid_to_uri_i->second;
}

YIELD::ONCRPCRequest* DIRProxy::createONCRPCRequest( YIELD::Object& out_body )
{
  YIELD::auto_Object<org::xtreemfs::interfaces::UserCredentials> user_credentials = new org::xtreemfs::interfaces::UserCredentials;
  policies->getCurrentUserCredentials( *user_credentials.get() );
  return new YIELD::ONCRPCRequest( out_body, object_factories, org::xtreemfs::interfaces::ONCRPC_AUTH_FLAVOR, user_credentials.release() );
}

YIELD::URI DIRProxy::getURIFromUUID( const std::string& uuid )
{
  if ( uuid_to_uri_cache_lock.try_acquire() )
  {
    std::map<std::string, CachedAddressMappingURI*>::iterator uuid_to_uri_i = uuid_to_uri_cache.find( uuid );
    if ( uuid_to_uri_i != uuid_to_uri_cache.end() )
    {
      CachedAddressMappingURI* uri = uuid_to_uri_i->second;
      double uri_age_s = YIELD::Time::getCurrentUnixTimeS()- uri->get_creation_epoch_time_s();
      if ( uri_age_s < uri->get_ttl_s() )
      {
        uuid_to_uri_cache_lock.release();
        return *uri;
      }
      else
      {
        delete uri;
        uuid_to_uri_cache.erase( uuid_to_uri_i );
        uuid_to_uri_cache_lock.release();
      }
    }
    else
      uuid_to_uri_cache_lock.release();
  }

  org::xtreemfs::interfaces::AddressMappingSet address_mappings;
  dir_interface.xtreemfs_address_mappings_get( uuid, address_mappings, this );
  if ( !address_mappings.empty() )
  {
    const org::xtreemfs::interfaces::AddressMapping& address_mapping = address_mappings[0];
    std::ostringstream uri_str;
    uri_str << address_mapping.get_protocol() << "://" << address_mapping.get_address() << ":" << address_mapping.get_port();
    CachedAddressMappingURI* uri = new CachedAddressMappingURI( uri_str.str(), address_mapping.get_ttl_s() );
    uuid_to_uri_cache_lock.acquire();
    uuid_to_uri_cache[uuid] = uri;
    uuid_to_uri_cache_lock.release();
    return *uri;
  }
  else
    throw YIELD::Exception( "could not find address mapping for UUID" );
}

YIELD::URI DIRProxy::getVolumeURIFromVolumeName( const std::string& volume_name )
{
  org::xtreemfs::interfaces::ServiceSet services;
  dir_interface.xtreemfs_service_get_by_name( volume_name, services, this );
  if ( !services.empty() )
  {
    for ( org::xtreemfs::interfaces::ServiceSet::const_iterator service_i = services.begin(); service_i != services.end(); service_i++ )
    {
      const org::xtreemfs::interfaces::ServiceDataMap& data = ( *service_i ).get_data();
      for ( org::xtreemfs::interfaces::ServiceDataMap::const_iterator service_data_i = data.begin(); service_data_i != data.end(); service_data_i++ )
      {
        if ( service_data_i->first == "mrc" )
          return YIELD::URI( getURIFromUUID( service_data_i->second ) );
      }
    }

    throw YIELD::Exception( "unknown volume" );
  }
  else
    throw YIELD::Exception( "unknown volume" );
}

<commit_msg>DIRProxy: IPv6 URI parsing fix<commit_after>// Copyright 2009 Minor Gordon.
// This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions).

#include "org/xtreemfs/client/dir_proxy.h"
#include "org/xtreemfs/interfaces/exceptions.h"
#include "policy_container.h"
using namespace org::xtreemfs::client;

DIRProxy::DIRProxy( const YIELD::URI& uri, YIELD::SSLContext* ssl_context, YIELD::Log* log )
  : YIELD::ONCRPCProxy( uri, ssl_context, log )
{
  dir_interface.registerObjectFactories( object_factories );
  org::xtreemfs::interfaces::Exceptions().registerObjectFactories( object_factories );
  policies = new PolicyContainer;
}

DIRProxy::~DIRProxy()
{
  delete policies;
  for ( std::map<std::string, CachedAddressMappingURI*>::iterator uuid_to_uri_i = uuid_to_uri_cache.begin(); uuid_to_uri_i != uuid_to_uri_cache.end(); uuid_to_uri_i++ )
    delete uuid_to_uri_i->second;
}

YIELD::ONCRPCRequest* DIRProxy::createONCRPCRequest( YIELD::Object& out_body )
{
  YIELD::auto_Object<org::xtreemfs::interfaces::UserCredentials> user_credentials = new org::xtreemfs::interfaces::UserCredentials;
  policies->getCurrentUserCredentials( *user_credentials.get() );
  return new YIELD::ONCRPCRequest( out_body, object_factories, org::xtreemfs::interfaces::ONCRPC_AUTH_FLAVOR, user_credentials.release() );
}

YIELD::URI DIRProxy::getURIFromUUID( const std::string& uuid )
{
  if ( uuid_to_uri_cache_lock.try_acquire() )
  {
    std::map<std::string, CachedAddressMappingURI*>::iterator uuid_to_uri_i = uuid_to_uri_cache.find( uuid );
    if ( uuid_to_uri_i != uuid_to_uri_cache.end() )
    {
      CachedAddressMappingURI* uri = uuid_to_uri_i->second;
      double uri_age_s = YIELD::Time::getCurrentUnixTimeS()- uri->get_creation_epoch_time_s();
      if ( uri_age_s < uri->get_ttl_s() )
      {
        uuid_to_uri_cache_lock.release();
        return *uri;
      }
      else
      {
        delete uri;
        uuid_to_uri_cache.erase( uuid_to_uri_i );
        uuid_to_uri_cache_lock.release();
      }
    }
    else
      uuid_to_uri_cache_lock.release();
  }

  org::xtreemfs::interfaces::AddressMappingSet address_mappings;
  dir_interface.xtreemfs_address_mappings_get( uuid, address_mappings, this );
  if ( !address_mappings.empty() )
  {
    const org::xtreemfs::interfaces::AddressMapping& address_mapping = address_mappings[0];
    std::ostringstream uri_str;
    uri_str << address_mapping.get_protocol() << "://";
    if ( address_mapping.get_address().find( ':' ) != std::string::npos ) // IPv6
    {
      uri_str << "[";
      std::string::size_type percent_sign_pos = address_mapping.get_address().find( '%' );
      if ( percent_sign_pos != std::string::npos ) // Cut off the "zone index, %n at the end of the IPv6 representation
        uri_str << address_mapping.get_address().substr( 0, percent_sign_pos );
      else
        uri_str << address_mapping.get_address();
      uri_str << "]";
    }
    else
      uri_str << address_mapping.get_address();
    uri_str << ":" << address_mapping.get_port();
//    uri_str << address_mapping.get_protocol() << "://" << "localhost" << ":" << address_mapping.get_port();
    CachedAddressMappingURI* uri = new CachedAddressMappingURI( uri_str.str(), address_mapping.get_ttl_s() );
    uuid_to_uri_cache_lock.acquire();
    uuid_to_uri_cache[uuid] = uri;
    uuid_to_uri_cache_lock.release();
    return *uri;
  }
  else
    throw YIELD::Exception( "could not find address mapping for UUID" );
}

YIELD::URI DIRProxy::getVolumeURIFromVolumeName( const std::string& volume_name )
{
  org::xtreemfs::interfaces::ServiceSet services;
  dir_interface.xtreemfs_service_get_by_name( volume_name, services, this );
  if ( !services.empty() )
  {
    for ( org::xtreemfs::interfaces::ServiceSet::const_iterator service_i = services.begin(); service_i != services.end(); service_i++ )
    {
      const org::xtreemfs::interfaces::ServiceDataMap& data = ( *service_i ).get_data();
      for ( org::xtreemfs::interfaces::ServiceDataMap::const_iterator service_data_i = data.begin(); service_data_i != data.end(); service_data_i++ )
      {
        if ( service_data_i->first == "mrc" )
          return YIELD::URI( getURIFromUUID( service_data_i->second ) );
      }
    }

    throw YIELD::Exception( "unknown volume" );
  }
  else
    throw YIELD::Exception( "unknown volume" );
}

<|endoftext|>


<commit_before>#include "simd.hpp"
#include "muglm/muglm_impl.hpp"
#include "util.hpp"
#include "transforms.hpp"
#include <assert.h>
#include <string.h>

using namespace Granite;

int main()
{
	mat4 a(vec4(1, 2, 3, 4), vec4(5, 6, 7, 8), vec4(9, 10, 11, 12), vec4(13, 14, 15, 16));
	mat4 b(vec4(1, 2, 3, 4), vec4(-5, 6, 7, -8), vec4(9, 10, 11, 12), vec4(13, -14, 15, 16));
	mat4 ref = a * b;
	mat4 c;
	SIMD::mul(c, a, b);

	if (memcmp(&ref, &c, sizeof(mat4)) != 0)
	{
		LOGE("Error!\n");
		return 1;
	}

	mat4 test_transform;
	compute_model_transform(test_transform, vec3(8.0f, 6.0f, -3.0f), angleAxis(0.8f, vec3(0.1f, 0.2f, 0.3f)), vec3(8.0f, 1.0f, -0.5f), mat4(1.0f));

	AABB aabb(vec3(-10.0f, 4.0f, 2.0f), vec3(5.0f, 6.0f, 7.0f));
	AABB ref_aabb = aabb.transform(test_transform);
	AABB optim_aabb;
	SIMD::transform_aabb(optim_aabb, aabb, test_transform);
	if (distance(ref_aabb.get_minimum4(), optim_aabb.get_minimum4()) > 0.00001f)
	{
		LOGE("Error!\n");
		return 1;
	}

	if (distance(ref_aabb.get_maximum4(), optim_aabb.get_maximum4()) > 0.00001f)
	{
		LOGE("Error!\n");
		return 1;
	}
}<commit_msg>Basic test of frustum culling code.<commit_after>#include "simd.hpp"
#include "muglm/muglm_impl.hpp"
#include "muglm/matrix_helper.hpp"
#include "util.hpp"
#include "transforms.hpp"
#include "frustum.hpp"
#include <assert.h>
#include <string.h>

using namespace Granite;

static void test_matrix_multiply()
{
	mat4 a(vec4(1, 2, 3, 4), vec4(5, 6, 7, 8), vec4(9, 10, 11, 12), vec4(13, 14, 15, 16));
	mat4 b(vec4(1, 2, 3, 4), vec4(-5, 6, 7, -8), vec4(9, 10, 11, 12), vec4(13, -14, 15, 16));
	mat4 ref = a * b;
	mat4 c;
	SIMD::mul(c, a, b);

	if (memcmp(&ref, &c, sizeof(mat4)) != 0)
	{
		LOGE("Error!\n");
		exit(1);
	}
}

static void test_aabb_transform()
{
	mat4 test_transform;
	compute_model_transform(test_transform, vec3(8.0f, 6.0f, -3.0f), angleAxis(0.8f, vec3(0.1f, 0.2f, 0.3f)), vec3(8.0f, 1.0f, -0.5f), mat4(1.0f));

	AABB aabb(vec3(-10.0f, 4.0f, 2.0f), vec3(5.0f, 6.0f, 7.0f));
	AABB ref_aabb = aabb.transform(test_transform);
	AABB optim_aabb;
	SIMD::transform_aabb(optim_aabb, aabb, test_transform);
	if (distance(ref_aabb.get_minimum4(), optim_aabb.get_minimum4()) > 0.00001f)
	{
		LOGE("Error!\n");
		exit(1);
	}

	if (distance(ref_aabb.get_maximum4(), optim_aabb.get_maximum4()) > 0.00001f)
	{
		LOGE("Error!\n");
		exit(1);
	}
}

static void test_frustum_cull()
{
	mat4 m = projection(0.4f, 1.0f, 0.1f, 5.0f);
	Frustum frustum;
	frustum.build_planes(inverse(m));

	for (int z = -10; z <= 10; z++)
	{
		for (int y = -10; y <= 10; y++)
		{
			for (int x = -10; x <= 10; x++)
			{
				AABB aabb(vec3(x, y, z) * 0.25f - 0.1f, vec3(x, y, z) * 0.25f + 0.1f);
				bool slow_test = frustum.intersects(aabb);
				bool fast_test = SIMD::frustum_cull(aabb, frustum.get_planes());
				if (slow_test != fast_test)
				{
					LOGE("Frustum cull mismatch.\n");
					exit(1);
				}
			}
		}
	}
}

int main()
{
	test_matrix_multiply();
	test_aabb_transform();
	test_frustum_cull();
}<|endoftext|>


<commit_before><commit_msg>Stop to override real error message on creating index<commit_after><|endoftext|>


<commit_before>/*
 * urdftorob.cpp
 *
 *  Created on: Jun 07, 2013
 *      Author: jingru
 */
#include "Modeling/Robot.h"
#include <string.h>
#include <utils/stringutils.h>
#include "IO/URDFConverter.h"
#include <utils/AnyCollection.h>
#include <fstream>
#include <string.h>

using namespace std;

class ProgramSettings : public AnyCollection
{
public:
  ProgramSettings() { }

  bool read(const char* fn) {
    ifstream in(fn,ios::in);
    if(!in) return false;
    AnyCollection newEntries;
    if(!newEntries.read(in)) return false;
    merge(newEntries);
    return true;
  }
  bool write(const char* fn) {
    ofstream out(fn,ios::out);
    if(!out) return false;
    AnyCollection::write(out);
    out.close();
    return true;
  }
};

int URDFtoRob(AnyCollection settings,string infile,string outfile){
  string path = GetFilePath(outfile.c_str());

  Robot robot;

  URDFConverter::useVisGeom = settings["useVisGeom"];
  URDFConverter::flipYZ = settings["flipYZ"];
  settings["packageRootPath"].as(URDFConverter::packageRootPath);
  string geomPrefix,geomExtension;
  settings["outputGeometryPrefix"].as(geomPrefix);
  settings["outputGeometryExtension"].as(geomExtension);
  robot.LoadURDF(infile.c_str());
  robot.SetGeomFiles(geomPrefix.c_str(),geomExtension.c_str());
  robot.Save(outfile.c_str());
  if(!geomExtension.empty()) {
    //save in absolute path
    robot.SaveGeometry(path.c_str());
  }
  return 1;
}

int main_shell(int argc, char** argv)
{
  ProgramSettings settings;
  settings["useVisGeom"] = false;
  settings["flipYZ"] = false;
  settings["outputGeometryExtension"] = string("tri");
  settings["outputGeometryPrefix"] = string("");
  settings["packageRootPath"] = string("");
  if(!settings.read("urdftorob.settings")) {
    printf("Didn't read settings from urdftorob.settings\n");
    printf("Writing default settings to urdftorob_default.settings\n");
    settings.write("urdftorob_default.settings");
  }

  if (argc < 2 || argc > 3) {
    printf(
	   "USAGE: URDFtoRob robot_file.urdf [optional filename for .rob]\n");
    return 0;
  }

  string infile=argv[1],outfile;

  if(argc == 2) {
    outfile.assign(argv[1]);
    StripExtension(outfile);
    outfile.append(".rob");
  }
  else if(argc == 3)
    outfile.assign(argv[2]);

  const char* ext = FileExtension(argv[1]);
  if (0 == strcmp(ext, "urdf")) {
    URDFtoRob(settings,infile,outfile);
    cout<<"Converted "<<infile<<" to "<< outfile<<endl;
    cout << "Done!" << endl;
    return 1;
  }
  else {
    printf("Unknown file extension %s on file %s!\nOnly converts URDF to Rob", ext, argv[1]);
    return 0;
  }
}
#ifndef HAVE_QT
int main(int argc,char** argv){
    main_shell(argc,argv);
}
#endif

<commit_msg>Only changes geometry extensions if string is non empty<commit_after>/*
 * urdftorob.cpp
 *
 *  Created on: Jun 07, 2013
 *      Author: jingru
 */
#include "Modeling/Robot.h"
#include <string.h>
#include <utils/stringutils.h>
#include "IO/URDFConverter.h"
#include <utils/AnyCollection.h>
#include <fstream>
#include <string.h>

using namespace std;

class ProgramSettings : public AnyCollection
{
public:
  ProgramSettings() { }

  bool read(const char* fn) {
    ifstream in(fn,ios::in);
    if(!in) return false;
    AnyCollection newEntries;
    if(!newEntries.read(in)) return false;
    merge(newEntries);
    return true;
  }
  bool write(const char* fn) {
    ofstream out(fn,ios::out);
    if(!out) return false;
    AnyCollection::write(out);
    out.close();
    return true;
  }
};

int URDFtoRob(AnyCollection settings,string infile,string outfile){
  string path = GetFilePath(outfile.c_str());

  Robot robot;

  URDFConverter::useVisGeom = settings["useVisGeom"];
  URDFConverter::flipYZ = settings["flipYZ"];
  settings["packageRootPath"].as(URDFConverter::packageRootPath);
  string geomPrefix,geomExtension;
  settings["outputGeometryPrefix"].as(geomPrefix);
  settings["outputGeometryExtension"].as(geomExtension);
  robot.LoadURDF(infile.c_str());
  if(!geomExtension.empty()) {
    //change the geometry file extension
    robot.SetGeomFiles(geomPrefix.c_str(),geomExtension.c_str());
  }
  robot.Save(outfile.c_str());
  if(!geomExtension.empty()) {
    //save in absolute path
    robot.SaveGeometry(path.c_str());
  }
  return 1;
}

int main_shell(int argc, char** argv)
{
  ProgramSettings settings;
  settings["useVisGeom"] = false;
  settings["flipYZ"] = false;
  settings["outputGeometryExtension"] = string("tri");
  settings["outputGeometryPrefix"] = string("");
  settings["packageRootPath"] = string("");
  if(!settings.read("urdftorob.settings")) {
    printf("Didn't read settings from urdftorob.settings\n");
    printf("Writing default settings to urdftorob_default.settings\n");
    settings.write("urdftorob_default.settings");
  }

  if (argc < 2 || argc > 3) {
    printf(
	   "USAGE: URDFtoRob robot_file.urdf [optional filename for .rob]\n");
    return 0;
  }

  string infile=argv[1],outfile;

  if(argc == 2) {
    outfile.assign(argv[1]);
    StripExtension(outfile);
    outfile.append(".rob");
  }
  else if(argc == 3)
    outfile.assign(argv[2]);

  const char* ext = FileExtension(argv[1]);
  if (0 == strcmp(ext, "urdf")) {
    URDFtoRob(settings,infile,outfile);
    cout<<"Converted "<<infile<<" to "<< outfile<<endl;
    cout << "Done!" << endl;
    return 1;
  }
  else {
    printf("Unknown file extension %s on file %s!\nOnly converts URDF to Rob", ext, argv[1]);
    return 0;
  }
}
#ifndef HAVE_QT
int main(int argc,char** argv){
    main_shell(argc,argv);
}
#endif

<|endoftext|>


<commit_before>/*{{{
    Copyright © 2013 Matthias Kretz <kretz@kde.org>

    Permission to use, copy, modify, and distribute this software
    and its documentation for any purpose and without fee is hereby
    granted, provided that the above copyright notice appear in all
    copies and that both that the copyright notice and this
    permission notice and warranty disclaimer appear in supporting
    documentation, and that the name of the author not be used in
    advertising or publicity pertaining to distribution of the
    software without specific, written prior permission.

    The author disclaim all warranties with regard to this
    software, including all implied warranties of merchantability
    and fitness.  In no event shall the author be liable for any
    special, indirect or consequential damages or any damages
    whatsoever resulting from loss of use, data or profits, whether
    in an action of contract, negligence or other tortious action,
    arising out of or in connection with the use or performance of
    this software.

}}}*/

#define VC_NEWTEST
#include "unittest.h"
#include <Vc/array>
#include <Vc/vector>
#include "../common/subscript.h"

TEST_BEGIN(V, init, (ALL_VECTORS))
{
    typedef typename V::EntryType T;
    Vc::array<T, 256> data;
    Vc::vector<T> data2(256);
    for (int i = 0; i < data.size(); ++i) {
        data[i] = i;
        data2[i] = i;
    }

    Vc::vector<T> ctorTest1(6, T());
    Vc::vector<T> ctorTest2{T(), T()};
    COMPARE(ctorTest1.size(), 6);
    COMPARE(ctorTest2.size(), 2);
}
TEST_END

TEST_BEGIN(V, gathers, (SIMD_ARRAYS(32), ALL_VECTORS))
{
    typedef typename V::EntryType T;
    typedef typename V::IndexType IT;
    Vc::array<T, 256> data;
    Vc::vector<T> data2(256);
    for (int i = 0; i < data.size(); ++i) {
        data[i] = i;
        data2[i] = i;
    }

    V test = data[IT::IndexesFromZero()];
    COMPARE(test, V::IndexesFromZero());
    test = data2[IT::IndexesFromZero()];
    COMPARE(test, V::IndexesFromZero());

    IT indexes = abs(IT::Random()) % 256;
    test = data[indexes];
    COMPARE(test, static_cast<V>(indexes));
    test = data2[indexes];
    COMPARE(test, static_cast<V>(indexes));
}
TEST_END

TEST_BEGIN(V, scatters, (SIMD_ARRAYS(32), ALL_VECTORS))
{
    typedef typename V::EntryType T;
    typedef typename V::IndexType IT;
    Vc::array<T, 256> data1;
    Vc::vector<T> data2(256);
    std::fill_n(&data1[0], 256, 0);
    std::fill_n(&data2[0], 256, 0);

    data1[IT::IndexesFromZero()] = V::IndexesFromZero();
    data2[IT::IndexesFromZero()] = V::IndexesFromZero();

    for (size_t i = 0; i < V::Size; ++i) {
        COMPARE(data1[i], i);
        COMPARE(data2[i], i);
    }

    for (int repetition = 0; repetition < 1024 / V::Size; ++repetition) {
        IT indexes = abs(IT::Random()) % 256;
        data1[indexes] = V::IndexesFromZero();
        data2[indexes] = V::IndexesFromZero();

        for (size_t i = 0; i < V::Size; ++i) {
            COMPARE(data1[indexes[i]], i);
            COMPARE(data2[indexes[i]], i);
        }
    }
}
TEST_END

TEST_BEGIN(V, fixedWidthGathers, (SIMD_ARRAYS(4)))
{
    typedef typename V::EntryType T;
    typedef typename V::IndexType IT;
    Vc::array<T, 256> data;
    Vc::vector<T> data2(256);
    for (int i = 0; i < data.size(); ++i) {
        data[i] = i;
        data2[i] = i;
    }
    V test;

    const auto indexes = { 0, 5, 8, 3 };
    test = data[indexes];
    COMPARE(test, static_cast<V>(indexes));
    test = data2[indexes];
    COMPARE(test, static_cast<V>(indexes));
}
TEST_END
<commit_msg>subscript test: more tests of the subscript operators<commit_after>/*{{{
    Copyright © 2013 Matthias Kretz <kretz@kde.org>

    Permission to use, copy, modify, and distribute this software
    and its documentation for any purpose and without fee is hereby
    granted, provided that the above copyright notice appear in all
    copies and that both that the copyright notice and this
    permission notice and warranty disclaimer appear in supporting
    documentation, and that the name of the author not be used in
    advertising or publicity pertaining to distribution of the
    software without specific, written prior permission.

    The author disclaim all warranties with regard to this
    software, including all implied warranties of merchantability
    and fitness.  In no event shall the author be liable for any
    special, indirect or consequential damages or any damages
    whatsoever resulting from loss of use, data or profits, whether
    in an action of contract, negligence or other tortious action,
    arising out of or in connection with the use or performance of
    this software.

}}}*/

#define VC_NEWTEST
#include "unittest.h"
#include <Vc/array>
#include <Vc/vector>
#include "../common/subscript.h"

TEST_BEGIN(V, init, (ALL_VECTORS))
{
    typedef typename V::EntryType T;
    Vc::array<T, 256> data;
    Vc::vector<T> data2(256);
    for (int i = 0; i < data.size(); ++i) {
        data[i] = i;
        data2[i] = i;
    }

    std::initializer_list<T> initList1 = {T(), T()};
    const std::initializer_list<T> initList2 = {T(), T()};

    Vc::vector<T> ctorTest1(6, T());
    Vc::vector<T> ctorTest2{T(), T()};
    Vc::vector<T> ctorTest3 = initList1;
    Vc::vector<T> ctorTest4 = initList2;
    Vc::vector<T> ctorTest5(initList1);
    Vc::vector<T> ctorTest6(initList2);
    COMPARE(ctorTest1.size(), 6);
    COMPARE(ctorTest2.size(), 2);
    COMPARE(ctorTest3.size(), 2);
    COMPARE(ctorTest4.size(), 2);
    COMPARE(ctorTest5.size(), 2);
    COMPARE(ctorTest6.size(), 2);
}
TEST_END

template <typename V>
static typename std::enable_if<Vc::is_unsigned<V>::value, V>::type positiveRandom()
{
    return V::Random();
}
template <typename V>
static typename std::enable_if<!Vc::is_unsigned<V>::value, V>::type positiveRandom()
{
    return abs(V::Random());
}

template <typename V, int Modulo> static V randomIndexes()
{
    V indexes = positiveRandom<V>() % Modulo;
    for (std::size_t i = 0; i < V::Size; ++i) {
        while ((indexes == static_cast<int>(indexes[i])).count() !=
               1) {  // the static_cast prevents an ICE with GCC 4.8.1
            indexes[i] = (indexes[i] + 1) % Modulo;
        }
    }
    return indexes;
}

TEST_BEGIN(V, gathers, (SIMD_ARRAYS(32), ALL_VECTORS))
{
    typedef typename V::EntryType T;
    typedef typename V::IndexType IT;
    Vc::array<T, 256> data;
    Vc::vector<T> data2(256);
    for (int i = 0; i < data.size(); ++i) {
        data[i] = i;
        data2[i] = i;
    }

    V test = data[IT::IndexesFromZero()];
    COMPARE(test, V::IndexesFromZero());
    test = data2[IT::IndexesFromZero()];
    COMPARE(test, V::IndexesFromZero());

    for (int repetition = 0; repetition < 1024 / V::Size; ++repetition) {
        const IT indexes = randomIndexes<IT, 256>();
        test = data[indexes];
        COMPARE(test, static_cast<V>(indexes));
        test = data2[indexes];
        COMPARE(test, static_cast<V>(indexes));
    }
}
TEST_END

template <typename T, std::size_t N>
std::ostream &operator<<(std::ostream &s, const Vc::array<T, N> &data)
{
    for (std::size_t i = 0; i < N; ++i) {
        s << data[i];
        if (i % 32 == 31) {
            s << '\n';
        } else {
            s << ' ';
        }
    }
    s << std::setw(0);
    return s;
}

TEST_BEGIN(V, scatters, (SIMD_ARRAYS(32), ALL_VECTORS))
{
    static_assert(std::is_same<decltype(V() + 1), V>::value, "");
    typedef typename V::EntryType T;
    typedef typename V::IndexType IT;
    Vc::array<T, 256> data1;
    Vc::vector<T> data2(256);
    std::fill_n(&data1[0], 256, 0);
    std::fill_n(&data2[0], 256, 0);

    data1[IT::IndexesFromZero()] = V::IndexesFromZero();
    data2[IT::IndexesFromZero()] = V::IndexesFromZero();

    for (size_t i = 0; i < V::Size; ++i) {
        COMPARE(data1[i], i);
        COMPARE(data2[i], i);
    }

    for (int repetition = 0; repetition < 1024 / V::Size; ++repetition) {
        std::fill_n(&data1[0], 256, 0);
        std::fill_n(&data2[0], 256, 0);

        const IT indexes = randomIndexes<IT, 256>();
        data1[indexes] = V::IndexesFromZero() + 1;
        data2[indexes] = V::IndexesFromZero() + 1;

        //std::cerr << data1 << '\n';

        for (size_t i = 0; i < V::Size; ++i) {
            COMPARE(data1[indexes[i]], i + 1) << indexes[i];
            COMPARE(data2[indexes[i]], i + 1) << indexes[i];
        }
    }
}
TEST_END

template <typename T> struct S
{
    void operator=(int x)
    {
        a = x;
        b = x + 1;
        c = x + 2;
    }
    double x0;
    T a;
    char x1;
    T b;
    short x2;
    T c;
    char x3;
};

TEST_BEGIN(V, structGathers, (SIMD_ARRAYS(32), ALL_VECTORS))
{
    typedef typename V::EntryType T;
    typedef typename V::IndexType IT;
    Vc::array<S<T>, 256> data1;
    Vc::array<S<S<T>>, 256> data2;
    Vc::array<S<S<S<T>>>, 256> data3;
    Vc::array<S<S<S<S<T>>>>, 256> data4;
    for (int i = 0; i < 256; ++i) {
        data1[i] = i;
        data2[i] = i;
        data3[i] = i;
        data4[i] = i;
    }

    V test;

    test = data1[IT::IndexesFromZero()][&S<T>::a];
    COMPARE(test, V::IndexesFromZero());
    test = data1[IT::IndexesFromZero()][&S<T>::b];
    COMPARE(test, V::IndexesFromZero() + 1);
    test = data1[IT::IndexesFromZero()][&S<T>::c];
    COMPARE(test, V::IndexesFromZero() + 2);

    test = data2[IT::IndexesFromZero()][&S<S<T>>::a][&S<T>::a];
    COMPARE(test, V::IndexesFromZero());
    test = data2[IT::IndexesFromZero()][&S<S<T>>::b][&S<T>::c];
    COMPARE(test, V::IndexesFromZero() + 3);

    test = data3[IT::IndexesFromZero()][&S<S<S<T>>>::a][&S<S<T>>::a][&S<T>::a];
    COMPARE(test, V::IndexesFromZero());
    test = data3[IT::IndexesFromZero()][&S<S<S<T>>>::b][&S<S<T>>::c][&S<T>::b];
    COMPARE(test, V::IndexesFromZero() + 4);

    test = data4[IT::IndexesFromZero()][&S<S<S<S<T>>>>::a][&S<S<S<T>>>::a][&S<S<T>>::a][&S<T>::a];
    COMPARE(test, V::IndexesFromZero());
    test = data4[IT::IndexesFromZero()][&S<S<S<S<T>>>>::a][&S<S<S<T>>>::a][&S<S<T>>::a][&S<T>::b];
    COMPARE(test, V::IndexesFromZero() + 1);
    test = data4[IT::IndexesFromZero()][&S<S<S<S<T>>>>::a][&S<S<S<T>>>::a][&S<S<T>>::b][&S<T>::a];
    COMPARE(test, V::IndexesFromZero() + 1);
    test = data4[IT::IndexesFromZero()][&S<S<S<S<T>>>>::c][&S<S<S<T>>>::b][&S<S<T>>::b][&S<T>::c];
    COMPARE(test, V::IndexesFromZero() + 6);

    for (int repetition = 0; repetition < 1024 / V::Size; ++repetition) {
        const IT indexes = randomIndexes<IT, 256>();
        test = data1[indexes][&S<T>::b];
        COMPARE(test, static_cast<V>(indexes + 1));

        test = data2[indexes][&S<S<T>>::c][&S<T>::b];
        COMPARE(test, static_cast<V>(indexes + 3));

        test = data3[indexes][&S<S<S<T>>>::b][&S<S<T>>::c][&S<T>::b];
        COMPARE(test, static_cast<V>(indexes + 4));

        test = data4[indexes][&S<S<S<S<T>>>>::c][&S<S<S<T>>>::b][&S<S<T>>::c][&S<T>::b];
        COMPARE(test, static_cast<V>(indexes + 6));
    }
}
TEST_END

TEST_BEGIN(V, subarrayGathers, (SIMD_ARRAYS(32), ALL_VECTORS))
{
    typedef typename V::EntryType T;
    typedef typename V::IndexType IT;
    Vc::array<Vc::array<T, 256>, 256> data1;
    for (int i = 0; i < 256; ++i) {
        for (int j = 0; j < 256; ++j) {
            data1[i][j] = i + j;
        }
    }

    V test;

    test = data1[IT::IndexesFromZero()][0];
    COMPARE(test, V::IndexesFromZero());
    test = data1[IT::IndexesFromZero()][255];
    COMPARE(test, V::IndexesFromZero() + 255);
    test = data1[254][IT::IndexesFromZero()];
    COMPARE(test, V::IndexesFromZero() + 254);

    test = data1[IT::IndexesFromZero()][IT::IndexesFromZero()];
    COMPARE(test, V::IndexesFromZero() * 2);

    for (int repetition = 0; repetition < 1024 / V::Size; ++repetition) {
        const IT indexes1 = randomIndexes<IT, 256>();
        const IT indexes2 = randomIndexes<IT, 256>();

        test = data1[indexes1][indexes2];
        COMPARE(test, static_cast<V>(indexes1 + indexes2));
    }

    Vc::vector<std::array<T, 256>> data2(64);
    for (int i = 0; i < 64; ++i) {
        for (int j = 0; j < 256; ++j) {
            data2[i][j] = i + j;
        }
    }

    test = data2[IT::IndexesFromZero()][0];
    COMPARE(test, V::IndexesFromZero());
}
TEST_END

TEST_BEGIN(V, fixedWidthGatherScatter4, (SIMD_ARRAYS(4)))
{
    typedef typename V::EntryType T;
    typedef typename V::IndexType IT;
    Vc::array<T, 256> data;
    Vc::vector<T> data2(256);
    for (int i = 0; i < data.size(); ++i) {
        data[i] = i;
        data2[i] = i;
    }
    V test;

    const std::initializer_list<int> indexes = { 0, 5, 8, 3 };
    test = data[indexes];
    const V reference = {0, 5, 8, 3};
    COMPARE(test, reference);
    test = data2[indexes];
    COMPARE(test, reference);

    /*
    test = V::Random();
    data[indexes] = test;
    data2[indexes] = test;

    std::size_t i = 0;
    for (const auto x : indexes) {
        COMPARE(data[x], test[i]);
        COMPARE(data2[x], test[i]);
        ++i;
    }
    */
}
TEST_END

TEST_BEGIN(V, fixedWidthGatherScatter32, (SIMD_ARRAYS(32)))
{
    typedef typename V::EntryType T;
    typedef typename V::IndexType IT;
    Vc::array<T, 256> data;
    Vc::vector<T> data2(256);
    for (int i = 0; i < data.size(); ++i) {
        data[i] = i;
        data2[i] = i;
    }
    V test;
    const std::initializer_list<int> indexes = {73, 17, 15, 0,  38, 74, 25, 41, 7, 28, 68,
                                                2,  23, 98, 5,  87, 72, 18, 16, 1, 39, 75,
                                                26, 42, 8,  29, 69, 3,  24, 99, 6, 88};
    test = data[indexes];
    const V reference = {73, 17, 15, 0, 38, 74, 25, 41, 7, 28, 68, 2, 23, 98, 5, 87,
                         72, 18, 16, 1, 39, 75, 26, 42, 8, 29, 69, 3, 24, 99, 6, 88};
    COMPARE(test, reference);
    test = data2[indexes];
    COMPARE(test, reference);
}
TEST_END

TEST(promotionOfIndexVectorType)
{
    Vc::array<Vc::array<int, 1024>, 1024> data;
    int *ptr = &data[0][0];
    for (std::size_t i = 0; i < 1024 * 1024; ++i) {
        ptr[i] = i;
    }

    const Vc::short_v indexes = 1023 - Vc::short_v::IndexesFromZero();
    Vc::int_v reference = static_cast<Vc::int_v>(indexes) * 1024;
    Vc::int_v test = data[indexes][0];
    COMPARE(test, reference);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <map>

int main( ) {
  std::string File;
  unsigned int BlockNo = 1;
  unsigned int EmptyBlocks = 0;
  unsigned char TempChar[188];
  unsigned char Skip;
  unsigned int SkippedBytes = 0;
  unsigned int Adaptation;
  std::map<int,int> PMTs;
  while( std::cin.good( ) && BlockNo <= 5) {
    for( int i = 0; i < 188; i++ ) {
      TempChar[i] = std::cin.get();
    }

    if( ( ( TempChar[1] & 0x1F ) << 8 ) + ( TempChar[2] ) != 0x1FFF ) {
      printf( "Block %d:\n", BlockNo );
      printf( "\tSync Byte:\t\t\t%X\n", TempChar[0] );
      printf( "\tTransport Error Indicator:\t%d\n", ( ( TempChar[1] & 0x80 ) != 0 ) );
      printf( "\tPayload Unit Start Indicator:\t%d\n", ( ( TempChar[1] & 0x40 ) != 0 ) );
      printf( "\tTransport Priority:\t\t%d\n", ( ( TempChar[1] & 0x20 ) != 0 ) );
      printf( "\tPID:\t\t\t\t%X\n", ( ( TempChar[1] & 0x1F ) << 8 ) + ( TempChar[2] ) );
      printf( "\tScrambling control:\t\t%d%d\n", ( ( TempChar[3] & 0x80 ) != 0 ), ( ( TempChar[3] & 0x40 ) != 0 ) );
      printf( "\tAdaptation Field Exists:\t%d%d\n", ( ( TempChar[3] & 0x20 ) != 0 ), ( ( TempChar[3] & 0x10 ) != 0 ) );
      printf( "\tContinuity Counter:\t\t%X\n", ( TempChar[3] & 0x0F ) );

      Adaptation = ( ( TempChar[3] & 0x30 ) >> 4 );

      //Adaptation Field Exists
      if( Adaptation == 2 || Adaptation == 3 ) {
        printf( "\tAdaptation Field:\n" );
        printf( "\t\tNOT IMPLEMENTED YET!!\n" );
      }

      if( ( ( ( TempChar[1] & 0x1F ) << 8 ) +  TempChar[2] ) == 0 ) {
        printf( "\tProgram Association Table\n" );
        printf( "\t\tpointer_field:\t\t\t%X\n", TempChar[4] );
        printf( "\t\ttable_id:\t\t\t%X\n", TempChar[5] );
        printf( "\t\tsection_syntax_indicator:\t%d\n", ( ( TempChar[6] & 0x80 ) != 0 ) );
        printf( "\t\t0:\t\t\t\t%d\n", ( ( TempChar[6] & 0x40 ) != 0 ) );
        printf( "\t\treserved:\t\t\t%d\n", ( ( TempChar[6] & 0x30 ) >> 4 ) );
        printf( "\t\tsection_length:\t\t\t%X\n", ( ( TempChar[6] & 0x0F ) << 8 ) + TempChar[7] );
        printf( "\t\ttransport_stream_id\t\t%X\n", ( ( TempChar[8] << 8 ) + TempChar[9] ) );
        printf( "\t\treserved:\t\t\t%d\n", ( ( TempChar[10] & 0xC0 ) >> 6 ) );
        printf( "\t\tversion_number:\t\t\t%X\n", ( ( TempChar[10] & 0x3E ) >> 1 ) );
        printf( "\t\tcurrent_next_indicator:\t\t%d\n", ( ( TempChar[10] & 0x01 ) != 0 ) );
        printf( "\t\tsection_number:\t\t\t%X\n", TempChar[11] );
        printf( "\t\tlast_section_number:\t\t%d\n", TempChar[12] );
        int SectionLength = ( ( TempChar[6] & 0x0F ) << 8 ) + TempChar[7];
        for( int i = 0; i < SectionLength - 9; i += 4 ) {
          printf( "\t\tENTRY %d:\n", i / 4 );
          printf( "\t\t\tProgram Number:\t%X\n", ( TempChar[13+i] << 8 ) + TempChar[14+i] );
          printf( "\t\t\tReserved:\t%X\n", ( TempChar[15+i] & 0xE0 ) >> 5 );
          if( ( ( TempChar[13+i] << 8 ) + TempChar[14+i] ) == 0 ) {
            printf( "\t\t\tnetwork_PID:\t\t%X\n", ( ( TempChar[15+i] & 0x1F ) << 8 ) + TempChar[16+i] );
          } else {
            printf( "\t\t\tprogram_map_PID:\t\t%X\n", ( ( TempChar[15+i] & 0x1F ) << 8 ) + TempChar[16+i] );
          }
        }
        printf( "\t\tCRC_32\t\t\t\t%x\n", ( TempChar[8+SectionLength-4] << 24 ) + ( TempChar[8+SectionLength-3] << 16 ) + ( TempChar[8+SectionLength-2] << 8 ) + ( TempChar[8+SectionLength-1] ) );
      }

      BlockNo ++;

    }
  else {
      EmptyBlocks ++;
    }

    //Find Next Sync Byte
    SkippedBytes = 0;
    while( (int)std::cin.peek( ) != 0x47 ) {
      std::cin >> Skip;
      SkippedBytes ++;
    }
  }
  return 0;
}
<commit_msg>PAT Rewriting<commit_after>#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <vector>

struct program_association_table_entry {
  unsigned int Program_Num;
  unsigned char Reserved;
  unsigned int Program_PID;
};

struct program_association_table {
  unsigned char Pointer_Field;
  unsigned char Table_ID;
  bool Section_Syntax_Indicator;
  bool Zero;
  unsigned char Reserved_1;
  unsigned int Section_Length;
  unsigned int Transport_Stream_ID;
  unsigned char Reserved_2;
  unsigned char Version_Number;
  bool Current_Next_Indicator;
  unsigned char Section_Number;
  unsigned char Last_Section_Number;
  std::vector<program_association_table_entry> Entries;
  unsigned int CRC_32;
};

void print_pat( program_association_table PAT, bool Pointer_Field = false, std::string offset="\t" ) {
  printf( "\tProgram Association Table\n" );
  if( Pointer_Field ) {
    printf( "%s\tPointer Field:\t\t\t%X\n", offset.c_str(), PAT.Pointer_Field );
  }
  printf( "%s\tTable ID:\t\t\t%X\n", offset.c_str(), PAT.Table_ID );
  printf( "%s\tSection Syntax Indicator:\t%d\n", offset.c_str(), PAT.Section_Syntax_Indicator );
}

int main( ) {
  std::string File;
  unsigned int BlockNo = 1;
  unsigned int EmptyBlocks = 0;
  unsigned char TempChar[188];
  unsigned char Skip;
  unsigned int SkippedBytes = 0;
  unsigned int Adaptation;
  while( std::cin.good( ) && BlockNo <= 4) {
    for( int i = 0; i < 188; i++ ) {
      TempChar[i] = std::cin.get();
    }

    if( ( ( TempChar[1] & 0x1F ) << 8 ) + ( TempChar[2] ) != 0x1FFF ) {
      printf( "Block %d:\n", BlockNo );
      printf( "\tSync Byte:\t\t\t%X\n", TempChar[0] );
      printf( "\tTransport Error Indicator:\t%d\n", ( ( TempChar[1] & 0x80 ) != 0 ) );
      printf( "\tPayload Unit Start Indicator:\t%d\n", ( ( TempChar[1] & 0x40 ) != 0 ) );
      printf( "\tTransport Priority:\t\t%d\n", ( ( TempChar[1] & 0x20 ) != 0 ) );
      printf( "\tPID:\t\t\t\t%X\n", ( ( TempChar[1] & 0x1F ) << 8 ) + ( TempChar[2] ) );
      printf( "\tScrambling control:\t\t%d%d\n", ( ( TempChar[3] & 0x80 ) != 0 ), ( ( TempChar[3] & 0x40 ) != 0 ) );
      printf( "\tAdaptation Field Exists:\t%d%d\n", ( ( TempChar[3] & 0x20 ) != 0 ), ( ( TempChar[3] & 0x10 ) != 0 ) );
      printf( "\tContinuity Counter:\t\t%X\n", ( TempChar[3] & 0x0F ) );

      Adaptation = ( ( TempChar[3] & 0x30 ) >> 4 );

      //Adaptation Field Exists
      if( Adaptation == 2 || Adaptation == 3 ) {
        printf( "\tAdaptation Field:\n" );
        printf( "\t\tNOT IMPLEMENTED YET!!\n" );
      }

      if( ( ( ( TempChar[1] & 0x1F ) << 8 ) +  TempChar[2] ) == 0 ) {
        printf( "\tProgram Association Table\n" );
        printf( "\t\tpointer_field:\t\t\t%X\n", TempChar[4] );
        printf( "\t\ttable_id:\t\t\t%X\n", TempChar[5] );
        printf( "\t\tsection_syntax_indicator:\t%d\n", ( ( TempChar[6] & 0x80 ) != 0 ) );

        printf( "\t\t0:\t\t\t\t%d\n", ( ( TempChar[6] & 0x40 ) != 0 ) );
        printf( "\t\treserved:\t\t\t%d\n", ( ( TempChar[6] & 0x30 ) >> 4 ) );
        printf( "\t\tsection_length:\t\t\t%X\n", ( ( TempChar[6] & 0x0F ) << 8 ) + TempChar[7] );
        printf( "\t\ttransport_stream_id\t\t%X\n", ( ( TempChar[8] << 8 ) + TempChar[9] ) );
        printf( "\t\treserved:\t\t\t%d\n", ( ( TempChar[10] & 0xC0 ) >> 6 ) );
        printf( "\t\tversion_number:\t\t\t%X\n", ( ( TempChar[10] & 0x3E ) >> 1 ) );
        printf( "\t\tcurrent_next_indicator:\t\t%d\n", ( ( TempChar[10] & 0x01 ) != 0 ) );
        printf( "\t\tsection_number:\t\t\t%X\n", TempChar[11] );
        printf( "\t\tlast_section_number:\t\t%d\n", TempChar[12] );
        int SectionLength = ( ( TempChar[6] & 0x0F ) << 8 ) + TempChar[7];
        for( int i = 0; i < SectionLength - 9; i += 4 ) {
          printf( "\t\tENTRY %d:\n", i / 4 );
          printf( "\t\t\tProgram Number:\t%X\n", ( TempChar[13+i] << 8 ) + TempChar[14+i] );
          printf( "\t\t\tReserved:\t%X\n", ( TempChar[15+i] & 0xE0 ) >> 5 );
          if( ( ( TempChar[13+i] << 8 ) + TempChar[14+i] ) == 0 ) {
            printf( "\t\t\tnetwork_PID:\t\t%X\n", ( ( TempChar[15+i] & 0x1F ) << 8 ) + TempChar[16+i] );
          } else {
            printf( "\t\t\tprogram_map_PID:\t\t%X\n", ( ( TempChar[15+i] & 0x1F ) << 8 ) + TempChar[16+i] );
          }
        }
        printf( "\t\tCRC_32\t\t\t\t%x\n", ( TempChar[8+SectionLength-4] << 24 ) + ( TempChar[8+SectionLength-3] << 16 ) + ( TempChar[8+SectionLength-2] << 8 ) + ( TempChar[8+SectionLength-1] ) );
      }

      BlockNo ++;

    }
  else {
      EmptyBlocks ++;
    }

    //Find Next Sync Byte
    SkippedBytes = 0;
    while( (int)std::cin.peek( ) != 0x47 ) {
      std::cin >> Skip;
      SkippedBytes ++;
    }
  }
  return 0;
}
<|endoftext|>


<commit_before>// This file (SampleCode.cpp) was converted from SampleCode.Bas
// with uCalc Transform 2.5 on 1/21/2014 3:11:55 PM using the Open Source
// PowerBASIC to C++ converter found at https://github.com/uCalc/powerbasic-to-cpp

#include <Windows.h>
#include <math.h>
#include <string>
using namespace std;

//  File name: SampleCode.Bas
//  To convert this file to C++ make sure you have uCalc Transform on your PC
//  and *.uc from github.com/uCalc/powerbasic-to-cpp/tree/master/convert
//  Do the following at the Command Prompt:
//
//  C:\> PBtoCPP.Bat SampleCode.Bas

const int MyEquate = 0x100;
const int Other = 0x200;

int ProgStatus;

#if defined Other
//  Something
#elif !defined abcd
//  Something else
#else
//  Etc
#endif

#define MyMacroNum 12345
#define MyMacro(a, b, c) (a + b * (c))

struct point {
   int x;
   int y;
};

struct MyBits {
   unsigned int Year : 7;
   unsigned int Month : 5;
   unsigned int DayOfMonth : 4;
   unsigned int DayOfWeek : 3;
   unsigned char Red : 1;
   unsigned char Blue : 1;
   unsigned char Green : 1;
   double Other;
};

int MyFunc(int x)
{
   return x * 2;
}

int MyFunction(int a, float& b)
{
   int x;
   int y;
   int *Test = new int [a+25+1];
   int yVar;
   int MyValue;
   //  Dim q As Long
   //  The commented line above is not translated

   MyFunc(a);
   x = MyFunc(b)+1;

   if (b > 5) {
      for (x=1; x<=10; x += 1) {
         for (yVar=10; yVar>=1; yVar += -1) {
            if (x > y) {
               return a+y;
            }
            while (Test[a+5] == yVar) {
               while (!(a+1 == 1234)) {
                  if (y < MyEquate) {
                     return Test[x-y]*10;
                  }
                  a = a + 1;
                  do {
                     b = a * 5 + b;
                  } while (!(b == 300));
               }
            }
         }
      }
   }

   delete[] Test;
}

void MySub(int x)
{
   int y;
   float *Test;
   float *Number = new float [10+1];
   int *Other = new int [x+1];
   int z;

   ProgStatus = 10;
   y = x + 1;
   z = y+x;
   Other[x] = x+1;

   while (x < 10) {
      y = MyFunction(x, *Test);
      Test = &x;
      Number[z] = *Test + Other[5+x];
      x = x+1;
   }

   delete[] Other;
   delete[] Number;
}
//   ' This line is broken up using a _ (underscore)
//   This is a commment (even without ')
//   Everything after _ is a comment

void TestCertainOperators(int x, int y, int z, double& OtherVar, float *FinalArg)
{
   //  Note: comments after _ are regrouped into a different place

   int *MyArray = new int [10+1];
   Point MyPoint;
   Point *pp;
   int n;

   for (x=1; x<=10; x += 1) {
      n = y == z //  This works differently in PB than in C++
      MyArray[x] = x*2;
      if (x == 5) {
         y = x+5;
      } else {
         y = 23*2;
      }
      y = x == z;
      MyArray[5] = MyArray[n] == MyArray[n+1];
      if (x == y == z) {
         y = n == 2;
      } else {
         y = n == 3;
      }
      if (x == y && x != 10 || y == x && x < 25) {
         y = x || y == z;
      }
      if ((x == y & x != 10 | y == x & x < 25)) {
         y = x || y == z;
      }
      if ((x == y & x != 10) || y == x && x < 25) {
         y = x || y == z;
      }
      if (~(x == y | x == z)) {
         x = y + 10;
      }
      if (~(x == y | x == z)) {
         x = y + 10;
      }

      if (x != y) {
         MyPoint.x = y;
      } else {
         MyPoint.x = x;
      }

      pp = &p;
      MyPoint.x = MyPoint.y+1;
      n = MyPoint.x == MyPoint.y;
      *pp.x = *pp.y == *pp.x+1;
   }

   delete[] MyArray;
}

//  The section below is a test for variables declared implicitely with data type
//  based on Def[Type] declarations or on type specifiers.

float MyValue;
string Label;
Currency Price;
double ExtVal;
__int64 qNum;

int TestFunc(int& a, unsigned char& b, int& c, short& i, String& s, float& n)
{
   Print MyValue, Label, PriceB;

   Label = "Missing quote at the end of this line is added by Refactor.uc";
}

string Report(string& LastName, int x, double& NewPrice, float& n, short i, float& nValue, __int64& qValue)
{
   string FirstName;
   unsigned char Age;
   double Total;
   static int Index;

   Print LastName, x, NewPrice, n, i, nValue, qValue;
   Report = FirstName + LastName;
}

string Hello(string& txt)
{
   Print txt;
   return txt + " friend!";
}

unsigned char  Bye() {
   Print "Bye";
}

//  This section is a test for Subs or Functions that are called as a statement
//  without parentheses.  The converter adds them.

// #Include "Win32API.inc"
extern __declspec(dllimport) unsigned int ShellExecute(unsigned int hwnd, lpOperation As LPCSTR, lpFile As LPCSTR, lpParameters As LPCSTR, lpDirectory As LPCSTR, int nShowCmd);
extern __declspec(dllimport) int SetCursorPos(int x, int y);
extern __declspec(dllimport) void SetLastError(unsigned int dwErrCode);

void DoSomething(int Arg1, string& txt, double& Number, Optional unsigned int *xyz)
{
   SetCursorPos(10, Arg1 + 5);
   if (Arg1 == 15) {
      SetLastError(123);
   }
}

float main()
{
   double x;
   double pi;
   DoSomething(Len("Test")+5, "Hello " + "world!", Sin(x+1)*pi, &x-4) //  Comment

   DoSomething(10, "abc", 5, 1);
   DoSomething(1, "x", 5, 0)  //  Etc...

   if (x > 1) {
      DoSomething(1, "x", 5, 0) //  Parenthesis already here
   }

   MyFunc(5);

   ShellExecute(0, "Open", "ReadMe.Txt", $Nul, $Nul, SW_ShowNormal);

   //  File handling test
   //  Open "MyInput.Txt" For Input As #1
   _FileHandle(1) = CreateFile("MyInput.Txt", GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

   //  Open "MyOutput.Txt" For Output As #2
   _FileHandle(2) = CreateFile("MyOutput.Txt", GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

   //  Open "MyAppend.Txt" For Append As #3
   _FileHandle(3) = CreateFile("MyAppend.Txt", GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
   SetFilePointer(_FileHandle(3), 0, 0, FILE_END);

   //  Open "MyBin.Txt" For Binary As #tst
   _FileHandle(tst) = CreateFile("MyBin.Txt", GENERIC_READ Or GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

   //  Open "MyRandom.Txt" For Random As #r Len = 1
   _FileHandle(r) = CreateFile("MyRandom.Txt", GENERIC_READ Or GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

   //  Close #1
   CloseHandle(_FileHandle(1));
   _FileHandle(1) = 0;

   //  Close #2
   CloseHandle(_FileHandle(2));
   _FileHandle(2) = 0;

   //  Close #3
   CloseHandle(_FileHandle(3));
   _FileHandle(3) = 0;

   //  Close #tst
   CloseHandle(_FileHandle(tst));
   _FileHandle(tst) = 0;

   //  Close #r
   CloseHandle(_FileHandle(r));
   _FileHandle(r) = 0;
} int;

//  This section tests transforms found in strings.uc
string StringTest(string& MyString, string OtherString)
{
   string MyText;
   int i;
   wstring MyWideStr;
   string Txt;
   string x;
   string y;
   wstring z;

   i = (MyString.find("abc", (1)-1)+1);
   i = (MyString.find("xyz", (i+10)-1)+1)*2;
   i = (MyString.find_first_of("aeiou", (1)-1)+1);
   //    i = InStr(i+10, "This is a test")
   //    i = InStr("This is a test", ANY "aeiou")
   MyText = MyString.substr(0, 3) + OtherString.substr((5)-1, 10) + x.substr(x.length()-(i+1), i+1);
   if (MyText.substr((3)-1, 5) == y) {
      MyText.replace((20)-1, MyText.length(), "Test" + to_string(i*15));
   }
   x.replace((25)-1, stold(y) +1, y);
   MyString.replace((25)-1, 5, y.substr((stold(x) )-1, 7));
}

//  This tests exported subs/functions
extern "C" __declspec(dllexport) int __stdcall MyExport(int n) {
   StringTest("abc", "xyz");
}

extern "C" __declspec(dllexport) void __stdcall MyExportSub(int a, unsigned char b) {
   DoSomething(1, "xyz", 2, 3);
}

//  Math test
//  If x Mod 2 > Cint(Sqr(x^2 + y^2)) Then Incr q Else Decr q
double DoMath()
{
   if (x % 2 > lround(sqrt(pow(x, 2) + pow(y, 2)))) {
      q++;
   } else {
      q--;
   }
   n = sqrt(x) * atan(y) + 2 // * x^2 + Tan(x^3-1)^2
   pow(n == x, 2) + pow(y, 2);
   y = trunc(3.14159);
}
<commit_msg>Update SampleCode.cpp<commit_after>// This file (SampleCode.cpp) was converted from SampleCode.Bas
// with uCalc Transform 2.5 on 1/22/2014 11:18:31 PM using the Open Source
// PowerBASIC to C++ converter found at https://github.com/uCalc/powerbasic-to-cpp

#include <Windows.h>
#include <math.h>
#include <string>
using namespace std;

//  File name: SampleCode.Bas
//  To convert this file to C++ make sure you have uCalc Transform on your PC
//  and *.uc from github.com/uCalc/powerbasic-to-cpp/tree/master/convert
//  Do the following at the Command Prompt:
//
//  C:\> PBtoCPP.Bat SampleCode.Bas

const int MyEquate = 0x100;
const int Other = 0x200;

int ProgStatus;

#if defined Other
//  Something
#elif !defined abcd
//  Something else
#else
//  Etc
#endif

#define MyMacroNum 12345
#define MyMacro(a, b, c) (a + b * (c))

struct point {
   int x;
   int y;
};

struct MyBits {
   unsigned int Year : 7;
   unsigned int Month : 5;
   unsigned int DayOfMonth : 4;
   unsigned int DayOfWeek : 3;
   unsigned char Red : 1;
   unsigned char Blue : 1;
   unsigned char Green : 1;
   double Other;
};

int MyFunc(int x)
{
   return x * 2;
}

int MyFunction(int a, float& b)
{
   int x;
   int y;
   int *Test = new int [a+25+1];
   int yVar;
   int MyValue;
   //  Dim q As Long
   //  The commented line above is not translated

   MyFunc(a);
   x = MyFunc(b)+1;

   if (b > 5) {
      for (x=1; x<=10; x += 1) {
         for (yVar=10; yVar>=1; yVar += -1) {
            if (x > y) {
               return a+y;
            }
            while (Test[a+5] == yVar) {
               while (!(a+1 == 1234)) {
                  if (y < MyEquate) {
                     return Test[x-y]*10;
                  }
                  a = a + 1;
                  do {
                     b = a * 5 + b;
                  } while (!(b == 300));
               }
            }
         }
      }
   }

   delete[] Test;
}

void MySub(int x)
{
   int y;
   float *Test;
   float *Number = new float [10+1];
   int *Other = new int [x+1];
   int z;

   ProgStatus = 10;
   y = x + 1;
   z = y+x;
   Other[x] = x+1;

   while (x < 10) {
      y = MyFunction(x, *Test);
      Test = &x;
      Number[z] = *Test + Other[5+x];
      x = x+1;
   }

   delete[] Other;
   delete[] Number;
}
//   ' This line is broken up using a _ (underscore)
//   This is a commment (even without ')
//   Everything after _ is a comment

void TestCertainOperators(int x, int y, int z, double& OtherVar, float *FinalArg)
{
   //  Note: comments after _ are regrouped into a different place

   int *MyArray = new int [10+1];
   Point MyPoint;
   Point *pp;
   int n;

   for (x=1; x<=10; x += 1) {
      n = y == z //  This works differently in PB than in C++
      MyArray[x] = x*2;
      if (x == 5) {
         y = x+5;
      } else {
         y = 23*2;
      }
      y = x == z;
      MyArray[5] = MyArray[n] == MyArray[n+1];
      if (x == y == z) {
         y = n == 2;
      } else {
         y = n == 3;
      }
      if (x == y && x != 10 || y == x && x < 25) {
         y = x || y == z;
      }
      if ((x == y & x != 10 | y == x & x < 25)) {
         y = x || y == z;
      }
      if ((x == y & x != 10) || y == x && x < 25) {
         y = x || y == z;
      }
      if (~(x == y | x == z)) {
         x = y + 10;
      }
      if (~(x == y | x == z)) {
         x = y + 10;
      }

      if (x != y) {
         MyPoint.x = y;
      } else {
         MyPoint.x = x;
      }

      pp = &p;
      MyPoint.x = MyPoint.y+1;
      n = MyPoint.x == MyPoint.y;
      *pp.x = *pp.y == *pp.x+1;
   }

   delete[] MyArray;
}

//  The section below is a test for variables declared implicitely with data type
//  based on Def[Type] declarations or on type specifiers.

float MyValue;
string Label;
Currency Price;
double ExtVal;
__int64 qNum;

int TestFunc(int& a, unsigned char& b, int& c, short& i, String& s, float& n)
{
   Print MyValue, Label, PriceB;

   Label = "Missing quote at the end of this line is added by Refactor.uc";
}

string Report(string& LastName, int x, double& NewPrice, float& n, short i, float& nValue, __int64& qValue)
{
   string FirstName;
   unsigned char Age;
   double Total;
   static int Index;

   Print LastName, x, NewPrice, n, i, nValue, qValue;
   Report = FirstName + LastName;
}

string Hello(string& txt)
{
   Print txt;
   return txt + " friend!";
}

unsigned char  Bye() {
   Print "Bye";
}

//  This section is a test for Subs or Functions that are called as a statement
//  without parentheses.  The converter adds them.

// #Include "Win32API.inc"
extern __declspec(dllimport) unsigned int ShellExecute(unsigned int hwnd, lpOperation As LPCSTR, lpFile As LPCSTR, lpParameters As LPCSTR, lpDirectory As LPCSTR, int nShowCmd);
extern __declspec(dllimport) int SetCursorPos(int x, int y);
extern __declspec(dllimport) void SetLastError(unsigned int dwErrCode);

void DoSomething(int Arg1, string& txt, double& Number, Optional unsigned int *xyz)
{
   SetCursorPos(10, Arg1 + 5);
   if (Arg1 == 15) {
      SetLastError(123);
   }
}

float main()
{
   double x;
   double pi;
   DoSomething(Len("Test")+5, "Hello " + "world!", Sin(x+1)*pi, &x-4) //  Comment

   DoSomething(10, "abc", 5, 1);
   DoSomething(1, "x", 5, 0)  //  Etc...

   if (x > 1) {
      DoSomething(1, "x", 5, 0) //  Parenthesis already here
   }

   MyFunc(5);

   ShellExecute(0, "Open", "ReadMe.Txt", $Nul, $Nul, SW_ShowNormal);

   //  File handling test
   //  Open "MyInput.Txt" For Input As #1
   _FileHandle(1) = CreateFile("MyInput.Txt", GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

   //  Open "MyOutput.Txt" For Output As #2
   _FileHandle(2) = CreateFile("MyOutput.Txt", GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

   //  Open "MyAppend.Txt" For Append As #3
   _FileHandle(3) = CreateFile("MyAppend.Txt", GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
   SetFilePointer(_FileHandle(3), 0, 0, FILE_END);

   //  Open "MyBin.Txt" For Binary As #tst
   _FileHandle(tst) = CreateFile("MyBin.Txt", GENERIC_READ Or GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

   //  Open "MyRandom.Txt" For Random As #r Len = 1
   _FileHandle(r) = CreateFile("MyRandom.Txt", GENERIC_READ Or GENERIC_WRITE, 0, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

   i = GetFileSize(_FileHandle(tst), 0);
   i = SetFilePointer(_FileHandle(tst), 0, 0, FILE_CURRENT)+1;
   SetFilePointer(_FileHandle(tst), i+100-1, 0, FILE_BEGIN);

   //  Close #1
   CloseHandle(_FileHandle(1));
   _FileHandle(1) = 0;

   //  Close #2
   CloseHandle(_FileHandle(2));
   _FileHandle(2) = 0;

   //  Close #3
   CloseHandle(_FileHandle(3));
   _FileHandle(3) = 0;

   //  Close #tst
   CloseHandle(_FileHandle(tst));
   _FileHandle(tst) = 0;

   //  Close #r
   CloseHandle(_FileHandle(r));
   _FileHandle(r) = 0;
} int;

//  This section tests transforms found in strings.uc
string StringTest(string& MyString, string OtherString)
{
   string MyText;
   int i;
   wstring MyWideStr;
   string Txt;
   string x;
   string y;
   wstring z;

   i = (MyString.find("abc", (1)-1)+1);
   i = (MyString.find("xyz", (i+10)-1)+1)*2;
   i = (MyString.find_first_of("aeiou", (1)-1)+1);
   //    i = InStr(i+10, "This is a test")
   //    i = InStr("This is a test", ANY "aeiou")
   MyText = MyString.substr(0, 3) + OtherString.substr((5)-1, 10) + x.substr(x.length()-(i+1), i+1);
   if (MyText.substr((3)-1, 5) == y) {
      MyText.replace((20)-1, MyText.length(), "Test" + to_string(i*15));
   }
   x.replace((25)-1, stold(y) +1, y);
   MyString.replace((25)-1, 5, y.substr((stold(x) )-1, 7));
}

//  This tests exported subs/functions
extern "C" __declspec(dllexport) int __stdcall MyExport(int n) {
   StringTest("abc", "xyz");
}

extern "C" __declspec(dllexport) void __stdcall MyExportSub(int a, unsigned char b) {
   DoSomething(1, "xyz", 2, 3);
}

//  Math test
//  If x Mod 2 > Cint(Sqr(x^2 + y^2)) Then Incr q Else Decr q
double DoMath()
{
   if (x % 2 > lround(sqrt(pow(x, 2) + pow(y, 2)))) {
      q++;
   } else {
      q--;
   }
   n = sqrt(x) * atan(y) + 2 // * x^2 + Tan(x^3-1)^2
   pow(n == x, 2) + pow(y, 2);
   y = trunc(3.14159);
}
<|endoftext|>


<commit_before><commit_msg>Delete mainScanner.cpp<commit_after><|endoftext|>


<commit_before>/**
 * @file kmeans_main.cpp
 * @author Ryan Curtin
 *
 * Executable for running K-Means.
 */
#include <mlpack/core.hpp>

#include "kmeans.hpp"
#include "allow_empty_clusters.hpp"
#include "refined_start.hpp"

using namespace mlpack;
using namespace mlpack::kmeans;
using namespace std;

// Define parameters for the executable.
PROGRAM_INFO("K-Means Clustering", "This program performs K-Means clustering "
    "on the given dataset, storing the learned cluster assignments either as "
    "a column of labels in the file containing the input dataset or in a "
    "separate file.  Empty clusters are not allowed by default; when a cluster "
    "becomes empty, the point furthest from the centroid of the cluster with "
    "maximum variance is taken to fill that cluster."
    "\n\n"
    "Optionally, the Bradley and Fayyad approach (\"Refining initial points for"
    " k-means clustering\", 1998) can be used to select initial points by "
    "specifying the --refined_start (-r) option.  This approach works by taking"
    " random samples of the dataset; to specify the number of samples, the "
    "--samples parameter is used, and to specify the percentage of the dataset "
    "to be used in each sample, the --percentage parameter is used (it should "
    "be a value between 0.0 and 1.0)."
    "\n\n"
    "If you want to specify your own initial cluster assignments or initial "
    "cluster centroids, this functionality is available in the C++ interface. "
    "Alternately, file a bug (well, a feature request) on the mlpack bug "
    "tracker.");

// Required options.
PARAM_STRING_REQ("inputFile", "Input dataset to perform clustering on.", "i");
PARAM_INT_REQ("clusters", "Number of clusters to find.", "c");

// Output options.
PARAM_FLAG("in_place", "If specified, a column of the learned cluster "
    "assignments will be added to the input dataset file.  In this case, "
    "--outputFile is not necessary.", "p");
PARAM_STRING("output_file", "File to write output labels or labeled data to.",
    "o", "output.csv");
PARAM_STRING("centroid_file", "If specified, the centroids of each cluster will"
    " be written to the given file.", "C", "");

// k-means configuration options.
PARAM_FLAG("allow_empty_clusters", "Allow empty clusters to be created.", "e");
PARAM_FLAG("labels_only", "Only output labels into output file.", "l");
PARAM_DOUBLE("overclustering", "Finds (overclustering * clusters) clusters, "
    "then merges them together until only the desired number of clusters are "
    "left.", "O", 1.0);
PARAM_INT("max_iterations", "Maximum number of iterations before K-Means "
    "terminates.", "m", 1000);
PARAM_INT("seed", "Random seed.  If 0, 'std::time(NULL)' is used.", "s", 0);

// This is known to not work (#251).
//PARAM_FLAG("fast_kmeans", "Use the experimental fast k-means algorithm by "
//    "Pelleg and Moore.", "f");

// Parameters for "refined start" k-means.
PARAM_FLAG("refined_start", "Use the refined initial point strategy by Bradley "
    "and Fayyad to choose initial points.", "r");
PARAM_INT("samplings", "Number of samplings to perform for refined start (use "
    "when --refined_start is specified).", "S", 100);
PARAM_DOUBLE("percentage", "Percentage of dataset to use for each refined start"
    " sampling (use when --refined_start is specified).", "p", 0.02);

int main(int argc, char** argv)
{
  CLI::ParseCommandLine(argc, argv);

  // Initialize random seed.
  if (CLI::GetParam<int>("seed") != 0)
    math::RandomSeed((size_t) CLI::GetParam<int>("seed"));
  else
    math::RandomSeed((size_t) std::time(NULL));

  // Now do validation of options.
  string inputFile = CLI::GetParam<string>("inputFile");
  int clusters = CLI::GetParam<int>("clusters");
  if (clusters < 1)
  {
    Log::Fatal << "Invalid number of clusters requested (" << clusters << ")! "
        << "Must be greater than or equal to 1." << std::endl;
  }

  int maxIterations = CLI::GetParam<int>("max_iterations");
  if (maxIterations < 0)
  {
    Log::Fatal << "Invalid value for maximum iterations (" << maxIterations <<
        ")! Must be greater than or equal to 0." << std::endl;
  }

  double overclustering = CLI::GetParam<double>("overclustering");
  if (overclustering < 1)
  {
    Log::Fatal << "Invalid value for overclustering (" << overclustering <<
        ")! Must be greater than or equal to 1." << std::endl;
  }

  // Make sure we have an output file if we're not doing the work in-place.
  if (!CLI::HasParam("in_place") && !CLI::HasParam("output_file"))
  {
    Log::Fatal << "--outputFile not specified (and --in_place not set)."
        << std::endl;
  }

  // Load our dataset.
  arma::mat dataset;
  data::Load(inputFile.c_str(), dataset, true); // Fatal upon failure.

  // Now create the KMeans object.  Because we could be using different types,
  // it gets a little weird...
  arma::Col<size_t> assignments;
  arma::mat centroids;

  if (CLI::HasParam("allow_empty_clusters"))
  {
    if (CLI::HasParam("refined_start"))
    {
      const int samplings = CLI::GetParam<int>("samplings");
      const double percentage = CLI::GetParam<int>("percentage");

      if (samplings < 0)
        Log::Fatal << "Number of samplings (" << samplings << ") must be "
            << "greater than 0!" << std::endl;
      if (percentage <= 0.0 || percentage > 1.0)
        Log::Fatal << "Percentage for sampling (" << percentage << ") must be "
            << "greater than 0.0 and less than or equal to 1.0!" << std::endl;

      KMeans<metric::SquaredEuclideanDistance, RefinedStart, AllowEmptyClusters>
          k(maxIterations, overclustering, metric::SquaredEuclideanDistance(),
          RefinedStart(samplings, percentage));

      Timer::Start("clustering");
      if (CLI::HasParam("fast_kmeans"))
        k.FastCluster(dataset, clusters, assignments);
      else
        k.Cluster(dataset, clusters, assignments, centroids);
      Timer::Stop("clustering");
    }
    else
    {
      KMeans<metric::SquaredEuclideanDistance, RandomPartition,
          AllowEmptyClusters> k(maxIterations, overclustering);

      Timer::Start("clustering");
      if (CLI::HasParam("fast_kmeans"))
        k.FastCluster(dataset, clusters, assignments);
      else
        k.Cluster(dataset, clusters, assignments, centroids);
      Timer::Stop("clustering");
    }
  }
  else
  {
    if (CLI::HasParam("refined_start"))
    {
      const int samplings = CLI::GetParam<int>("samplings");
      const double percentage = CLI::GetParam<int>("percentage");

      if (samplings < 0)
        Log::Fatal << "Number of samplings (" << samplings << ") must be "
            << "greater than 0!" << std::endl;
      if (percentage <= 0.0 || percentage > 1.0)
        Log::Fatal << "Percentage for sampling (" << percentage << ") must be "
            << "greater than 0.0 and less than or equal to 1.0!" << std::endl;

      KMeans<metric::SquaredEuclideanDistance, RefinedStart, AllowEmptyClusters>
          k(maxIterations, overclustering, metric::SquaredEuclideanDistance(),
          RefinedStart(samplings, percentage));

      Timer::Start("clustering");
      if (CLI::HasParam("fast_kmeans"))
        k.FastCluster(dataset, clusters, assignments);
      else
        k.Cluster(dataset, clusters, assignments, centroids);
      Timer::Stop("clustering");
    }
    else
    {
      KMeans<> k(maxIterations, overclustering);

      Timer::Start("clustering");
      if (CLI::HasParam("fast_kmeans"))
        k.FastCluster(dataset, clusters, assignments);
      else
        k.Cluster(dataset, clusters, assignments, centroids);
      Timer::Stop("clustering");
    }
  }

  // Now figure out what to do with our results.
  if (CLI::HasParam("in_place"))
  {
    // Add the column of assignments to the dataset; but we have to convert them
    // to type double first.
    arma::vec converted(assignments.n_elem);
    for (size_t i = 0; i < assignments.n_elem; i++)
      converted(i) = (double) assignments(i);

    dataset.insert_rows(dataset.n_rows, trans(converted));

    // Save the dataset.
    data::Save(inputFile, dataset);
  }
  else
  {
    if (CLI::HasParam("labels_only"))
    {
      // Save only the labels.
      string outputFile = CLI::GetParam<string>("output_file");
      arma::Mat<size_t> output = trans(assignments);
      data::Save(outputFile, output);
    }
    else
    {
      // Convert the assignments to doubles.
      arma::vec converted(assignments.n_elem);
      for (size_t i = 0; i < assignments.n_elem; i++)
        converted(i) = (double) assignments(i);

      dataset.insert_rows(dataset.n_rows, trans(converted));

      // Now save, in the different file.
      string outputFile = CLI::GetParam<string>("output_file");
      data::Save(outputFile, dataset);
    }
  }

  // Should we write the centroids to a file?
  if (CLI::HasParam("centroid_file"))
    data::Save(CLI::GetParam<std::string>("centroid_file"), centroids);
}

<commit_msg>Comment out --fast_kmeans option so it does not work at all, for now.<commit_after>/**
 * @file kmeans_main.cpp
 * @author Ryan Curtin
 *
 * Executable for running K-Means.
 */
#include <mlpack/core.hpp>

#include "kmeans.hpp"
#include "allow_empty_clusters.hpp"
#include "refined_start.hpp"

using namespace mlpack;
using namespace mlpack::kmeans;
using namespace std;

// Define parameters for the executable.
PROGRAM_INFO("K-Means Clustering", "This program performs K-Means clustering "
    "on the given dataset, storing the learned cluster assignments either as "
    "a column of labels in the file containing the input dataset or in a "
    "separate file.  Empty clusters are not allowed by default; when a cluster "
    "becomes empty, the point furthest from the centroid of the cluster with "
    "maximum variance is taken to fill that cluster."
    "\n\n"
    "Optionally, the Bradley and Fayyad approach (\"Refining initial points for"
    " k-means clustering\", 1998) can be used to select initial points by "
    "specifying the --refined_start (-r) option.  This approach works by taking"
    " random samples of the dataset; to specify the number of samples, the "
    "--samples parameter is used, and to specify the percentage of the dataset "
    "to be used in each sample, the --percentage parameter is used (it should "
    "be a value between 0.0 and 1.0)."
    "\n\n"
    "If you want to specify your own initial cluster assignments or initial "
    "cluster centroids, this functionality is available in the C++ interface. "
    "Alternately, file a bug (well, a feature request) on the mlpack bug "
    "tracker.");

// Required options.
PARAM_STRING_REQ("inputFile", "Input dataset to perform clustering on.", "i");
PARAM_INT_REQ("clusters", "Number of clusters to find.", "c");

// Output options.
PARAM_FLAG("in_place", "If specified, a column of the learned cluster "
    "assignments will be added to the input dataset file.  In this case, "
    "--outputFile is not necessary.", "p");
PARAM_STRING("output_file", "File to write output labels or labeled data to.",
    "o", "output.csv");
PARAM_STRING("centroid_file", "If specified, the centroids of each cluster will"
    " be written to the given file.", "C", "");

// k-means configuration options.
PARAM_FLAG("allow_empty_clusters", "Allow empty clusters to be created.", "e");
PARAM_FLAG("labels_only", "Only output labels into output file.", "l");
PARAM_DOUBLE("overclustering", "Finds (overclustering * clusters) clusters, "
    "then merges them together until only the desired number of clusters are "
    "left.", "O", 1.0);
PARAM_INT("max_iterations", "Maximum number of iterations before K-Means "
    "terminates.", "m", 1000);
PARAM_INT("seed", "Random seed.  If 0, 'std::time(NULL)' is used.", "s", 0);

// This is known to not work (#251).
//PARAM_FLAG("fast_kmeans", "Use the experimental fast k-means algorithm by "
//    "Pelleg and Moore.", "f");

// Parameters for "refined start" k-means.
PARAM_FLAG("refined_start", "Use the refined initial point strategy by Bradley "
    "and Fayyad to choose initial points.", "r");
PARAM_INT("samplings", "Number of samplings to perform for refined start (use "
    "when --refined_start is specified).", "S", 100);
PARAM_DOUBLE("percentage", "Percentage of dataset to use for each refined start"
    " sampling (use when --refined_start is specified).", "p", 0.02);

int main(int argc, char** argv)
{
  CLI::ParseCommandLine(argc, argv);

  // Initialize random seed.
  if (CLI::GetParam<int>("seed") != 0)
    math::RandomSeed((size_t) CLI::GetParam<int>("seed"));
  else
    math::RandomSeed((size_t) std::time(NULL));

  // Now do validation of options.
  string inputFile = CLI::GetParam<string>("inputFile");
  int clusters = CLI::GetParam<int>("clusters");
  if (clusters < 1)
  {
    Log::Fatal << "Invalid number of clusters requested (" << clusters << ")! "
        << "Must be greater than or equal to 1." << std::endl;
  }

  int maxIterations = CLI::GetParam<int>("max_iterations");
  if (maxIterations < 0)
  {
    Log::Fatal << "Invalid value for maximum iterations (" << maxIterations <<
        ")! Must be greater than or equal to 0." << std::endl;
  }

  double overclustering = CLI::GetParam<double>("overclustering");
  if (overclustering < 1)
  {
    Log::Fatal << "Invalid value for overclustering (" << overclustering <<
        ")! Must be greater than or equal to 1." << std::endl;
  }

  // Make sure we have an output file if we're not doing the work in-place.
  if (!CLI::HasParam("in_place") && !CLI::HasParam("output_file"))
  {
    Log::Fatal << "--outputFile not specified (and --in_place not set)."
        << std::endl;
  }

  // Load our dataset.
  arma::mat dataset;
  data::Load(inputFile.c_str(), dataset, true); // Fatal upon failure.

  // Now create the KMeans object.  Because we could be using different types,
  // it gets a little weird...
  arma::Col<size_t> assignments;
  arma::mat centroids;

  if (CLI::HasParam("allow_empty_clusters"))
  {
    if (CLI::HasParam("refined_start"))
    {
      const int samplings = CLI::GetParam<int>("samplings");
      const double percentage = CLI::GetParam<int>("percentage");

      if (samplings < 0)
        Log::Fatal << "Number of samplings (" << samplings << ") must be "
            << "greater than 0!" << std::endl;
      if (percentage <= 0.0 || percentage > 1.0)
        Log::Fatal << "Percentage for sampling (" << percentage << ") must be "
            << "greater than 0.0 and less than or equal to 1.0!" << std::endl;

      KMeans<metric::SquaredEuclideanDistance, RefinedStart, AllowEmptyClusters>
          k(maxIterations, overclustering, metric::SquaredEuclideanDistance(),
          RefinedStart(samplings, percentage));

      Timer::Start("clustering");
//      if (CLI::HasParam("fast_kmeans"))
//        k.FastCluster(dataset, clusters, assignments);
//      else
        k.Cluster(dataset, clusters, assignments, centroids);
      Timer::Stop("clustering");
    }
    else
    {
      KMeans<metric::SquaredEuclideanDistance, RandomPartition,
          AllowEmptyClusters> k(maxIterations, overclustering);

      Timer::Start("clustering");
//      if (CLI::HasParam("fast_kmeans"))
//        k.FastCluster(dataset, clusters, assignments);
//      else
        k.Cluster(dataset, clusters, assignments, centroids);
      Timer::Stop("clustering");
    }
  }
  else
  {
    if (CLI::HasParam("refined_start"))
    {
      const int samplings = CLI::GetParam<int>("samplings");
      const double percentage = CLI::GetParam<int>("percentage");

      if (samplings < 0)
        Log::Fatal << "Number of samplings (" << samplings << ") must be "
            << "greater than 0!" << std::endl;
      if (percentage <= 0.0 || percentage > 1.0)
        Log::Fatal << "Percentage for sampling (" << percentage << ") must be "
            << "greater than 0.0 and less than or equal to 1.0!" << std::endl;

      KMeans<metric::SquaredEuclideanDistance, RefinedStart, AllowEmptyClusters>
          k(maxIterations, overclustering, metric::SquaredEuclideanDistance(),
          RefinedStart(samplings, percentage));

      Timer::Start("clustering");
//      if (CLI::HasParam("fast_kmeans"))
//        k.FastCluster(dataset, clusters, assignments);
//      else
        k.Cluster(dataset, clusters, assignments, centroids);
      Timer::Stop("clustering");
    }
    else
    {
      KMeans<> k(maxIterations, overclustering);

      Timer::Start("clustering");
//      if (CLI::HasParam("fast_kmeans"))
//        k.FastCluster(dataset, clusters, assignments);
//      else
        k.Cluster(dataset, clusters, assignments, centroids);
      Timer::Stop("clustering");
    }
  }

  // Now figure out what to do with our results.
  if (CLI::HasParam("in_place"))
  {
    // Add the column of assignments to the dataset; but we have to convert them
    // to type double first.
    arma::vec converted(assignments.n_elem);
    for (size_t i = 0; i < assignments.n_elem; i++)
      converted(i) = (double) assignments(i);

    dataset.insert_rows(dataset.n_rows, trans(converted));

    // Save the dataset.
    data::Save(inputFile, dataset);
  }
  else
  {
    if (CLI::HasParam("labels_only"))
    {
      // Save only the labels.
      string outputFile = CLI::GetParam<string>("output_file");
      arma::Mat<size_t> output = trans(assignments);
      data::Save(outputFile, output);
    }
    else
    {
      // Convert the assignments to doubles.
      arma::vec converted(assignments.n_elem);
      for (size_t i = 0; i < assignments.n_elem; i++)
        converted(i) = (double) assignments(i);

      dataset.insert_rows(dataset.n_rows, trans(converted));

      // Now save, in the different file.
      string outputFile = CLI::GetParam<string>("output_file");
      data::Save(outputFile, dataset);
    }
  }

  // Should we write the centroids to a file?
  if (CLI::HasParam("centroid_file"))
    data::Save(CLI::GetParam<std::string>("centroid_file"), centroids);
}

<|endoftext|>