<commit_before>/*
Copyright 2011, Jernej Kovacic

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

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

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

/**
 * @file
 * @author Jernej Kovacic
 *
 * Implementation  of the class NumericUtil, a collection of some useful
 * numerical utilities. This is a templated class and must not be compiled.
 * Instead it must be included after the class declaration in the .h file
 */

// Deliberately there is no #include "NumericUtil.hpp"
#include "rational/Rational.hpp"
#include "matrix/SqMatrixGeneric.hpp"
#include "polynomial/PolynomialGeneric.hpp"

#include <cstddef>
#include <complex>
#include <limits>

// Note that the optimal EPS depends on application's requirements

// For float, double and long double, a suggested value for EPS can be
// obtained by std::numeric_limits<type>::epsilon().
#define _MATH_NUMERICUTIL_SPECIALIZED_EPS(FDL) \
template<> \
FDL math::NumericUtil<FDL>::EPS = std::numeric_limits<FDL>::epsilon();
// end of #define

// definition of EPS for float:
_MATH_NUMERICUTIL_SPECIALIZED_EPS(float)

// double is a more accurate type:
_MATH_NUMERICUTIL_SPECIALIZED_EPS(double)

// ... and long double is even more accurate:
_MATH_NUMERICUTIL_SPECIALIZED_EPS(long double)

// #definition of _MATH_NUMERICUTIL_SPECIALIZED_EPS not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_EPS

/*
 * For int and other types, EPS doesn't make sense, so set it to 0
 */
template<class T>
T math::NumericUtil<T>::EPS = static_cast<T>(0);

/**
 * A constant value with the T's representation of zero (0)
 */
template<class T>
const T math::NumericUtil<T>::ZERO ( static_cast<T>(0) );

/**
 * A constant value with the T's representation of one (1)
 */
template<class T>
const T math::NumericUtil<T>::ONE ( static_cast<T>(1) );

/**
 * Does the given value equal (or is close enough to) zero?
 * Implementation depends on the type T.
 * For floating point types (float, double, long double), it checks
 * whether its absolute value is less than a hardcoded constant 'eps'.
 *
 * @param value
 *
 * @return true or false
 */
template<class T>
bool math::NumericUtil<T>::isZero(const T& value)
{
    /*
     * The implementation for integers et al. where the == operator
     * does make sense and no comparison to EPS is necessary.
     */
    bool retVal = ( ZERO==value ? true : false );

    return retVal;
}

/*
 * Float, double and long double require specialized implementations of isZero().
 * In case of these three types, the equality operator (==) is useless.
 * In numerical mathematics, two numbers are considered "equal", when
 * absolute value of their difference does not exceed a reasonably set EPS.
 * All specializations are very similar and only differ in types of an input value.
 * For easier maintainability, the specialization will be implemented
 * only once using a parameterized #define
 */

#define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(FDL) \
template<> \
bool math::NumericUtil<FDL>::isZero(const FDL& value) \
{ \
    bool retVal = false; \
    retVal = ( value>-EPS && value<EPS ? true : false ); \
    return retVal; \
}
// end of #define

// derive specialization for float:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(float)

// ... for double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(double)

// ... and long double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(long double)

// #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO

/*
 * Specialization for complex.
 * As complex is a templated class, again it must be implemented for each supported subtemplated
 * type. To facilitate this, a parameterized macro is introduced.
 * Note: norm() calculates a sum of both parts' squares. It is a bit more efficient to compare
 * it with EPS^2 than calculating its square root (the actual definition of complex abs. value).
 */
#define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(FDL) \
template<> \
bool math::NumericUtil<std::complex<FDL> >::isZero(const std::complex<FDL>& value) \
{ \
    bool retVal = false; \
    const FDL eps = math::NumericUtil<FDL>::getEPS(); \
    retVal = ( std::norm(value)<=eps*eps ? true : false ); \
    return retVal; \
}
// end of #define

// derive specialization for float:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(float)

// ... for double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(double)

// ... and long double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(long double)

// #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX
/*
 * Implementation for Rational
 */
template<>
bool math::NumericUtil<math::Rational>::isZero(const math::Rational& value)
{
    // Rational already contains its own isZero()...
    return value.isZero();
}

/**
 * @return value of 'eps' for the desired type
 */
template<class T>
T math::NumericUtil<T>::getEPS()
{
    return EPS;
}

/**
 * Sets the new value of 'eps' for the desired type if the default one does
 * not meet application's requirements.
 *
 * @note There is no check of input so make sure a sensible value
 *       (typically a very small positive number) is entered.
 *
 * @param eps - new value of EPS
 */
template<class T>
void math::NumericUtil<T>::setEPS(const T& eps)
{
    EPS = eps;
}

/*
 * In C++, it is not possible to specialize a function of a templated class
 * if the specialization is also a generic type (e.g. T -> math::SqMatrixGeneric<T>).
 * However it is possible if a single function is templated.
 * For more details, see the discussion at:
 * http://www.cplusplus.com/forum/general/68298/
 *
 * At the moment, getUnit() is only used by power(). Until it is changed,
 * getUnit() will be defined in this file as a templated standalone function.
 * Additionally, implementations of the function are "hidden" in the namespace
 * math::getunit which is not supposed to be known to other members of math::
 */
namespace math
{
    namespace getunit
    {
        /*
         * @param t - an arbitrary instance of T, ignored by the generic implementation,
         *            at specializations it might be useful to determine unit's dimensions etc.
         *
         * @return an instance of T acting as a multiplication unit
         */
        template<class T>
        T getUnit(const T& t)
        {
            (void) t;
            return T(math::NumericUtil<T>::ONE);
        }

        /*
         * Specialization for generic class math::SqMatrixGeneric<T>
         *
         * @param t - an arbitrary instance of a square matrix to determine
         *            dimensions of the returned unit matrix
         *
         * @return a unit n x n square matrix where n is a dimension of 't'
         */
        template<class T>
        math::SqMatrixGeneric<T> getUnit(const math::SqMatrixGeneric<T>& t)
        {
            const size_t N = t.nrRows();
            math::SqMatrixGeneric<T> retVal(N);
            retVal.setUnit();
            return retVal;
        }

        /*
         * Specialization for generic class math::PolynomialGeneric<T>
         *
         * @param t - ignored
         *
         * @return a unit polynomial p(x) = (T)1
         */
        template<class T>
        math::PolynomialGeneric<T> getUnit(const math::PolynomialGeneric<T>& t)
        {
            (void) t;
            return math::PolynomialGeneric<T>(math::NumericUtil<T>::ONE);
        }

    } // namespace units
} // namespace math

/**
 * Efficient calculation of positive integer power.
 * Complexity of the algorithm is O(log2 n).
 *
 * @note T must have implemented operator*=
 *
 * @param base - base of the exponentiation
 * @param n - exponent (a positive integer number)
 *
 * @return base^n
 */
template<class T>
T math::NumericUtil<T>::power(const T& base, size_t n)
{
    /*
     * "Exponentiation by squaring" algorithm will be applied.
     *
     * Exponentiation can be expanded into:
     *        n    n%2       n/2
     *       a  = a   * (a^2)
     *
     * where / and % are integer division and remainder operators.
     *
     * The expression above can be further recursively derived to:
     *  n    n%2    (n/2)%2     (n/2)/2
     * a  = a   (a^2)       (a^4)       =
     *
     *       n%2    (n/2)%2    (n/4)%2    ((n/2)/2)/2
     *    = a   (a^2)      (a^4)      (a^8)           = ....
     *
     * It is simple to develop an iterative algorithm where factor
     * is iteratively increased by squaring itself and coefficients
     * ai (i=0..n) are iteratively calculated by the remainder of
     * division by 2
     */

    // Note: it is safe to use bitwise operators for arithmetic operations
    // on unsigned int values as they do not depend on endianess:
    // http://stackoverflow.com/questions/7184789/does-bit-shift-depends-on-endianness

    T retVal = math::getunit::getUnit(base);
    T factor = base;

    // Obtain coefficients ai from the exponent's binary form.
    // Note: "i>>=1" is a bitwise equivalent bitwise equivalent of "i/=2"
    for ( size_t i=n; i>0; i>>=1 )
    {
        // Check the coefficient ai (no need to multiply retVal by 1 if ai is 0)
        // Note: "i&1" is a bitwise equivalent of "i%2"
        if ( 0!=(i & static_cast<size_t>(1) ) )
        {
            retVal *= factor;
        }

        factor *= factor;
    }

    return retVal;
}
<commit_msg>simplified some methods<commit_after>/*
Copyright 2011, Jernej Kovacic

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

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

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

/**
 * @file
 * @author Jernej Kovacic
 *
 * Implementation  of the class NumericUtil, a collection of some useful
 * numerical utilities. This is a templated class and must not be compiled.
 * Instead it must be included after the class declaration in the .h file
 */

// Deliberately there is no #include "NumericUtil.hpp"
#include "rational/Rational.hpp"
#include "matrix/SqMatrixGeneric.hpp"
#include "polynomial/PolynomialGeneric.hpp"

#include <cstddef>
#include <complex>
#include <limits>

// Note that the optimal EPS depends on application's requirements

// For float, double and long double, a suggested value for EPS can be
// obtained by std::numeric_limits<type>::epsilon().
#define _MATH_NUMERICUTIL_SPECIALIZED_EPS(FDL) \
template<> \
FDL math::NumericUtil<FDL>::EPS = std::numeric_limits<FDL>::epsilon();
// end of #define

// definition of EPS for float:
_MATH_NUMERICUTIL_SPECIALIZED_EPS(float)

// double is a more accurate type:
_MATH_NUMERICUTIL_SPECIALIZED_EPS(double)

// ... and long double is even more accurate:
_MATH_NUMERICUTIL_SPECIALIZED_EPS(long double)

// #definition of _MATH_NUMERICUTIL_SPECIALIZED_EPS not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_EPS

/*
 * For int and other types, EPS doesn't make sense, so set it to 0
 */
template<class T>
T math::NumericUtil<T>::EPS = static_cast<T>(0);

/**
 * A constant value with the T's representation of zero (0)
 */
template<class T>
const T math::NumericUtil<T>::ZERO ( static_cast<T>(0) );

/**
 * A constant value with the T's representation of one (1)
 */
template<class T>
const T math::NumericUtil<T>::ONE ( static_cast<T>(1) );

/**
 * Does the given value equal (or is close enough to) zero?
 * Implementation depends on the type T.
 * For floating point types (float, double, long double), it checks
 * whether its absolute value is less than a hardcoded constant 'eps'.
 *
 * @param value
 *
 * @return true or false
 */
template<class T>
bool math::NumericUtil<T>::isZero(const T& value)
{
    /*
     * The implementation for integers et al. where the == operator
     * does make sense and no comparison to EPS is necessary.
     */

    return ( ZERO==value ? true : false );
}

/*
 * Float, double and long double require specialized implementations of isZero().
 * In case of these three types, the equality operator (==) is useless.
 * In numerical mathematics, two numbers are considered "equal", when
 * absolute value of their difference does not exceed a reasonably set EPS.
 * All specializations are very similar and only differ in types of an input value.
 * For easier maintainability, the specialization will be implemented
 * only once using a parameterized #define
 */

#define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(FDL) \
template<> \
bool math::NumericUtil<FDL>::isZero(const FDL& value) \
{ \
    return ( value>-EPS && value<EPS ? true : false ); \
}
// end of #define

// derive specialization for float:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(float)

// ... for double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(double)

// ... and long double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO(long double)

// #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO

/*
 * Specialization for complex.
 * As complex is a templated class, again it must be implemented for each supported subtemplated
 * type. To facilitate this, a parameterized macro is introduced.
 * Note: norm() calculates a sum of both parts' squares. It is a bit more efficient to compare
 * it with EPS^2 than calculating its square root (the actual definition of complex abs. value).
 */
#define _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(FDL) \
template<> \
bool math::NumericUtil<std::complex<FDL> >::isZero(const std::complex<FDL>& value) \
{ \
    const FDL eps = math::NumericUtil<FDL>::getEPS(); \
    return ( std::norm(value)<=eps*eps ? true : false ); \
}
// end of #define

// derive specialization for float:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(float)

// ... for double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(double)

// ... and long double:
_MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX(long double)

// #definition of _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX not needed anymore, #undef it:
#undef _MATH_NUMERICUTIL_SPECIALIZED_IS_ZERO_COMPLEX
/*
 * Implementation for Rational
 */
template<>
bool math::NumericUtil<math::Rational>::isZero(const math::Rational& value)
{
    // Rational already contains its own isZero()...
    return value.isZero();
}

/**
 * @return value of 'eps' for the desired type
 */
template<class T>
T math::NumericUtil<T>::getEPS()
{
    return EPS;
}

/**
 * Sets the new value of 'eps' for the desired type if the default one does
 * not meet application's requirements.
 *
 * @note There is no check of input so make sure a sensible value
 *       (typically a very small positive number) is entered.
 *
 * @param eps - new value of EPS
 */
template<class T>
void math::NumericUtil<T>::setEPS(const T& eps)
{
    EPS = eps;
}

/*
 * In C++, it is not possible to specialize a function of a templated class
 * if the specialization is also a generic type (e.g. T -> math::SqMatrixGeneric<T>).
 * However it is possible if a single function is templated.
 * For more details, see the discussion at:
 * http://www.cplusplus.com/forum/general/68298/
 *
 * At the moment, getUnit() is only used by power(). Until it is changed,
 * getUnit() will be defined in this file as a templated standalone function.
 * Additionally, implementations of the function are "hidden" in the namespace
 * math::getunit which is not supposed to be known to other members of math::
 */
namespace math
{
    namespace getunit
    {
        /*
         * @param t - an arbitrary instance of T, ignored by the generic implementation,
         *            at specializations it might be useful to determine unit's dimensions etc.
         *
         * @return an instance of T acting as a multiplication unit
         */
        template<class T>
        T getUnit(const T& t)
        {
            (void) t;
            return T(math::NumericUtil<T>::ONE);
        }

        /*
         * Specialization for generic class math::SqMatrixGeneric<T>
         *
         * @param t - an arbitrary instance of a square matrix to determine
         *            dimensions of the returned unit matrix
         *
         * @return a unit n x n square matrix where n is a dimension of 't'
         */
        template<class T>
        math::SqMatrixGeneric<T> getUnit(const math::SqMatrixGeneric<T>& t)
        {
            const size_t N = t.nrRows();
            math::SqMatrixGeneric<T> retVal(N);
            retVal.setUnit();
            return retVal;
        }

        /*
         * Specialization for generic class math::PolynomialGeneric<T>
         *
         * @param t - ignored
         *
         * @return a unit polynomial p(x) = (T)1
         */
        template<class T>
        math::PolynomialGeneric<T> getUnit(const math::PolynomialGeneric<T>& t)
        {
            (void) t;
            return math::PolynomialGeneric<T>(math::NumericUtil<T>::ONE);
        }

    } // namespace units
} // namespace math

/**
 * Efficient calculation of positive integer power.
 * Complexity of the algorithm is O(log2 n).
 *
 * @note T must have implemented operator*=
 *
 * @param base - base of the exponentiation
 * @param n - exponent (a positive integer number)
 *
 * @return base^n
 */
template<class T>
T math::NumericUtil<T>::power(const T& base, size_t n)
{
    /*
     * "Exponentiation by squaring" algorithm will be applied.
     *
     * Exponentiation can be expanded into:
     *        n    n%2       n/2
     *       a  = a   * (a^2)
     *
     * where / and % are integer division and remainder operators.
     *
     * The expression above can be further recursively derived to:
     *  n    n%2    (n/2)%2     (n/2)/2
     * a  = a   (a^2)       (a^4)       =
     *
     *       n%2    (n/2)%2    (n/4)%2    ((n/2)/2)/2
     *    = a   (a^2)      (a^4)      (a^8)           = ....
     *
     * It is simple to develop an iterative algorithm where factor
     * is iteratively increased by squaring itself and coefficients
     * ai (i=0..n) are iteratively calculated by the remainder of
     * division by 2
     */

    // Note: it is safe to use bitwise operators for arithmetic operations
    // on unsigned int values as they do not depend on endianess:
    // http://stackoverflow.com/questions/7184789/does-bit-shift-depends-on-endianness

    T retVal = math::getunit::getUnit(base);
    T factor = base;

    // Obtain coefficients ai from the exponent's binary form.
    // Note: "i>>=1" is a bitwise equivalent bitwise equivalent of "i/=2"
    for ( size_t i=n; i>0; i>>=1 )
    {
        // Check the coefficient ai (no need to multiply retVal by 1 if ai is 0)
        // Note: "i&1" is a bitwise equivalent of "i%2"
        if ( 0!=(i & static_cast<size_t>(1) ) )
        {
            retVal *= factor;
        }

        factor *= factor;
    }

    return retVal;
}
<|endoftext|>


<commit_before>// Time:  O(1)
// Space: O(1)

class Solution {
public:
    int maxA(int N) {
        if (N < 7) {
            return N;
        }
        if (N == 10) {  // the following rule doesn't hold in N = 10
            return 20;
        }
        auto n = N / 5 + 1;  // n3 + n4 increases one every 5 keys
        // (1) n     =     n3 +     n4
        // (2) N + 1 = 4 * n3 + 5 * n4
        //     5 x (1) - (2) => 5*n - N - 1 = n3
        auto n3 = 5 * n - N - 1;
        auto n4 = n - n3;
        return pow(3, n3) * pow(4, n4);
    }
};

// Time:  O(n)
// Space: O(1)
class Solution2 {
public:
    int maxA(int N) {
        if (N < 7) {
            return N;
        }
        vector<int> dp(6);
        iota(dp.begin(), dp.end(), 0);
        for (int i = 7; i <= N; ++i) {
            dp[i % 6] = max(dp[(i - 4) % 6] * 3, dp[(i - 5) % 6] * 4);
        }
        return dp[N % 6];
    }
};
<commit_msg>Update 4-keys-keyboard.cpp<commit_after>// Time:  O(1)
// Space: O(1)

class Solution {
public:
    int maxA(int N) {
        if (N < 7) {
            return N;
        }
        if (N == 10) {  // the following rule doesn't hold when N = 10
            return 20;
        }
        auto n = N / 5 + 1;  // n3 + n4 increases one every 5 keys
        // (1) n     =     n3 +     n4
        // (2) N + 1 = 4 * n3 + 5 * n4
        //     5 x (1) - (2) => 5*n - N - 1 = n3
        auto n3 = 5 * n - N - 1;
        auto n4 = n - n3;
        return pow(3, n3) * pow(4, n4);
    }
};

// Time:  O(n)
// Space: O(1)
class Solution2 {
public:
    int maxA(int N) {
        if (N < 7) {
            return N;
        }
        vector<int> dp(6);
        iota(dp.begin(), dp.end(), 0);
        for (int i = 7; i <= N; ++i) {
            dp[i % 6] = max(dp[(i - 4) % 6] * 3, dp[(i - 5) % 6] * 4);
        }
        return dp[N % 6];
    }
};
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <signal.h>
#include <unistd.h>
#include <netinet/in.h>
#include "libcmm.h"
#include "libcmm_test.h"
#include "common.h"
#include <errno.h>
#include "timeops.h"

static bool running;

void handler(int sig)
{
    running = false;
}

void str_reverse(char *str)
{
    char *head = str;
    char *tail = str + strlen(str) - 1;
    while (head < tail) {
        char tmp = *head;
        *head = *tail;
        *tail = tmp;
        head++;
        tail--;
    }
}

void * Worker(void * arg)
{
#ifdef NOMULTISOCK
    int sock = *((int*)arg);
#else
    mc_socket_t sock = *((mc_socket_t*)arg);
#endif
    printf("Starting up on connection %d\n", sock);
    while (1) {
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(sock, &readfds);
#ifdef NOMULTISOCK
        int s_rc = select(sock+1, &readfds, NULL, NULL, NULL);
#else
        /* XXX: make sure this is working properly. */
        int s_rc = cmm_select(sock+1, &readfds, NULL, NULL, NULL);
        //int s_rc = 1;
#endif
        if (s_rc < 0) {
            perror("select");
            break;
        }

        struct chunk ch;
        struct timeval begin, end, diff;
        TIME(begin);
#ifdef NOMULTISOCK
        int rc = read(sock, &ch, sizeof(ch));
#else
        u_long sender_labels = 0;
        int rc = cmm_read(sock, &ch, sizeof(ch), &sender_labels);
#endif
        TIME(end);
        if (rc != sizeof(ch)) {
            if (rc == 0) {
                dbgprintf_always("Connection %d closed remotely\n", sock);
            } else {
                dbgprintf_always("Connection %d had error %d\n", sock, errno);
                perror("cmm_read");
            }
            break;
        }
        TIMEDIFF(begin, end, diff);
        dbgprintf_always("[%lu.%06lu][testapp] Received msg; took %lu.%06lu seconds\n",
                end.tv_sec, end.tv_usec, diff.tv_sec, diff.tv_usec);

        ch.data[sizeof(ch)-1] = '\0';
        printf("Msg: %*s\n", (int)(sizeof(ch) - 1), ch.data);
        //str_reverse(ch.data);
        errno = 0;
        //struct timeval begin, end, diff;
        TIME(begin);
        dbgprintf_always("[%lu.%06lu][testapp] About to send response\n",
                begin.tv_sec, begin.tv_usec);
#ifdef NOMULTISOCK
        rc = send(sock, &ch, sizeof(ch), 0);
#else
        rc = cmm_send(sock, &ch, sizeof(ch), 0,
                      sender_labels, NULL, NULL);
#endif
        TIME(end);
        if (rc != sizeof(ch)) {
            dbgprintf_always("cmm_send returned %d (expected %u), errno=%d\n",
                    rc, sizeof(ch), errno);
            perror("cmm_send");
            break;
        }
        TIMEDIFF(begin, end, diff);
        dbgprintf_always("Sent message; took %lu.%06lu seconds\n",
                diff.tv_sec, diff.tv_usec);
    }

    printf("Done with connection %d\n", sock);
#ifdef NOMULTISOCK
    close(sock);
#else
    cmm_close(sock);
#endif
    return NULL;
}

int main()
{
    int listen_sock = socket(PF_INET, SOCK_STREAM, 0);
    handle_error(listen_sock < 0, "socket");

    int on = 1;
    int rc = setsockopt (listen_sock, SOL_SOCKET, SO_REUSEADDR,
                         (char *) &on, sizeof(on));
    if (rc < 0) {
        dbgprintf_always("Cannot reuse socket address");
    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(LISTEN_PORT);

    rc = bind(listen_sock, (struct sockaddr *)&addr, (socklen_t)sizeof(addr));
    handle_error(rc < 0, "bind");

#ifdef NOMULTISOCK
    rc = listen(listen_sock, 5);
#else
    rc = cmm_listen(listen_sock, 5);
#endif
    handle_error(rc < 0, "cmm_listen");

    running = true;
    signal(SIGINT, handler);
    signal(SIGPIPE, SIG_IGN);

    while (running) {
        struct sockaddr_in remote_addr;
        socklen_t addrlen = sizeof(remote_addr);
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(listen_sock, &readfds);
        rc = select(listen_sock + 1, &readfds, NULL, NULL, NULL);
        if (rc < 0) {
            continue;
        }

#ifdef NOMULTISOCK
        int connecting_sock = accept(listen_sock,
                                     (struct sockaddr *)&addr,
                                     &addrlen);
#else
        mc_socket_t connecting_sock = cmm_accept(listen_sock,
                                                 (struct sockaddr *)&addr,
                                                 &addrlen);
#endif
        if (connecting_sock < 0) {
            perror("cmm_accept");
            continue;
        }
        //pthread_t tid;
        //(void)pthread_create(&tid, NULL, Worker, (void*)&connecting_sock);
        (void)Worker((void*)&connecting_sock);
    }

    return 0;
}

<commit_msg>Changed simple test-receiver to apply counterintutive prefer-labels in response to receiving fg/bg messages, just for testing the prefer-labels.  Result: preference successfully applied.<commit_after>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <signal.h>
#include <unistd.h>
#include <netinet/in.h>
#include "libcmm.h"
#include "libcmm_test.h"
#include "libcmm_net_preference.h"
#include "common.h"
#include <errno.h>
#include "timeops.h"

static bool running;

void handler(int sig)
{
    running = false;
}

void str_reverse(char *str)
{
    char *head = str;
    char *tail = str + strlen(str) - 1;
    while (head < tail) {
        char tmp = *head;
        *head = *tail;
        *tail = tmp;
        head++;
        tail--;
    }
}

void * Worker(void * arg)
{
#ifdef NOMULTISOCK
    int sock = *((int*)arg);
#else
    mc_socket_t sock = *((mc_socket_t*)arg);
#endif
    printf("Starting up on connection %d\n", sock);
    while (1) {
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(sock, &readfds);
#ifdef NOMULTISOCK
        int s_rc = select(sock+1, &readfds, NULL, NULL, NULL);
#else
        /* XXX: make sure this is working properly. */
        int s_rc = cmm_select(sock+1, &readfds, NULL, NULL, NULL);
        //int s_rc = 1;
#endif
        if (s_rc < 0) {
            perror("select");
            break;
        }

        struct chunk ch;
        struct timeval begin, end, diff;
        TIME(begin);
#ifdef NOMULTISOCK
        int rc = read(sock, &ch, sizeof(ch));
#else
        u_long sender_labels = 0;
        int rc = cmm_read(sock, &ch, sizeof(ch), &sender_labels);

        if (sender_labels & CMM_LABEL_ONDEMAND) {
            sender_labels &= (~CMM_LABEL_WIFI_PREFERRED);
            sender_labels |= CMM_LABEL_THREEG_PREFERRED;
            dbgprintf_always("Got FG request: sending prefer-3G response (for testing)\n");
        } else if (sender_labels & CMM_LABEL_BACKGROUND) {
            sender_labels &= (~CMM_LABEL_THREEG_PREFERRED);
            sender_labels |= CMM_LABEL_WIFI_PREFERRED;
            dbgprintf_always("Got BG request: sending prefer-wifi response (for testing)\n");
        }
#endif
        TIME(end);
        if (rc != sizeof(ch)) {
            if (rc == 0) {
                dbgprintf_always("Connection %d closed remotely\n", sock);
            } else {
                dbgprintf_always("Connection %d had error %d\n", sock, errno);
                perror("cmm_read");
            }
            break;
        }
        TIMEDIFF(begin, end, diff);
        dbgprintf_always("[%lu.%06lu][testapp] Received msg; took %lu.%06lu seconds\n",
                end.tv_sec, end.tv_usec, diff.tv_sec, diff.tv_usec);

        ch.data[sizeof(ch)-1] = '\0';
        printf("Msg: %*s\n", (int)(sizeof(ch) - 1), ch.data);
        //str_reverse(ch.data);
        errno = 0;
        //struct timeval begin, end, diff;
        TIME(begin);
        dbgprintf_always("[%lu.%06lu][testapp] About to send response\n",
                begin.tv_sec, begin.tv_usec);
#ifdef NOMULTISOCK
        rc = send(sock, &ch, sizeof(ch), 0);
#else
        rc = cmm_send(sock, &ch, sizeof(ch), 0,
                      sender_labels, NULL, NULL);
#endif
        TIME(end);
        if (rc != sizeof(ch)) {
            dbgprintf_always("cmm_send returned %d (expected %u), errno=%d\n",
                    rc, sizeof(ch), errno);
            perror("cmm_send");
            break;
        }
        TIMEDIFF(begin, end, diff);
        dbgprintf_always("Sent message; took %lu.%06lu seconds\n",
                diff.tv_sec, diff.tv_usec);
    }

    printf("Done with connection %d\n", sock);
#ifdef NOMULTISOCK
    close(sock);
#else
    cmm_close(sock);
#endif
    return NULL;
}

int main()
{
    int listen_sock = socket(PF_INET, SOCK_STREAM, 0);
    handle_error(listen_sock < 0, "socket");

    int on = 1;
    int rc = setsockopt (listen_sock, SOL_SOCKET, SO_REUSEADDR,
                         (char *) &on, sizeof(on));
    if (rc < 0) {
        dbgprintf_always("Cannot reuse socket address");
    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(LISTEN_PORT);

    rc = bind(listen_sock, (struct sockaddr *)&addr, (socklen_t)sizeof(addr));
    handle_error(rc < 0, "bind");

#ifdef NOMULTISOCK
    rc = listen(listen_sock, 5);
#else
    rc = cmm_listen(listen_sock, 5);
#endif
    handle_error(rc < 0, "cmm_listen");

    running = true;
    signal(SIGINT, handler);
    signal(SIGPIPE, SIG_IGN);

    while (running) {
        struct sockaddr_in remote_addr;
        socklen_t addrlen = sizeof(remote_addr);
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(listen_sock, &readfds);
        rc = select(listen_sock + 1, &readfds, NULL, NULL, NULL);
        if (rc < 0) {
            continue;
        }

#ifdef NOMULTISOCK
        int connecting_sock = accept(listen_sock,
                                     (struct sockaddr *)&addr,
                                     &addrlen);
#else
        mc_socket_t connecting_sock = cmm_accept(listen_sock,
                                                 (struct sockaddr *)&addr,
                                                 &addrlen);
#endif
        if (connecting_sock < 0) {
            perror("cmm_accept");
            continue;
        }
        //pthread_t tid;
        //(void)pthread_create(&tid, NULL, Worker, (void*)&connecting_sock);
        (void)Worker((void*)&connecting_sock);
    }

    return 0;
}

<|endoftext|>


<commit_before>/*  -*- c++ -*-
    This file is part of KMail, the KDE mail client.
    Copyright (c) 2001-2002 Michael Haeckel <haeckel@kde.org>
    Copyright (c) 2003 Marc Mutz <mutz@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KMail is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "servertest.h"

#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kurl.h>
#include <kio/scheduler.h>
#include <kio/slave.h>
#include <kio/job.h>
#include <kio/global.h>
#include <QApplication>

using namespace KPIM;

//-----------------------------------------------------------------------------
ServerTest::ServerTest( const QString & protocol, const QString & host, int port )
  : QObject(),
    mProtocol( protocol ), mHost( host ),
    mSSL( false ), mJob( 0 ), mSlave( 0 ), mConnectionErrorCount( 0 )
{
  KIO::Scheduler::connect(
    SIGNAL(slaveError(KIO::Slave *, int, const QString &)),
    this, SLOT(slotSlaveResult(KIO::Slave *, int, const QString &)));

  if ( port == 993 || port == 995 || port == 465 )
    port = 0;

  startOffSlave( port );
}

//-----------------------------------------------------------------------------
ServerTest::~ServerTest()
{
  if (mJob) mJob->kill();
}

KIO::MetaData ServerTest::slaveConfig() const {
  KIO::MetaData md;
  md.insert( "nologin", "on" );
  return md;
}

void ServerTest::startOffSlave( int port ) {
  KUrl url;
  url.setProtocol( mSSL ? mProtocol + 's' : mProtocol );
  url.setHost( mHost );
  if ( port )
    url.setPort( port );

  mSlave = KIO::Scheduler::getConnectedSlave( url, slaveConfig() );
  if ( !mSlave ) {
    slotSlaveResult( 0, 1 );
    return;
  }
  connect( mSlave, SIGNAL(metaData(const KIO::MetaData&)),
	   SLOT(slotMetaData(const KIO::MetaData&)) );

  QByteArray packedArgs;
  QDataStream stream( &packedArgs, QIODevice::WriteOnly );

  stream << (int) 'c';

  mJob = KIO::special( url, packedArgs, false );
  KIO::Scheduler::assignJobToSlave( mSlave, mJob );
  connect( mJob, SIGNAL(result(KJob*)), SLOT(slotResult(KJob*)) );
  connect( mJob, SIGNAL(infoMessage(KJob*,const QString&,const QString&)),
	   SLOT(slotData(KJob*,const QString&,const QString&)) );
}

//-----------------------------------------------------------------------------
void ServerTest::slotData(KJob *, const QString &data,const QString&)
{
  if ( mSSL )
    mListSSL = data.split(' ', QString::SkipEmptyParts);
  else
    mListNormal = data.split(' ', QString::SkipEmptyParts);
}

void ServerTest::slotMetaData( const KIO::MetaData & md ) {
  KIO::MetaData::const_iterator it = md.find( "PLAIN AUTH METHODS" );
  if ( it != md.end() ) {
    mAuthNone = it.value();
    kDebug(5006) << "mAuthNone: " << mAuthNone << endl;
  }
  it = md.find( "TLS AUTH METHODS" );
  if ( it != md.end() ) {
    mAuthTLS = it.value();
    kDebug(5006) << "mAuthTLS: " << mAuthTLS << endl;
  }
  it = md.find( "SSL AUTH METHODS" );
  if ( it != md.end() ) {
    mAuthSSL = it.value();
    kDebug(5006) << "mAuthSSL: " << mAuthSSL << endl;
  }
}

//-----------------------------------------------------------------------------
void ServerTest::slotResult(KJob *job)
{
  slotSlaveResult(mSlave, job->error());
}

//-----------------------------------------------------------------------------
void ServerTest::slotSlaveResult(KIO::Slave *aSlave, int error,
  const QString &errorText)
{
  if (aSlave != mSlave) return;
  if ( mSSL && error == 0 ) {
    // add a dummy entry to the list of SSL capabilities so that the receiver
    // of the capabilities signal can use mListSSL.isEmpty() in order to find
    // out whether SSL is supported
    mListSSL.append("SSL");
  }

  if (error != KIO::ERR_SLAVE_DIED && mSlave)
  {
    // disconnect slave after every connect
    KIO::Scheduler::disconnectSlave(mSlave);
    mSlave = 0;
  }
  if ( error == KIO::ERR_COULD_NOT_CONNECT )
  {
    // if one of the two connection tests fails we ignore the error
    // if both fail the host is probably not correct so we display the error
    if ( mConnectionErrorCount == 0 )
    {
      error = 0;
    }
    ++mConnectionErrorCount;
  }
  if ( error )
  {
    mJob = 0;
    KMessageBox::error( qApp->activeWindow(),
        KIO::buildErrorString( error, errorText ),
        i18n("Error") );
    emit capabilities( mListNormal, mListSSL );
    emit capabilities( mListNormal, mListSSL, mAuthNone, mAuthSSL, mAuthTLS );
    return;
  }
  if (!mSSL) {
    mSSL = true;
    mListNormal.append("NORMAL-CONNECTION");
    startOffSlave();
  } else {
    mJob = 0;

    emit capabilities( mListNormal, mListSSL );
    emit capabilities( mListNormal, mListSSL, mAuthNone, mAuthSSL, mAuthTLS );
  }
}

#include "servertest.moc"
<commit_msg>Handle the special case that the ioslave could not be started and show 'Unknown error n' if KIO::buildErrorString() returns an empty string.<commit_after>/*  -*- c++ -*-
    This file is part of KMail, the KDE mail client.
    Copyright (c) 2001-2002 Michael Haeckel <haeckel@kde.org>
    Copyright (c) 2003 Marc Mutz <mutz@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KMail is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "servertest.h"

#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kurl.h>
#include <kio/scheduler.h>
#include <kio/slave.h>
#include <kio/job.h>
#include <kio/global.h>
#include <QApplication>

using namespace KPIM;

//-----------------------------------------------------------------------------
ServerTest::ServerTest( const QString & protocol, const QString & host, int port )
  : QObject(),
    mProtocol( protocol ), mHost( host ),
    mSSL( false ), mJob( 0 ), mSlave( 0 ), mConnectionErrorCount( 0 )
{
  KIO::Scheduler::connect(
    SIGNAL(slaveError(KIO::Slave *, int, const QString &)),
    this, SLOT(slotSlaveResult(KIO::Slave *, int, const QString &)));

  if ( port == 993 || port == 995 || port == 465 )
    port = 0;

  startOffSlave( port );
}

//-----------------------------------------------------------------------------
ServerTest::~ServerTest()
{
  if (mJob) mJob->kill();
}

KIO::MetaData ServerTest::slaveConfig() const {
  KIO::MetaData md;
  md.insert( "nologin", "on" );
  return md;
}

void ServerTest::startOffSlave( int port ) {
  KUrl url;
  url.setProtocol( mSSL ? mProtocol + 's' : mProtocol );
  url.setHost( mHost );
  if ( port )
    url.setPort( port );

  mSlave = KIO::Scheduler::getConnectedSlave( url, slaveConfig() );
  if ( !mSlave ) {
    slotSlaveResult( 0, 1 );
    return;
  }
  connect( mSlave, SIGNAL(metaData(const KIO::MetaData&)),
	   SLOT(slotMetaData(const KIO::MetaData&)) );

  QByteArray packedArgs;
  QDataStream stream( &packedArgs, QIODevice::WriteOnly );

  stream << (int) 'c';

  mJob = KIO::special( url, packedArgs, false );
  KIO::Scheduler::assignJobToSlave( mSlave, mJob );
  connect( mJob, SIGNAL(result(KJob*)), SLOT(slotResult(KJob*)) );
  connect( mJob, SIGNAL(infoMessage(KJob*,const QString&,const QString&)),
	   SLOT(slotData(KJob*,const QString&,const QString&)) );
}

//-----------------------------------------------------------------------------
void ServerTest::slotData(KJob *, const QString &data,const QString&)
{
  if ( mSSL )
    mListSSL = data.split(' ', QString::SkipEmptyParts);
  else
    mListNormal = data.split(' ', QString::SkipEmptyParts);
}

void ServerTest::slotMetaData( const KIO::MetaData & md ) {
  KIO::MetaData::const_iterator it = md.find( "PLAIN AUTH METHODS" );
  if ( it != md.end() ) {
    mAuthNone = it.value();
    kDebug(5006) << "mAuthNone: " << mAuthNone << endl;
  }
  it = md.find( "TLS AUTH METHODS" );
  if ( it != md.end() ) {
    mAuthTLS = it.value();
    kDebug(5006) << "mAuthTLS: " << mAuthTLS << endl;
  }
  it = md.find( "SSL AUTH METHODS" );
  if ( it != md.end() ) {
    mAuthSSL = it.value();
    kDebug(5006) << "mAuthSSL: " << mAuthSSL << endl;
  }
}

//-----------------------------------------------------------------------------
void ServerTest::slotResult(KJob *job)
{
  slotSlaveResult(mSlave, job->error());
}

//-----------------------------------------------------------------------------
void ServerTest::slotSlaveResult(KIO::Slave *aSlave, int error,
  const QString &errorText)
{
  if (aSlave != mSlave) return;
  if ( mSSL && error == 0 ) {
    // add a dummy entry to the list of SSL capabilities so that the receiver
    // of the capabilities signal can use mListSSL.isEmpty() in order to find
    // out whether SSL is supported
    mListSSL.append("SSL");
  }

  if (error != KIO::ERR_SLAVE_DIED && mSlave)
  {
    // disconnect slave after every connect
    KIO::Scheduler::disconnectSlave(mSlave);
    mSlave = 0;
  }
  if ( error == KIO::ERR_COULD_NOT_CONNECT )
  {
    // if one of the two connection tests fails we ignore the error
    // if both fail the host is probably not correct so we display the error
    if ( mConnectionErrorCount == 0 )
    {
      error = 0;
    }
    ++mConnectionErrorCount;
  }
  if ( error )
  {
    mJob = 0;
    QString errorMessage;
    if ( error == 1 )
    {
      // handle the special case that the slave could not be started
      errorMessage = i18n( "Starting the ioslave for protocol %1 failed.",
                           mSSL ? mProtocol + 's' : mProtocol );
    }
    else
    {
      errorMessage = KIO::buildErrorString( error, errorText );
      if ( errorMessage.isEmpty() ) {
        errorMessage = i18n( "Unknown error %1.", error );
      }
    }
    KMessageBox::error( qApp->activeWindow(), errorMessage, i18n("Error") );
    emit capabilities( mListNormal, mListSSL );
    emit capabilities( mListNormal, mListSSL, mAuthNone, mAuthSSL, mAuthTLS );
    return;
  }
  if (!mSSL) {
    mSSL = true;
    mListNormal.append("NORMAL-CONNECTION");
    startOffSlave();
  } else {
    mJob = 0;

    emit capabilities( mListNormal, mListSSL );
    emit capabilities( mListNormal, mListSSL, mAuthNone, mAuthSSL, mAuthTLS );
  }
}

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


<commit_before>/*
    Copyright (C) 1998-2001 by Jorrit Tyberghein
    csObject library (C) 1999 by Ivan Avramovic <ivan@avramovic.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/csobject.h"
#include "csutil/dataobj.h"
#include "csutil/typedvec.h"

#include <stdlib.h>
#include <string.h>

CS_DECLARE_TYPED_IBASE_VECTOR (csObjectContainer, iObject);

/*** Object Iterators ***/

class csObjectIterator : public iObjectIterator
{
public:
  SCF_DECLARE_IBASE;
  csObject *Object;
  int Position;

  csObjectIterator (csObject *obj) : Object (obj)
  {
    SCF_CONSTRUCT_IBASE (NULL);
    Object->IncRef ();
    Reset ();
  }
  virtual ~csObjectIterator ()
  {
    Object->DecRef ();
  }
  virtual bool Next()
  {
    if (Position < 0)
      return false;

    Position++;
    if (Position == Object->Children->Length ())
    {
      Position = -1;
      return false;
    }
    return true;
  }
  virtual void Reset()
  {
    if (Object->Children == NULL || Object->Children->Length () < 1)
      Position = -1;
    else
      Position = 0;
  }
  virtual iObject *GetObject () const
  {
    return Object->Children->Get (Position);
  }
  virtual iObject* GetParentObj() const
  {
    return Object;
  }
  virtual bool IsFinished () const
  {
    return (Position < 0);
  }
  virtual bool FindName (const char* name)
  {
    while (!IsFinished ())
    {
      if (strcmp (GetObject ()->GetName (), name) == 0)
        return true;
      Next ();
    }
    return false;
  }
};

SCF_IMPLEMENT_IBASE (csObjectIterator)
  SCF_IMPLEMENTS_INTERFACE (iObjectIterator)
SCF_IMPLEMENT_IBASE_END

/*** csObject itself ***/

SCF_IMPLEMENT_IBASE (csObject)
  SCF_IMPLEMENTS_INTERFACE (iObject)
SCF_IMPLEMENT_IBASE_END

csObject::csObject (iBase* pParent) : Children (NULL), Name (NULL)
{
  SCF_CONSTRUCT_IBASE (pParent);
  static CS_ID id = 0;
  csid = id++;
  ParentObject = NULL;
}

csObject::csObject (csObject &o) : Children (NULL), Name (NULL)
{
  csObject (NULL);

  iObjectIterator *it = o.GetIterator ();
  while (!it->IsFinished ()) {
    ObjAdd (it->GetObject ());
    it->Next ();
  }
  it->DecRef ();
  SetName (o.GetName ());
}

csObject::~csObject ()
{
  ObjRemoveAll ();

  if (Children) { delete Children; Children = NULL; }
  delete [] Name; Name = NULL;

  /*
   * @@@ This should not be required for two reasons:
   * 1. If the parent keeps a pointer to this object, then the pointer was
   *    IncRef'ed, so this object cannot be deleted. Removing the object from
   *    its parent from here is only needed if the object was illegally
   *    deleted, not DecRef'ed.
   * 2. Several objects could contain this object as a child. The 'parent'
   *    pointer is not a safe way to find out which object contains this
   *    object as a child.
   */
  if (ParentObject)
  {
    ParentObject->ObjReleaseOld (this);
  }
}

void csObject::SetName (const char *iName)
{
  delete [] Name;
  Name = csStrNew (iName);
}

const char *csObject::GetName () const
{
  return Name;
}

CS_ID csObject::GetID () const
{
  return csid;
}

iObject* csObject::GetObjectParent () const
{
  return ParentObject;
}

void csObject::SetObjectParent (iObject *obj)
{
  ParentObject = obj;
}

void csObject::ObjAdd (iObject *obj)
{
  if (!obj)
    return;

  if (!Children)
    Children = new csObjectContainer ();

  obj->SetObjectParent (this);
  Children->Push (obj);
}

void csObject::ObjRemove (iObject *obj)
{
  if (!Children || !obj)
    return;

  int n = Children->Find (obj);
  if (n>=0)
  {
    obj->SetObjectParent (NULL);
    Children->Delete (n);
  }
}

void csObject::ObjReleaseOld (iObject *obj)
{
  if (!Children || !obj)
    return;

  int n = Children->Find (obj);
  if (n>=0)
  {
    obj->SetObjectParent (NULL);
    // @@@ WARNING! Doing only one DecRef() here does not prevent a second
    // deletion of 'obj'.  Keep in mind that we are currently executing
    // in the destructor of 'obj' itself. If only one 'IncRef()' is used
    // then the Delete() from the children vector will simply destroy the
    // object again (with bad consequences). Doing two IncRef()'s is a
    // solution for this and it doesn't prevent deletion of the object
    // since it is being deleted already.
    obj->IncRef ();
    obj->IncRef ();
    Children->Delete (n);
  }
}

void csObject::ObjRemoveAll ()
{
  if (!Children)
    return;

  int i;
  for (i=Children->Length ()-1; i>=0; i--)
  {
    iObject* child = Children->Get (i);
    child->SetObjectParent (NULL);
    Children->Delete (i);
  }
}

void csObject::ObjAddChildren (iObject *Parent)
{
  iObjectIterator *it = Parent->GetIterator ();
  while (!it->IsFinished ())
  {
    ObjAdd (it->GetObject ());
    it->Next ();
  }
  it->DecRef ();
}

void* csObject::GetChild (int InterfaceID, int Version,
	const char *Name, bool fn) const
{
  if (!Children)
    return NULL;

  if (fn)
  {
    iObject *obj = GetChild (Name);
    return obj ? obj->QueryInterface (InterfaceID, Version) : NULL;
  }

  int i;
  for (i = 0; i < Children->Length (); i++)
  {
    if (Name) {
      const char *OtherName = Children->Get (i)->GetName ();
      if (!OtherName) continue;
      if (strcmp(OtherName, Name)) continue;
    }

    void *obj = Children->Get (i)->QueryInterface (InterfaceID, Version);
    if (obj) return obj;
  }

  return NULL;
}

iObject* csObject::GetChild (const char *Name) const
{
  if (!Children || !Name)
    return NULL;

  int i;
  for (i = 0; i < Children->Length (); i++)
  {
    if (!strcmp (Children->Get (i)->GetName (), Name))
      return Children->Get (i);
  }
  return NULL;
}

iObjectIterator *csObject::GetIterator ()
{
  return new csObjectIterator (this);
}

//------------------- miscelaneous simple classes derived from csObject -----//

SCF_IMPLEMENT_IBASE_EXT (csDataObject)
  SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iDataObject)
SCF_IMPLEMENT_IBASE_EXT_END

SCF_IMPLEMENT_EMBEDDED_IBASE (csDataObject::DataObject)
  SCF_IMPLEMENTS_INTERFACE (iDataObject)
SCF_IMPLEMENT_EMBEDDED_IBASE_END
<commit_msg>Formatting.<commit_after>/*
    Copyright (C) 1998-2001 by Jorrit Tyberghein
    csObject library (C) 1999 by Ivan Avramovic <ivan@avramovic.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/csobject.h"
#include "csutil/dataobj.h"
#include "csutil/typedvec.h"

#include <stdlib.h>
#include <string.h>

CS_DECLARE_TYPED_IBASE_VECTOR (csObjectContainer, iObject);

/*** Object Iterators ***/

class csObjectIterator : public iObjectIterator
{
public:
  SCF_DECLARE_IBASE;
  csObject *Object;
  int Position;

  csObjectIterator (csObject *obj) : Object (obj)
  {
    SCF_CONSTRUCT_IBASE (NULL);
    Object->IncRef ();
    Reset ();
  }
  virtual ~csObjectIterator ()
  {
    Object->DecRef ();
  }
  virtual bool Next()
  {
    if (Position < 0)
      return false;

    Position++;
    if (Position == Object->Children->Length ())
    {
      Position = -1;
      return false;
    }
    return true;
  }
  virtual void Reset()
  {
    if (Object->Children == NULL || Object->Children->Length () < 1)
      Position = -1;
    else
      Position = 0;
  }
  virtual iObject *GetObject () const
  {
    return Object->Children->Get (Position);
  }
  virtual iObject* GetParentObj() const
  {
    return Object;
  }
  virtual bool IsFinished () const
  {
    return (Position < 0);
  }
  virtual bool FindName (const char* name)
  {
    while (!IsFinished ())
    {
      if (strcmp (GetObject ()->GetName (), name) == 0)
        return true;
      Next ();
    }
    return false;
  }
};

SCF_IMPLEMENT_IBASE (csObjectIterator)
  SCF_IMPLEMENTS_INTERFACE (iObjectIterator)
SCF_IMPLEMENT_IBASE_END

/*** csObject itself ***/

SCF_IMPLEMENT_IBASE (csObject)
  SCF_IMPLEMENTS_INTERFACE (iObject)
SCF_IMPLEMENT_IBASE_END

csObject::csObject (iBase* pParent) : Children (NULL), Name (NULL)
{
  SCF_CONSTRUCT_IBASE (pParent);
  static CS_ID id = 0;
  csid = id++;
  ParentObject = NULL;
}

csObject::csObject (csObject &o) : Children (NULL), Name (NULL)
{
  csObject (NULL);

  iObjectIterator *it = o.GetIterator ();
  while (!it->IsFinished ())
  {
    ObjAdd (it->GetObject ());
    it->Next ();
  }
  it->DecRef ();
  SetName (o.GetName ());
}

csObject::~csObject ()
{
  ObjRemoveAll ();

  if (Children) { delete Children; Children = NULL; }
  delete [] Name; Name = NULL;

  /*
   * @@@ This should not be required for two reasons:
   * 1. If the parent keeps a pointer to this object, then the pointer was
   *    IncRef'ed, so this object cannot be deleted. Removing the object from
   *    its parent from here is only needed if the object was illegally
   *    deleted, not DecRef'ed.
   * 2. Several objects could contain this object as a child. The 'parent'
   *    pointer is not a safe way to find out which object contains this
   *    object as a child.
   */
  if (ParentObject)
  {
    ParentObject->ObjReleaseOld (this);
  }
}

void csObject::SetName (const char *iName)
{
  delete [] Name;
  Name = csStrNew (iName);
}

const char *csObject::GetName () const
{
  return Name;
}

CS_ID csObject::GetID () const
{
  return csid;
}

iObject* csObject::GetObjectParent () const
{
  return ParentObject;
}

void csObject::SetObjectParent (iObject *obj)
{
  ParentObject = obj;
}

void csObject::ObjAdd (iObject *obj)
{
  if (!obj)
    return;

  if (!Children)
    Children = new csObjectContainer ();

  obj->SetObjectParent (this);
  Children->Push (obj);
}

void csObject::ObjRemove (iObject *obj)
{
  if (!Children || !obj)
    return;

  int n = Children->Find (obj);
  if (n>=0)
  {
    obj->SetObjectParent (NULL);
    Children->Delete (n);
  }
}

void csObject::ObjReleaseOld (iObject *obj)
{
  if (!Children || !obj)
    return;

  int n = Children->Find (obj);
  if (n>=0)
  {
    obj->SetObjectParent (NULL);
    // @@@ WARNING! Doing only one DecRef() here does not prevent a second
    // deletion of 'obj'.  Keep in mind that we are currently executing
    // in the destructor of 'obj' itself. If only one 'IncRef()' is used
    // then the Delete() from the children vector will simply destroy the
    // object again (with bad consequences). Doing two IncRef()'s is a
    // solution for this and it doesn't prevent deletion of the object
    // since it is being deleted already.
    obj->IncRef ();
    obj->IncRef ();
    Children->Delete (n);
  }
}

void csObject::ObjRemoveAll ()
{
  if (!Children)
    return;

  int i;
  for (i=Children->Length ()-1; i>=0; i--)
  {
    iObject* child = Children->Get (i);
    child->SetObjectParent (NULL);
    Children->Delete (i);
  }
}

void csObject::ObjAddChildren (iObject *Parent)
{
  iObjectIterator *it = Parent->GetIterator ();
  while (!it->IsFinished ())
  {
    ObjAdd (it->GetObject ());
    it->Next ();
  }
  it->DecRef ();
}

void* csObject::GetChild (int InterfaceID, int Version,
	const char *Name, bool fn) const
{
  if (!Children)
    return NULL;

  if (fn)
  {
    iObject *obj = GetChild (Name);
    return obj ? obj->QueryInterface (InterfaceID, Version) : NULL;
  }

  int i;
  for (i = 0; i < Children->Length (); i++)
  {
    if (Name)
    {
      const char *OtherName = Children->Get (i)->GetName ();
      if (!OtherName) continue;
      if (strcmp(OtherName, Name)) continue;
    }

    void *obj = Children->Get (i)->QueryInterface (InterfaceID, Version);
    if (obj) return obj;
  }

  return NULL;
}

iObject* csObject::GetChild (const char *Name) const
{
  if (!Children || !Name)
    return NULL;

  int i;
  for (i = 0; i < Children->Length (); i++)
  {
    if (!strcmp (Children->Get (i)->GetName (), Name))
      return Children->Get (i);
  }
  return NULL;
}

iObjectIterator *csObject::GetIterator ()
{
  return new csObjectIterator (this);
}

//------------------- miscelaneous simple classes derived from csObject -----//

SCF_IMPLEMENT_IBASE_EXT (csDataObject)
  SCF_IMPLEMENTS_EMBEDDED_INTERFACE (iDataObject)
SCF_IMPLEMENT_IBASE_EXT_END

SCF_IMPLEMENT_EMBEDDED_IBASE (csDataObject::DataObject)
  SCF_IMPLEMENTS_INTERFACE (iDataObject)
SCF_IMPLEMENT_EMBEDDED_IBASE_END
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unopracc.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 18:25:09 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVX_UNOPRACC_HXX
#define _SVX_UNOPRACC_HXX

#ifndef _SVX_UNOSHAPE_HXX
#include <svx/unoshape.hxx>
#endif

#ifndef _SVX_UNOTEXT_HXX
#include <svx/unotext.hxx>
#endif

class SvxEditSource;

/** Wraps SvxUnoTextRangeBase and provides us with the text properties

    Inherits from SvxUnoTextRangeBase and provides XPropertySet and
    XMultiPropertySet interfaces. Just set the selection to the
    required text range and return a reference to a XPropertySet.
 */
class SvxAccessibleTextPropertySet : public SvxUnoTextRangeBase,
                                     public ::com::sun::star::lang::XTypeProvider,
                                     public ::cppu::OWeakObject
{
public:
    SvxAccessibleTextPropertySet( const SvxEditSource*, const SfxItemPropertyMap* );
    virtual ~SvxAccessibleTextPropertySet() throw();

    // XTextRange
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XText > SAL_CALL getText() throw (::com::sun::star::uno::RuntimeException);

    // uno::XInterface
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL acquire() throw();
    virtual void SAL_CALL release() throw();

    // lang::XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException);

    // lang::XTypeProvider
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException);

    // XServiceName
    ::rtl::OUString SAL_CALL getServiceName() throw (::com::sun::star::uno::RuntimeException);
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.4.368); FILE MERGED 2008/04/01 12:49:10 thb 1.4.368.2: #i85898# Stripping all external header guards 2008/03/31 14:22:22 rt 1.4.368.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: unopracc.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SVX_UNOPRACC_HXX
#define _SVX_UNOPRACC_HXX

#include <svx/unoshape.hxx>
#include <svx/unotext.hxx>

class SvxEditSource;

/** Wraps SvxUnoTextRangeBase and provides us with the text properties

    Inherits from SvxUnoTextRangeBase and provides XPropertySet and
    XMultiPropertySet interfaces. Just set the selection to the
    required text range and return a reference to a XPropertySet.
 */
class SvxAccessibleTextPropertySet : public SvxUnoTextRangeBase,
                                     public ::com::sun::star::lang::XTypeProvider,
                                     public ::cppu::OWeakObject
{
public:
    SvxAccessibleTextPropertySet( const SvxEditSource*, const SfxItemPropertyMap* );
    virtual ~SvxAccessibleTextPropertySet() throw();

    // XTextRange
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XText > SAL_CALL getText() throw (::com::sun::star::uno::RuntimeException);

    // uno::XInterface
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL acquire() throw();
    virtual void SAL_CALL release() throw();

    // lang::XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException);

    // lang::XTypeProvider
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException);

    // XServiceName
    ::rtl::OUString SAL_CALL getServiceName() throw (::com::sun::star::uno::RuntimeException);
};

#endif

<|endoftext|>


<commit_before>/*  libscratch - Multipurpose objective C++ library.
    Copyright (C) 2012 - 2013  Angelo Geels

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include <cstdio> // for printf
#include <iostream> // for std::cin.get

#include <Scratch.h>

static INDEX _ctFailed = 0;

#define TEST(expr) {                \
  BOOL bSuccess = (expr);           \
  ASSERT(bSuccess);                 \
  printf("  Test: (%s) ", #expr);   \
  if(!bSuccess) {                   \
    _ctFailed++;                    \
    printf("FAILED!\n");            \
  } else {                          \
    printf("OK\n");                 \
  }                                 \
}

/// String testing
void TestString()
{
  printf("Testing strings\n");

  CString strTest;
  strTest += "Lib";
  strTest += "Scratch";
  strTest = strTest.ToLower();
  TEST(strTest == "libscratch");

  strTest += " is great";
  CStackArray<CString> astrParse = strTest.Split(" ");
  TEST(astrParse[2] == "great");
  TEST(astrParse[2][1] == 'r');

  CString strTest2 = strTest.Replace("great", "cool");
  TEST(strTest2 == "libscratch is cool");
}

/// Stack array testing
void TestStackArray()
{
  printf("Testing stack arrays\n");

  CStackArray<INDEX> aiNumbers;
  TEST(aiNumbers.Count() == 0);

  aiNumbers.Push() = 5;
  aiNumbers.Push() = 10;
  aiNumbers.Push() = 15;
  TEST(aiNumbers.Count() == 3);
  TEST(aiNumbers[0] == 5);
  TEST(aiNumbers[1] == 10);
  TEST(aiNumbers[2] + aiNumbers[0] == 20);

  TEST(aiNumbers.Pop() == 15);
  TEST(aiNumbers.Count() == 2);
}

int main()
{
  // perform tests
  TestString();
  TestStackArray();

  // check if all went OK
  if(_ctFailed == 0) {
    // it did! no failures. :)
    printf("\n\nAll OK!\n");
  } else {
    // oops, there's a bug somewhere. please report!
    printf("\n\nSome problems seem to have popped up. Please report a bug.\n");
  }

  std::cin.get();
  return 0;
}
<commit_msg>Added dictionary tests<commit_after>/*  libscratch - Multipurpose objective C++ library.
    Copyright (C) 2012 - 2013  Angelo Geels

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include <cstdio> // for printf
#include <iostream> // for std::cin.get

#include <Scratch.h>

static INDEX _ctFailed = 0;

#define TEST(expr) {                \
  BOOL bSuccess = (expr);           \
  ASSERT(bSuccess);                 \
  printf("  Test: (%s) ", #expr);   \
  if(!bSuccess) {                   \
    _ctFailed++;                    \
    printf("FAILED!\n");            \
  } else {                          \
    printf("OK\n");                 \
  }                                 \
}

/// String testing
void TestString()
{
  printf("Testing strings\n");

  CString strTest;
  strTest += "Lib";
  strTest += "Scratch";
  strTest = strTest.ToLower();
  TEST(strTest == "libscratch");

  strTest += " is great";
  CStackArray<CString> astrParse = strTest.Split(" ");
  TEST(astrParse[2] == "great");
  TEST(astrParse[2][1] == 'r');

  CString strTest2 = strTest.Replace("great", "cool");
  TEST(strTest2 == "libscratch is cool");
}

/// Stack array testing
void TestStackArray()
{
  printf("Testing stack arrays\n");

  CStackArray<INDEX> aiNumbers;
  TEST(aiNumbers.Count() == 0);

  aiNumbers.Push() = 5;
  aiNumbers.Push() = 10;
  aiNumbers.Push() = 15;
  TEST(aiNumbers.Count() == 3);
  TEST(aiNumbers[0] == 5);
  TEST(aiNumbers[1] == 10);
  TEST(aiNumbers[2] + aiNumbers[0] == 20);

  TEST(aiNumbers.Pop() == 15);
  TEST(aiNumbers.Count() == 2);
}

/// Dictionary testing
void TestDictionary()
{
  printf("Testing dictionary\n");

  CDictionary<CString, INDEX> diTest;
  TEST(!diTest.HasKey("Test"));

  diTest["Test"] = 100;
  diTest["Test2"] = 200;
  TEST(diTest.HasKey("Test"));
  TEST(diTest["Test"] == 100);

  diTest.RemoveByKey("Test");
  TEST(diTest.Count() == 1);
  TEST(!diTest.HasKey("Test"));
}

int main()
{
  // perform tests
  TestString();
  TestStackArray();
  TestDictionary();

  // check if all went OK
  if(_ctFailed == 0) {
    // it did! no failures. :)
    printf("\n\nAll OK!\n");
  } else {
    // oops, there's a bug somewhere. please report!
    printf("\n\nSome problems seem to have popped up. Please report a bug.\n");
  }

  std::cin.get();
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: inpdlg.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2006-11-06 14:53:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _INPDLG_HXX
#define _INPDLG_HXX

#ifndef _SVX_STDDLG_HXX //autogen
#include <svx/stddlg.hxx>
#endif

#ifndef _SV_SVMEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

class SwInputField;
class SwSetExpField;
class SwUserFieldType;
class SwField;
class SwWrtShell;

/*--------------------------------------------------------------------
     Beschreibung: Einfuegen Felder
 --------------------------------------------------------------------*/

class SwFldInputDlg: public SvxStandardDialog
{
    virtual void    Apply();
    virtual void    StateChanged( StateChangedType );

    SwWrtShell         &rSh;
    SwInputField*       pInpFld;
    SwSetExpField*      pSetFld;
    SwUserFieldType*    pUsrType;

    Edit                aLabelED;

    MultiLineEdit       aEditED;
    FixedLine           aEditFL;

    OKButton            aOKBT;
    CancelButton        aCancelBT;
    PushButton          aNextBT;
    HelpButton          aHelpBT;

    DECL_LINK(NextHdl, PushButton*);
public:
    SwFldInputDlg(  Window *pParent, SwWrtShell &rSh,
                    SwField* pField, BOOL bNextButton = FALSE );
    ~SwFldInputDlg();
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.656); FILE MERGED 2008/04/01 15:59:14 thb 1.5.656.2: #i85898# Stripping all external header guards 2008/03/31 16:58:33 rt 1.5.656.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: inpdlg.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _INPDLG_HXX
#define _INPDLG_HXX

#include <svx/stddlg.hxx>

#ifndef _SV_SVMEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif
#include <vcl/fixed.hxx>
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

class SwInputField;
class SwSetExpField;
class SwUserFieldType;
class SwField;
class SwWrtShell;

/*--------------------------------------------------------------------
     Beschreibung: Einfuegen Felder
 --------------------------------------------------------------------*/

class SwFldInputDlg: public SvxStandardDialog
{
    virtual void    Apply();
    virtual void    StateChanged( StateChangedType );

    SwWrtShell         &rSh;
    SwInputField*       pInpFld;
    SwSetExpField*      pSetFld;
    SwUserFieldType*    pUsrType;

    Edit                aLabelED;

    MultiLineEdit       aEditED;
    FixedLine           aEditFL;

    OKButton            aOKBT;
    CancelButton        aCancelBT;
    PushButton          aNextBT;
    HelpButton          aHelpBT;

    DECL_LINK(NextHdl, PushButton*);
public:
    SwFldInputDlg(  Window *pParent, SwWrtShell &rSh,
                    SwField* pField, BOOL bNextButton = FALSE );
    ~SwFldInputDlg();
};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: detreg.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 23:28:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include "swdetect.hxx"

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

extern "C" {

SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment(
        const  sal_Char**   ppEnvironmentTypeName,
        uno_Environment**   ppEnvironment           )
{
    *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}

SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo(
    void*   pServiceManager ,
    void*   pRegistryKey    )
{
    Reference< ::registry::XRegistryKey >
            xKey( reinterpret_cast< ::registry::XRegistryKey* >( pRegistryKey ) ) ;

    OUString aDelimiter( RTL_CONSTASCII_USTRINGPARAM("/") );
    OUString aUnoServices( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") );

    // Eigentliche Implementierung und ihre Services registrieren
    sal_Int32 i;
    Reference< ::registry::XRegistryKey >  xNewKey;

    xNewKey = xKey->createKey( aDelimiter + SwFilterDetect::impl_getStaticImplementationName() +
                               aUnoServices );

    Sequence< OUString > aServices = SwFilterDetect::impl_getStaticSupportedServiceNames();
    for(i = 0; i < aServices.getLength(); i++ )
        xNewKey->createKey( aServices.getConstArray()[i] );

    return sal_True;
}

SAL_DLLPUBLIC_EXPORT void* SAL_CALL component_getFactory(
    const sal_Char* pImplementationName,
    void* pServiceManager,
    void* pRegistryKey )
{
    // Set default return value for this operation - if it failed.
    void* pReturn = NULL ;

    if  (
            ( pImplementationName   !=  NULL ) &&
            ( pServiceManager       !=  NULL )
        )
    {
        // Define variables which are used in following macros.
        Reference< XSingleServiceFactory >   xFactory                                                                                ;
        Reference< XMultiServiceFactory >    xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;

        if( SwFilterDetect::impl_getStaticImplementationName().equalsAscii( pImplementationName ) )
        {
            xFactory = ::cppu::createSingleFactory( xServiceManager,
            SwFilterDetect::impl_getStaticImplementationName(),
            SwFilterDetect::impl_createInstance,
            SwFilterDetect::impl_getStaticSupportedServiceNames() );
        }

        // Factory is valid - service was found.
        if ( xFactory.is() )
        {
            xFactory->acquire();
            pReturn = xFactory.get();
        }
    }

    // Return with result of this operation.
    return pReturn ;
}
} // extern "C"

<commit_msg>INTEGRATION: CWS swwarnings (1.6.222); FILE MERGED 2007/03/26 12:09:31 tl 1.6.222.1: #i69287# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: detreg.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 12:41:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include "swdetect.hxx"

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

extern "C" {

SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment(
        const  sal_Char**   ppEnvironmentTypeName,
        uno_Environment**   /*ppEnvironment*/ )
{
    *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}

SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo(
    void*   /*pServiceManager*/,
    void*   pRegistryKey    )
{
    Reference< ::registry::XRegistryKey >
            xKey( reinterpret_cast< ::registry::XRegistryKey* >( pRegistryKey ) ) ;

    OUString aDelimiter( RTL_CONSTASCII_USTRINGPARAM("/") );
    OUString aUnoServices( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") );

    // Eigentliche Implementierung und ihre Services registrieren
    sal_Int32 i;
    Reference< ::registry::XRegistryKey >  xNewKey;

    xNewKey = xKey->createKey( aDelimiter + SwFilterDetect::impl_getStaticImplementationName() +
                               aUnoServices );

    Sequence< OUString > aServices = SwFilterDetect::impl_getStaticSupportedServiceNames();
    for(i = 0; i < aServices.getLength(); i++ )
        xNewKey->createKey( aServices.getConstArray()[i] );

    return sal_True;
}

SAL_DLLPUBLIC_EXPORT void* SAL_CALL component_getFactory(
    const sal_Char* pImplementationName,
    void* pServiceManager,
    void* /*pRegistryKey*/ )
{
    // Set default return value for this operation - if it failed.
    void* pReturn = NULL ;

    if  (
            ( pImplementationName   !=  NULL ) &&
            ( pServiceManager       !=  NULL )
        )
    {
        // Define variables which are used in following macros.
        Reference< XSingleServiceFactory >   xFactory                                                                                ;
        Reference< XMultiServiceFactory >    xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;

        if( SwFilterDetect::impl_getStaticImplementationName().equalsAscii( pImplementationName ) )
        {
            xFactory = ::cppu::createSingleFactory( xServiceManager,
            SwFilterDetect::impl_getStaticImplementationName(),
            SwFilterDetect::impl_createInstance,
            SwFilterDetect::impl_getStaticSupportedServiceNames() );
        }

        // Factory is valid - service was found.
        if ( xFactory.is() )
        {
            xFactory->acquire();
            pReturn = xFactory.get();
        }
    }

    // Return with result of this operation.
    return pReturn ;
}
} // extern "C"

<|endoftext|>