<commit_before>/*
 * Copyright (C) 2007,2008   Alex Shulgin
 *
 * This file is part of png++ the C++ wrapper for libpng.  PNG++ is free
 * software; the exact copying conditions are as follows:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * 3. The name of the author may not be used to endorse or promote products
 * derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
 * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#ifndef PNGPP_IO_BASE_HPP_INCLUDED
#define PNGPP_IO_BASE_HPP_INCLUDED

#include <cassert>
#include <cstdio>
#include "error.hpp"
#include "info.hpp"
#include "end_info.hpp"

namespace png
{

    /**
     * \brief Base class for PNG reader/writer classes.
     *
     * \see  reader, writer
     */
    class io_base
    {
        io_base(io_base const&);
        io_base& operator=(io_base const&);

    public:
        explicit io_base(png_struct* png)
            : m_png(png),
              m_info(*this, m_png),
              m_end_info(*this, m_png)
        {
        }

        ~io_base()
        {
            assert(! m_png);
            assert(! m_info.get_png_info());
            assert(! m_end_info.get_png_info());
        }

        png_struct* get_png_struct() const
        {
            return m_png;
        }

        info& get_info()
        {
            return m_info;
        }

        info const& get_info() const
        {
            return m_info;
        }

        image_info const& get_image_info() const
        {
            return m_info;
        }

        void set_image_info(image_info const& info)
        {
            static_cast< image_info& >(m_info) = info; // slice it
        }

        end_info& get_end_info()
        {
            return m_end_info;
        }

        end_info const& get_end_info() const
        {
            return m_end_info;
        }

        //////////////////////////////////////////////////////////////////////
        // info accessors
        //
        size_t get_width() const
        {
            return m_info.get_width();
        }

        void set_width(size_t width)
        {
            m_info.set_width(width);
        }

        size_t get_height() const
        {
            return m_info.get_height();
        }

        void set_height(size_t height)
        {
            m_info.set_height(height);
        }

        color_type get_color_type() const
        {
            return m_info.get_color_type();
        }

        void set_color_type(color_type color_space)
        {
            m_info.set_color_type(color_space);
        }

        size_t get_bit_depth() const
        {
            return m_info.get_bit_depth();
        }

        void set_bit_depth(size_t bit_depth)
        {
            m_info.set_bit_depth(bit_depth);
        }

        interlace_type get_interlace_type() const
        {
            return m_info.get_interlace_type();
        }

        void set_interlace_type(interlace_type interlace)
        {
            m_info.set_interlace_type(interlace);
        }

        compression_type get_compression_type() const
        {
            return m_info.get_compression_type();
        }

        void set_compression_type(compression_type compression)
        {
            m_info.set_compression_type(compression);
        }

        filter_type get_filter_type() const
        {
            return m_info.get_filter_type();
        }

        void set_filter_type(filter_type filter)
        {
            m_info.set_filter_type(filter);
        }

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

        bool has_chunk(chunk id)
        {
            return png_get_valid(m_png,
                                 m_info.get_png_info(),
                                 uint_32(id)) == uint_32(id);
        }

#if defined(PNG_READ_EXPAND_SUPPORTED)
        void set_gray_1_2_4_to_8() const
        {
            png_set_gray_1_2_4_to_8(m_png);
        }

        void set_palette_to_rgb() const
        {
            png_set_palette_to_rgb(m_png);
        }

        void set_tRNS_to_alpha() const
        {
            png_set_tRNS_to_alpha(m_png);
        }
#endif // defined(PNG_READ_EXPAND_SUPPORTED)

#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
        void set_bgr() const
        {
            png_set_bgr(m_png);
        }
#endif

#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
        void set_gray_to_rgb() const
        {
            png_set_gray_to_rgb(m_png);
        }
#endif

#ifdef PNG_FLOATING_POINT_SUPPORTED
        void set_rgb_to_gray(rgb_to_gray_error_action error_action
                             = rgb_to_gray_silent,
                             double red_weight   = -1.0,
                             double green_weight = -1.0) const
        {
            png_set_rgb_to_gray(m_png, error_action, red_weight, green_weight);
        }
#else
        void set_rgb_to_gray(rgb_to_gray_error_action error_action
                             = rgb_to_gray_silent,
                             fixed_point red_weight   = -1,
                             fixed_point green_weight = -1) const
        {
            png_set_rgb_to_gray_fixed(m_png, error_action,
                                      red_weight, green_weight);
        }
#endif // PNG_FLOATING_POINT_SUPPORTED

        //////////////////////////////////////////////////////////////////////
        // alpha channel transformations
        //
#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
        void set_strip_alpha() const
        {
            png_set_strip_alpha(m_png);
        }
#endif

#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) \
    || defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
        void set_swap_alpha() const
        {
            png_set_swap_alpha(m_png);
        }
#endif

#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) \
    || defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
        void set_invert_alpha() const
        {
            png_set_invert_alpha(m_png);
        }
#endif

#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
        void set_filler(uint_32 filler, filler_type type) const
        {
            png_set_filler(m_png, filler, type);
        }

#if !defined(PNG_1_0_X)
        void set_add_alpha(uint_32 filler, filler_type type) const
        {
            png_set_add_alpha(m_png, filler, type);
        }
#endif
#endif // PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED

#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
        void set_swap() const
        {
            png_set_swap(m_png);
        }
#endif

#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
        void set_packing() const
        {
            png_set_packing(m_png);
        }
#endif

#if defined(PNG_READ_PACKSWAP_SUPPORTED) \
    || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
        void set_packswap() const
        {
            png_set_packswap(m_png);
        }
#endif

#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
        void set_shift(byte red_bits, byte green_bits, byte blue_bits,
                       byte alpha_bits = 0) const
        {
            if (get_color_type() != color_type_rgb
                || get_color_type() != color_type_rgb_alpha)
            {
                throw error("set_shift: expected RGB or RGBA color type");
            }
            color_info bits;
            bits.red = red_bits;
            bits.green = green_bits;
            bits.blue = blue_bits;
            bits.alpha = alpha_bits;
            png_set_shift(m_png, & bits);
        }

        void set_shift(byte gray_bits, byte alpha_bits = 0) const
        {
            if (get_color_type() != color_type_gray
                || get_color_type() != color_type_gray_alpha)
            {
                throw error("set_shift: expected Gray or Gray+Alpha"
                            " color type");
            }
            color_info bits;
            bits.gray = gray_bits;
            bits.alpha = alpha_bits;
            png_set_shift(m_png, & bits);
        }
#endif // PNG_READ_SHIFT_SUPPORTED || PNG_WRITE_SHIFT_SUPPORTED

#if defined(PNG_READ_INTERLACING_SUPPORTED) \
    || defined(PNG_WRITE_INTERLACING_SUPPORTED)
        int set_interlace_handling() const
        {
            return png_set_interlace_handling(m_png);
        }
#endif

#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
        void set_invert_mono() const
        {
            png_set_invert_mono(m_png);
        }
#endif

#if defined(PNG_READ_16_TO_8_SUPPORTED)
        void set_strip_16() const
        {
            png_set_strip_16(m_png);
        }
#endif

#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
        void set_read_user_transform(png_user_transform_ptr transform_fn)
        {
            png_set_read_user_transform_fn(m_png, transform_fn);
        }
#endif

#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) \
    || defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
        void set_user_transform_info(void* info, int bit_depth, int channels)
        {
            png_set_user_transform_info(m_png, info, bit_depth, channels);
        }
#endif

    protected:
        void* get_io_ptr() const
        {
            return png_get_io_ptr(m_png);
        }

        void set_error(char const* message)
        {
            assert(message);
            m_error = message;
        }

        void reset_error()
        {
            m_error.clear();
        }

/*
        std::string const& get_error() const
        {
            return m_error;
        }
*/

        bool is_error() const
        {
            return !m_error.empty();
        }

        void raise_error()
        {
            longjmp(m_png->jmpbuf, -1);
        }

        static void raise_error(png_struct* png, char const* message)
        {
            io_base* io = static_cast< io_base* >(png_get_error_ptr(png));
            io->set_error(message);
            io->raise_error();
        }

        png_struct* m_png;
        info m_info;
        end_info m_end_info;
        std::string m_error;
    };

} // namespace png

#endif // PNGPP_IO_BASE_HPP_INCLUDED
<commit_msg>Fixed compilation with libpng-1.4<commit_after>/*
 * Copyright (C) 2007,2008   Alex Shulgin
 *
 * This file is part of png++ the C++ wrapper for libpng.  PNG++ is free
 * software; the exact copying conditions are as follows:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * 3. The name of the author may not be used to endorse or promote products
 * derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
 * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#ifndef PNGPP_IO_BASE_HPP_INCLUDED
#define PNGPP_IO_BASE_HPP_INCLUDED

#include <cassert>
#include <cstdio>
#include "error.hpp"
#include "info.hpp"
#include "end_info.hpp"

namespace png
{

    /**
     * \brief Base class for PNG reader/writer classes.
     *
     * \see  reader, writer
     */
    class io_base
    {
        io_base(io_base const&);
        io_base& operator=(io_base const&);

    public:
        explicit io_base(png_struct* png)
            : m_png(png),
              m_info(*this, m_png),
              m_end_info(*this, m_png)
        {
        }

        ~io_base()
        {
            assert(! m_png);
            assert(! m_info.get_png_info());
            assert(! m_end_info.get_png_info());
        }

        png_struct* get_png_struct() const
        {
            return m_png;
        }

        info& get_info()
        {
            return m_info;
        }

        info const& get_info() const
        {
            return m_info;
        }

        image_info const& get_image_info() const
        {
            return m_info;
        }

        void set_image_info(image_info const& info)
        {
            static_cast< image_info& >(m_info) = info; // slice it
        }

        end_info& get_end_info()
        {
            return m_end_info;
        }

        end_info const& get_end_info() const
        {
            return m_end_info;
        }

        //////////////////////////////////////////////////////////////////////
        // info accessors
        //
        size_t get_width() const
        {
            return m_info.get_width();
        }

        void set_width(size_t width)
        {
            m_info.set_width(width);
        }

        size_t get_height() const
        {
            return m_info.get_height();
        }

        void set_height(size_t height)
        {
            m_info.set_height(height);
        }

        color_type get_color_type() const
        {
            return m_info.get_color_type();
        }

        void set_color_type(color_type color_space)
        {
            m_info.set_color_type(color_space);
        }

        size_t get_bit_depth() const
        {
            return m_info.get_bit_depth();
        }

        void set_bit_depth(size_t bit_depth)
        {
            m_info.set_bit_depth(bit_depth);
        }

        interlace_type get_interlace_type() const
        {
            return m_info.get_interlace_type();
        }

        void set_interlace_type(interlace_type interlace)
        {
            m_info.set_interlace_type(interlace);
        }

        compression_type get_compression_type() const
        {
            return m_info.get_compression_type();
        }

        void set_compression_type(compression_type compression)
        {
            m_info.set_compression_type(compression);
        }

        filter_type get_filter_type() const
        {
            return m_info.get_filter_type();
        }

        void set_filter_type(filter_type filter)
        {
            m_info.set_filter_type(filter);
        }

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

        bool has_chunk(chunk id)
        {
            return png_get_valid(m_png,
                                 m_info.get_png_info(),
                                 uint_32(id)) == uint_32(id);
        }

#if defined(PNG_READ_EXPAND_SUPPORTED)
        void set_gray_1_2_4_to_8() const
        {
#if PNG_LIBPNG_VER >= 10400
            png_set_expand_gray_1_2_4_to_8(m_png);
#else
            png_set_gray_1_2_4_to_8(m_png);
#endif
        }

        void set_palette_to_rgb() const
        {
            png_set_palette_to_rgb(m_png);
        }

        void set_tRNS_to_alpha() const
        {
            png_set_tRNS_to_alpha(m_png);
        }
#endif // defined(PNG_READ_EXPAND_SUPPORTED)

#if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
        void set_bgr() const
        {
            png_set_bgr(m_png);
        }
#endif

#if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
        void set_gray_to_rgb() const
        {
            png_set_gray_to_rgb(m_png);
        }
#endif

#ifdef PNG_FLOATING_POINT_SUPPORTED
        void set_rgb_to_gray(rgb_to_gray_error_action error_action
                             = rgb_to_gray_silent,
                             double red_weight   = -1.0,
                             double green_weight = -1.0) const
        {
            png_set_rgb_to_gray(m_png, error_action, red_weight, green_weight);
        }
#else
        void set_rgb_to_gray(rgb_to_gray_error_action error_action
                             = rgb_to_gray_silent,
                             fixed_point red_weight   = -1,
                             fixed_point green_weight = -1) const
        {
            png_set_rgb_to_gray_fixed(m_png, error_action,
                                      red_weight, green_weight);
        }
#endif // PNG_FLOATING_POINT_SUPPORTED

        //////////////////////////////////////////////////////////////////////
        // alpha channel transformations
        //
#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
        void set_strip_alpha() const
        {
            png_set_strip_alpha(m_png);
        }
#endif

#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) \
    || defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
        void set_swap_alpha() const
        {
            png_set_swap_alpha(m_png);
        }
#endif

#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) \
    || defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
        void set_invert_alpha() const
        {
            png_set_invert_alpha(m_png);
        }
#endif

#if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
        void set_filler(uint_32 filler, filler_type type) const
        {
            png_set_filler(m_png, filler, type);
        }

#if !defined(PNG_1_0_X)
        void set_add_alpha(uint_32 filler, filler_type type) const
        {
            png_set_add_alpha(m_png, filler, type);
        }
#endif
#endif // PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED

#if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
        void set_swap() const
        {
            png_set_swap(m_png);
        }
#endif

#if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
        void set_packing() const
        {
            png_set_packing(m_png);
        }
#endif

#if defined(PNG_READ_PACKSWAP_SUPPORTED) \
    || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
        void set_packswap() const
        {
            png_set_packswap(m_png);
        }
#endif

#if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
        void set_shift(byte red_bits, byte green_bits, byte blue_bits,
                       byte alpha_bits = 0) const
        {
            if (get_color_type() != color_type_rgb
                || get_color_type() != color_type_rgb_alpha)
            {
                throw error("set_shift: expected RGB or RGBA color type");
            }
            color_info bits;
            bits.red = red_bits;
            bits.green = green_bits;
            bits.blue = blue_bits;
            bits.alpha = alpha_bits;
            png_set_shift(m_png, & bits);
        }

        void set_shift(byte gray_bits, byte alpha_bits = 0) const
        {
            if (get_color_type() != color_type_gray
                || get_color_type() != color_type_gray_alpha)
            {
                throw error("set_shift: expected Gray or Gray+Alpha"
                            " color type");
            }
            color_info bits;
            bits.gray = gray_bits;
            bits.alpha = alpha_bits;
            png_set_shift(m_png, & bits);
        }
#endif // PNG_READ_SHIFT_SUPPORTED || PNG_WRITE_SHIFT_SUPPORTED

#if defined(PNG_READ_INTERLACING_SUPPORTED) \
    || defined(PNG_WRITE_INTERLACING_SUPPORTED)
        int set_interlace_handling() const
        {
            return png_set_interlace_handling(m_png);
        }
#endif

#if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
        void set_invert_mono() const
        {
            png_set_invert_mono(m_png);
        }
#endif

#if defined(PNG_READ_16_TO_8_SUPPORTED)
        void set_strip_16() const
        {
            png_set_strip_16(m_png);
        }
#endif

#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
        void set_read_user_transform(png_user_transform_ptr transform_fn)
        {
            png_set_read_user_transform_fn(m_png, transform_fn);
        }
#endif

#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) \
    || defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
        void set_user_transform_info(void* info, int bit_depth, int channels)
        {
            png_set_user_transform_info(m_png, info, bit_depth, channels);
        }
#endif

    protected:
        void* get_io_ptr() const
        {
            return png_get_io_ptr(m_png);
        }

        void set_error(char const* message)
        {
            assert(message);
            m_error = message;
        }

        void reset_error()
        {
            m_error.clear();
        }

/*
        std::string const& get_error() const
        {
            return m_error;
        }
*/

        bool is_error() const
        {
            return !m_error.empty();
        }

        void raise_error()
        {
            longjmp(m_png->jmpbuf, -1);
        }

        static void raise_error(png_struct* png, char const* message)
        {
            io_base* io = static_cast< io_base* >(png_get_error_ptr(png));
            io->set_error(message);
            io->raise_error();
        }

        png_struct* m_png;
        info m_info;
        end_info m_end_info;
        std::string m_error;
    };

} // namespace png

#endif // PNGPP_IO_BASE_HPP_INCLUDED
<|endoftext|>


<commit_before>#include <cstdio>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
using namespace std;

#define REHASH(a, b, h) ((((h) - (a)*d) << 1) + (b))

// Rabin-Karp search (modified from:
// http://www-igm.univ-mlv.fr/~lecroq/string/node5.html#SECTION0050)
int indexOf(const char *needle, size_t needleLen, const char *haystack,
            size_t haystackLen) {
  if (needleLen == 0) {
    return 0;
  } else if (needleLen > haystackLen) {
    return -1;
  }

  int d, hx, hy, i, j;
  /* Preprocessing */
  /* computes d = 2^(m-1) with
    the left-shift operator */
  for (d = i = 1; i < needleLen; ++i)
    d = (d << 1);

  for (hy = hx = i = 0; i < needleLen; ++i) {
    hx = ((hx << 1) + needle[i]);
    hy = ((hy << 1) + haystack[i]);
  }

  /* Searching */
  j = 0;
  while (j <= haystackLen - needleLen) {
    if (hx == hy && memcmp(needle, haystack + j, needleLen) == 0) {
      return j;
    }
    hy = REHASH(haystack[j], haystack[j + needleLen], hy);
    ++j;
  }

  return -1;
}

int main(int argc, char **argv) {
  if (argc != 4) {
    cout << "usage: fastreplacestring <filename> <term> <replacement>\n";
    return 1;
  }

  string filename = argv[argc - 3];
  const char *old = argv[argc - 2];
  const char *newWord = argv[argc - 1];
  FILE *in = fopen(filename.c_str(), "rb");

  // Check if file exists and can is read-write
  // This is actually a shortcut because fopen might fail for a number of
  // reasons
  if (in == NULL) {
    cout << filename + " doesn't exist\n";
    return 1;
  }

  char *s = NULL;
  vector<int> indexCache;
  size_t r, newFilelen;

  // read filelen given by fileState
  // alternatively this could be determined with fseek && ftell
  fseek(in, 0, SEEK_END);
  size_t filelen = ftell(in);
  fseek(in, 0, SEEK_SET);

  if ((s = (char *)malloc(filelen)) == NULL) {
    printf("malloc s filelen problem \n");
    exit(1);
  }

  // Read in as much of specified file as possible
  // If there isn't anything to read, finish succesfully :)
  if ((r = fread(s, 1, filelen, in)) == 0) {
    free(s);
    fclose(in);
    return 0;
  }

  char *t = NULL;
  char *temp = NULL;

  size_t oldLen = strlen(old);
  size_t newLen = strlen(newWord);

  /* Find all matches and cache their positions. */
  const char *test = NULL;
  test = s;
  int j, start = 0, c = 0;
  int index;

  while ((index = indexOf(old, oldLen, test + start, filelen - start)) != -1) {
    c++;
    j = start;
    j += index;
    indexCache.push_back(j);
    start = j + oldLen;
  }

  if (c == 0) {
    free(s);
    return 0;
  } else {
    const char *pstr = s;
    // calculate new file len & allocate memory
    newFilelen = filelen + c * (newLen - oldLen);
    t = (char *)malloc(newFilelen);

    int i = 0;
    j = 0;
    start = 0;
    temp = t;

    if (temp == NULL) {
      free(s);
      exit(1);
    }
    // replace the bytes
    for (i = 0; i < c; i++) {
      j = indexCache[i];
      memcpy(temp, pstr, j - start);
      temp += j - start;
      pstr = s + j + oldLen;
      memcpy(temp, newWord, newLen);
      temp += newLen;
      start = j + oldLen;
    }
    memcpy(temp, pstr, filelen - j);

    free(s);

    // write the result to a temp file
    // wb mode opens the file for writing and makes it empty
    freopen(filename.c_str(), "wb", in);
    if (in == NULL) {
      cout << filename + " cannot be written to.\n";
      return 1;
    }
    fwrite(t, 1, newFilelen, in);
  }

  return 0;
}
<commit_msg>Make the segfault great again.<commit_after>#include <cstdio>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
using namespace std;

#define REHASH(a, b, h) ((((h) - (a)*d) << 1) + (b))

// Rabin-Karp search (modified from:
// http://www-igm.univ-mlv.fr/~lecroq/string/node5.html#SECTION0050)
int indexOf(const char *needle, size_t needleLen, const char *haystack,
            size_t haystackLen) {
  if (needleLen == 0) {
    return 0;
  } else if (needleLen > haystackLen) {
    return -1;
  }

  int d, hx, hy, i, j;
  /* Preprocessing */
  /* computes d = 2^(m-1) with
    the left-shift operator */
  for (d = i = 1; i < needleLen; ++i)
    d = (d << 1);

  for (hy = hx = i = 0; i < needleLen; ++i) {
    hx = ((hx << 1) + needle[i]);
    hy = ((hy << 1) + haystack[i]);
  }

  /* Searching */
  j = 0;
  while (j <= haystackLen - needleLen) {
    if (hx == hy && memcmp(needle, haystack + j, needleLen) == 0) {
      return j;
    }
    hy = REHASH(haystack[j], haystack[j + needleLen], hy);
    ++j;
  }

  return -1;
}

int main(int argc, char **argv) {
  if (argc != 4) {
    cout << "usage: fastreplacestring <filename> <term> <replacement>\n";
    return 1;
  }

  string filename = argv[argc - 3];
  const char *old = argv[argc - 2];
  const char *newWord = argv[argc - 1];
  FILE *in = fopen(filename.c_str(), "rb");

  // Check if file exists and can is read-write
  // This is actually a shortcut because fopen might fail for a number of
  // reasons
  if (in == NULL) {
    cout << filename + " doesn't exist\n";
    return 1;
  }

  char *s = NULL;
  vector<int> indexCache;
  size_t r, newFilelen;

  // read filelen given by fileState
  // alternatively this could be determined with fseek && ftell
  fseek(in, 0, SEEK_END);
  size_t filelen = ftell(in);
  fseek(in, 0, SEEK_SET);

  if ((s = (char *)malloc(filelen)) == NULL) {
    printf("malloc s filelen problem \n");
    exit(1);
  }

  // Read in as much of specified file as possible
  // If there isn't anything to read, finish succesfully :)
  if ((r = fread(s, 1, filelen, in)) == 0) {
    free(s);
    fclose(in);
    return 0;
  }

  char *t = NULL;
  char *temp = NULL;

  size_t oldLen = strlen(old);
  size_t newLen = strlen(newWord);

  /* Find all matches and cache their positions. */
  const char *test = NULL;
  test = s;
  int j, start = 0, c = 0;
  int index;

  while ((index = indexOf(old, oldLen, test + start, filelen - start)) != -1) {
    c++;
    j = start;
    j += index;
    indexCache.push_back(j);
    start = j + oldLen;
  }

  if (c == 0) {
    free(s);
    return 0;
  } else {
    const char *pstr = s;
    // calculate new file len & allocate memory
    newFilelen = filelen + c * (newLen - oldLen);
    t = (char *)malloc(newFilelen);

    int i = 0;
    j = 0;
    start = 0;
    temp = t;

    if (temp == NULL) {
      free(s);
      exit(1);
    }
    // replace the bytes
    for (i = 0; i < c; i++) {
      j = indexCache[i];
      memcpy(temp, pstr, j - start);
      temp += j - start;
      pstr = s + j + oldLen;
      memcpy(temp, newWord, newLen);
      temp += newLen;
      start = j + oldLen;
    }
    memcpy(temp, pstr, filelen - start);

    free(s);

    // write the result to a temp file
    // wb mode opens the file for writing and makes it empty
    freopen(filename.c_str(), "wb", in);
    if (in == NULL) {
      cout << filename + " cannot be written to.\n";
      return 1;
    }
    fwrite(t, 1, newFilelen, in);
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <agge.text/layout.h>

#include <agge/config.h>
#include <agge/math.h>
#include <agge/tools.h>
#include <agge.text/font_factory.h>
#include <agge.text/limit_processors.h>

using namespace std;

namespace agge
{
	namespace
	{
		template <typename VectorT>
		typename VectorT::value_type &duplicate_last(VectorT &container)
		{	return container.reserve(container.size() + 1), *container.insert(container.end(), container.back());	}
	}

	pair<real_t, real_t> layout::setup_line_metrics(text_line &line)
	{
		real_t descent = real_t();
		pair<real_t, real_t> m((real_t()), (real_t()));

		for (text_line::const_iterator i = line.begin(), end = line.end(); i != end; ++i)
		{
			const font_metrics grm = i->font_->get_metrics();

			if (m.first < grm.ascent)
				m.first = grm.ascent;
			if (m.second < grm.descent + grm.leading)
				m.second = grm.descent + grm.leading;
			if (descent < grm.descent)
				descent = grm.descent;
		}
		line.descent = descent;
		return m;
	}

	pair<real_t, real_t> layout::setup_line_metrics(text_line &line, const font_metrics &m)
	{	return line.empty() ? make_pair(m.ascent, m.descent + m.leading) : setup_line_metrics(line);	}

	layout::layout(font_factory &factory)
		: _factory(factory), _limit_width(1e30f)
	{	}

	void layout::process(const richtext_t &text)
	{
		_text_lines.clear();
		_glyph_runs.clear();
		_glyphs.clear();
		_box = zero();

		text_line *current_line = &*_text_lines.insert(_text_lines.end(), text_line(_glyph_runs));
		glyph_run *current = &*_glyph_runs.insert(_glyph_runs.end(), glyph_run(_glyphs));
		wrap_processor limit_processor;

		for (richtext_t::const_iterator range = text.ranges_begin(); range != text.ranges_end(); ++range)
		{
			current->font_ = _factory.create_font(range->get_annotation().basic);
			current->offset = create_vector(current_line->width, real_t());

			for (string::const_iterator i = range->begin(), end = range->end(), previous = i;
				populate_glyph_run(_glyphs, *current, limit_processor, _limit_width - current_line->width, i, end);
				previous = i)
			{
				if ((i == previous) & current_line->empty())
				{
					// Emergency: width limit is too small to layout even a single character - bailing out!
					_text_lines.clear();
					return;
				}
				commit_glyph_run(*current_line, current);
				limit_processor.init_newline(*current);

				const pair<real_t, real_t> m = setup_line_metrics(*current_line, current->font_->get_metrics());

				current_line->offset += create_vector(real_t(), m.first);
				if (!current_line->empty())
				{
					current_line = &duplicate_last(_text_lines);
					current_line->begin_index = current_line->end_index;
					_box.w = agge_max(_box.w, current_line->width);
					current_line->width = real_t();
				}
				current_line->offset += create_vector(real_t(), m.second);
			}

			// Commit any non-empty content of the current glyph run and prepare the next one.
			commit_glyph_run(*current_line, current);
		}
		if (current_line->empty())
			_text_lines.pop_back();
		else
			current_line->offset += create_vector(real_t(), setup_line_metrics(*current_line).first);
		if (!_text_lines.empty())
		{
			const text_line &last = _text_lines.back();

			_box.w = agge_max(_box.w, last.width);
			_box.h = last.offset.dy + last.descent;
		}
	}

	void layout::commit_glyph_run(text_line &current_line, glyph_run *&current)
	{
		if (!current->empty())
		{
			current_line.extend_end();
			current = &duplicate_last(_glyph_runs);
			current_line.width += current->width;
			current->width = real_t();
			current->set_end();
		}
	}
}
<commit_msg>reset_width extracted as template from commit code for glyph_run and for text_line<commit_after>#include <agge.text/layout.h>

#include <agge/config.h>
#include <agge/math.h>
#include <agge/tools.h>
#include <agge.text/font_factory.h>
#include <agge.text/limit_processors.h>

using namespace std;

namespace agge
{
	namespace
	{
		template <typename VectorT>
		typename VectorT::value_type &duplicate_last(VectorT &container)
		{	return container.reserve(container.size() + 1), *container.insert(container.end(), container.back());	}

		template <typename T>
		real_t reset_width(T &range_)
		{
			real_t w = range_.width;
			return range_.width = real_t(), w;
		}
	}

	pair<real_t, real_t> layout::setup_line_metrics(text_line &line)
	{
		real_t descent = real_t();
		pair<real_t, real_t> m((real_t()), (real_t()));

		for (text_line::const_iterator i = line.begin(), end = line.end(); i != end; ++i)
		{
			const font_metrics grm = i->font_->get_metrics();

			if (m.first < grm.ascent)
				m.first = grm.ascent;
			if (m.second < grm.descent + grm.leading)
				m.second = grm.descent + grm.leading;
			if (descent < grm.descent)
				descent = grm.descent;
		}
		line.descent = descent;
		return m;
	}

	pair<real_t, real_t> layout::setup_line_metrics(text_line &line, const font_metrics &m)
	{	return line.empty() ? make_pair(m.ascent, m.descent + m.leading) : setup_line_metrics(line);	}

	layout::layout(font_factory &factory)
		: _factory(factory), _limit_width(1e30f)
	{	}

	void layout::process(const richtext_t &text)
	{
		_text_lines.clear();
		_glyph_runs.clear();
		_glyphs.clear();
		_box = zero();

		text_line *current_line = &*_text_lines.insert(_text_lines.end(), text_line(_glyph_runs));
		glyph_run *current = &*_glyph_runs.insert(_glyph_runs.end(), glyph_run(_glyphs));
		wrap_processor limit_processor;

		for (richtext_t::const_iterator range = text.ranges_begin(); range != text.ranges_end(); ++range)
		{
			current->font_ = _factory.create_font(range->get_annotation().basic);
			current->offset = create_vector(current_line->width, real_t());

			for (string::const_iterator i = range->begin(), end = range->end(), previous = i;
				populate_glyph_run(_glyphs, *current, limit_processor, _limit_width - current_line->width, i, end);
				previous = i)
			{
				if ((i == previous) & current_line->empty())
				{
					// Emergency: width limit is too small to layout even a single character - bailing out!
					_text_lines.clear();
					return;
				}
				commit_glyph_run(*current_line, current);
				limit_processor.init_newline(*current);

				const pair<real_t, real_t> m = setup_line_metrics(*current_line, current->font_->get_metrics());

				current_line->offset += create_vector(real_t(), m.first);
				if (!current_line->empty())
				{
					current_line = &duplicate_last(_text_lines);
					current_line->begin_index = current_line->end_index;
					_box.w = agge_max(_box.w, reset_width(*current_line));
				}
				current_line->offset += create_vector(real_t(), m.second);
			}

			// Commit any non-empty content of the current glyph run and prepare the next one.
			commit_glyph_run(*current_line, current);
		}
		if (current_line->empty())
			_text_lines.pop_back();
		else
			current_line->offset += create_vector(real_t(), setup_line_metrics(*current_line).first);
		if (!_text_lines.empty())
		{
			const text_line &last = _text_lines.back();

			_box.w = agge_max(_box.w, last.width);
			_box.h = last.offset.dy + last.descent;
		}
	}

	void layout::commit_glyph_run(text_line &current_line, glyph_run *&current)
	{
		if (!current->empty())
		{
			current_line.extend_end();
			current = &duplicate_last(_glyph_runs);
			current->set_end();
			current_line.width += reset_width(*current);
		}
	}
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////

#include <string>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <cstdio>
#include <android/asset_manager.h>
#include <android/log.h>

#include "../platform.hpp"

#define REALM_FILE_FILTER ".realm"
#define REALM_FILE_FILTER_LEN 6

static inline bool is_realm_file(const char* str)
{
    size_t lenstr = strlen(str);
    if (REALM_FILE_FILTER_LEN > lenstr)
        return false;
    return strncmp(str + lenstr - REALM_FILE_FILTER_LEN, REALM_FILE_FILTER, REALM_FILE_FILTER_LEN) == 0;
}

static AAssetManager* s_asset_manager;
static std::string s_default_realm_directory;

namespace realm {

    void set_default_realm_file_directory(std::string dir)
    {
        s_default_realm_directory = dir;
    }

    void set_asset_manager(AAssetManager* asset_manager)
    {
        s_asset_manager = asset_manager;
    }

    std::string default_realm_file_directory()
    {
        return s_default_realm_directory;
    }

    void ensure_directory_exists_for_file(const std::string &file)
    {

    }

    void copy_bundled_realm_files()
    {
        AAssetDir* assetDir = AAssetManager_openDir(s_asset_manager, "");
        const char* filename = nullptr;

        while ((filename = AAssetDir_getNextFileName(assetDir)) != nullptr) {
            if (is_realm_file(filename)) {
                AAsset* asset = AAssetManager_open(s_asset_manager, filename, AASSET_MODE_STREAMING);

                char buf[BUFSIZ];
                int nb_read = 0;

                const char* dest_filename = (s_default_realm_directory + '/' + filename).c_str();
                if (access(dest_filename, F_OK ) == -1) {
                    // file doesn't exist, copy
                    FILE* out = fopen(dest_filename, "w");
                    while ((nb_read = AAsset_read(asset, buf, BUFSIZ)) > 0) {
                        fwrite(buf, nb_read, 1, out);
                    }
                    fclose(out);
                }
                AAsset_close(asset);
            }
        }
        AAssetDir_close(assetDir);
    }

    void remove_realm_files_from_directory(const std::string &directory)
    {
        std::string cmd = "rm " + s_default_realm_directory + "/*.realm " +
                          s_default_realm_directory + "/*.realm.lock";
        system(cmd.c_str());
    }

    void remove_directory(const std::string &path)
    {
        std::string cmd_clear_dir = "rm " + path + "/*";
        system(cmd_clear_dir.c_str());

        std::string cmd_rmdir = "rmdir " + path;
        system(cmd_rmdir.c_str());
    }

    void remove_file(const std::string &path)
    {
        std::string cmd = "rm " + path;
        system(cmd.c_str());
    }

    void print(const char* fmt, ...)
    {
        va_list vl;
        va_start(vl, fmt);
        __android_log_vprint(ANDROID_LOG_INFO, "RealmJS", fmt, vl);
        va_end(vl);
    }
}
<commit_msg>fix dangling c_str() (#3791)<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////

#include <string>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <cstdio>
#include <android/asset_manager.h>
#include <android/log.h>

#include "../platform.hpp"

#define REALM_FILE_FILTER ".realm"
#define REALM_FILE_FILTER_LEN 6

static inline bool is_realm_file(const char* str)
{
    size_t lenstr = strlen(str);
    if (REALM_FILE_FILTER_LEN > lenstr)
        return false;
    return strncmp(str + lenstr - REALM_FILE_FILTER_LEN, REALM_FILE_FILTER, REALM_FILE_FILTER_LEN) == 0;
}

static AAssetManager* s_asset_manager;
static std::string s_default_realm_directory;

namespace realm {

    void set_default_realm_file_directory(std::string dir)
    {
        s_default_realm_directory = dir;
    }

    void set_asset_manager(AAssetManager* asset_manager)
    {
        s_asset_manager = asset_manager;
    }

    std::string default_realm_file_directory()
    {
        return s_default_realm_directory;
    }

    void ensure_directory_exists_for_file(const std::string &file)
    {

    }

    void copy_bundled_realm_files()
    {
        AAssetDir* assetDir = AAssetManager_openDir(s_asset_manager, "");
        const char* filename = nullptr;

        while ((filename = AAssetDir_getNextFileName(assetDir)) != nullptr) {
            if (is_realm_file(filename)) {
                AAsset* asset = AAssetManager_open(s_asset_manager, filename, AASSET_MODE_STREAMING);

                char buf[BUFSIZ];
                int nb_read = 0;

                auto dest_filename = s_default_realm_directory + '/' + filename;
                if (access(dest_filename.c_str(), F_OK ) == -1) {
                    // file doesn't exist, copy
                    FILE* out = fopen(dest_filename.c_str(), "w");
                    while ((nb_read = AAsset_read(asset, buf, BUFSIZ)) > 0) {
                        fwrite(buf, nb_read, 1, out);
                    }
                    fclose(out);
                }
                AAsset_close(asset);
            }
        }
        AAssetDir_close(assetDir);
    }

    void remove_realm_files_from_directory(const std::string &directory)
    {
        std::string cmd = "rm " + s_default_realm_directory + "/*.realm " +
                          s_default_realm_directory + "/*.realm.lock";
        system(cmd.c_str());
    }

    void remove_directory(const std::string &path)
    {
        std::string cmd_clear_dir = "rm " + path + "/*";
        system(cmd_clear_dir.c_str());

        std::string cmd_rmdir = "rmdir " + path;
        system(cmd_rmdir.c_str());
    }

    void remove_file(const std::string &path)
    {
        std::string cmd = "rm " + path;
        system(cmd.c_str());
    }

    void print(const char* fmt, ...)
    {
        va_list vl;
        va_start(vl, fmt);
        __android_log_vprint(ANDROID_LOG_INFO, "RealmJS", fmt, vl);
        va_end(vl);
    }
}
<|endoftext|>


<commit_before><commit_msg>[FIXED] single frame also have expression<commit_after><|endoftext|>


<commit_before>#ifndef ASSET_MANAGER_HPP
#define ASSET_MANAGER_HPP

#include <map>
#include <array>
#include <utility>
#include <string>

#include <dirent.h>

#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Audio/SoundBuffer.hpp>
#include <SFML/Audio/Sound.hpp>
#include <SFML/Audio/Music.hpp>
#include "../Scripting/Script.hpp"

#include "../Logger/Logger.hpp"

#include "Mod.hpp"

namespace swift
{
	class Script;
	class AssetManager
	{
		public:
			AssetManager();
			~AssetManager();

			// Accepts a resource folder. This folder should contain folders containing a common group of resources.
			// This function will recursively roll through the top resource folder, grabbing all resources.
			// The function returns false if it cannot find the given folder, and returns true if otherwise.
			bool loadResourceFolder(const std::string& folder);

			bool loadMod(const Mod& mod);

			// destroys all resources the AssetManager contains
			void clean();

			// sets the AssetManager to load textures with smoothing (antialiasing)
			void setSmooth(bool s);

			sf::Texture& getTexture(const std::string& n);
			//Bitmask& getBitmask(const std::string& n);
			//Skeleton& getSkeleton(const std::string& n);
			sf::SoundBuffer& getSoundBuffer(const std::string& n);
			sf::Music& getSong(const std::string& n);
			sf::Font& getFont(const std::string& n);
			Script& getScript(const std::string& n);

		private:
			bool loadResource(const std::string& file);

			std::map<std::string, sf::Texture*> textures;
			//std::map<std::string, Bitmask*> bitmasks;
			//std::map<std::string, Skeleton> skeletons;
			std::map<std::string, sf::SoundBuffer*> soundBuffers;
			std::map<std::string, sf::Music*> music;
			std::map<std::string, sf::Font*> fonts;
			std::map<std::string, Script*> scripts;

			bool smooth;
	};
}

#endif // ASSET_MANAGER_HPP
<commit_msg>Got rid of unneeded #include<commit_after>#ifndef ASSET_MANAGER_HPP
#define ASSET_MANAGER_HPP

#include <map>
#include <array>
#include <utility>
#include <string>

#include <dirent.h>

#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Audio/SoundBuffer.hpp>
#include <SFML/Audio/Music.hpp>
#include "../Scripting/Script.hpp"

#include "../Logger/Logger.hpp"

#include "Mod.hpp"

namespace swift
{
	class Script;
	class AssetManager
	{
		public:
			AssetManager();
			~AssetManager();

			// Accepts a resource folder. This folder should contain folders containing a common group of resources.
			// This function will recursively roll through the top resource folder, grabbing all resources.
			// The function returns false if it cannot find the given folder, and returns true if otherwise.
			bool loadResourceFolder(const std::string& folder);

			bool loadMod(const Mod& mod);

			// destroys all resources the AssetManager contains
			void clean();

			// sets the AssetManager to load textures with smoothing (antialiasing)
			void setSmooth(bool s);

			sf::Texture& getTexture(const std::string& n);
			//Bitmask& getBitmask(const std::string& n);
			//Skeleton& getSkeleton(const std::string& n);
			sf::SoundBuffer& getSoundBuffer(const std::string& n);
			sf::Music& getSong(const std::string& n);
			sf::Font& getFont(const std::string& n);
			Script& getScript(const std::string& n);

		private:
			bool loadResource(const std::string& file);

			std::map<std::string, sf::Texture*> textures;
			//std::map<std::string, Bitmask*> bitmasks;
			//std::map<std::string, Skeleton> skeletons;
			std::map<std::string, sf::SoundBuffer*> soundBuffers;
			std::map<std::string, sf::Music*> music;
			std::map<std::string, sf::Font*> fonts;
			std::map<std::string, Script*> scripts;

			bool smooth;
	};
}

#endif // ASSET_MANAGER_HPP
<|endoftext|>


<commit_before>
// Projectname: amos-ss16-proj5
//
// Created on 03.06.2016.
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//

//std
#include <iostream>
#include <math.h>

#include "scenario.h"

float Scenario::ComputeDistance(Element first, Element second){

    std::vector<int> first_position = first.GetPosition();
    std::vector<int> second_position = second.GetPosition();

    return ComputePointDistance(first_position, second_position);

}

bool Scenario::DoOverlap(Element first, Element second){

    //determine whether the bounding box of the first element overlaps with the second one

   // std::cout << "SCENARIO::OVERLAP: first min, max x;y : " << first_min_x << " " << first_max_x << " " << first_min_y << " " << first_max_y <<std::endl;
   // std::cout << "SCENARIO::OVERLAP: second min, max x;y : " << second_min_x << " " << second_max_x << " " << second_min_y << " " << second_max_y <<std::endl;

    std::cout<< "In function DoOverlap: " << std::endl << "First Element positions: 1:" << first.GetMinX() << " " << first.GetMinY() << " 2: " << first.GetMaxX() << " " << first.GetMinY()
                << " 3: " << first.GetMaxX() << " " << first.GetMaxY() << " 4: " << first.GetMinX() << " " << first.GetMaxY()
                   << std::endl << "Second Element positions: 1:" <<
                      second.GetMinX() << " " << second.GetMinY() << " 2: " << second.GetMaxX() << " " << second.GetMinY()
                      << " 3: " << second.GetMaxX() << " " << second.GetMaxY() << " 4: " << second.GetMinX() << " " << second.GetMaxY() <<std::endl;

    if( (first.GetMinX() <= second.GetMinX()) || (first.GetMaxX() >= second.GetMaxX()) || ( (first.GetMinX() >= second.GetMinX()) && (first.GetMaxX() <= second.GetMaxX()) ) ){

        if( ( (second.GetMinY() >= first.GetMinY()) && (second.GetMinY() <= first.GetMaxY()) )
                ||  ( (second.GetMaxY() <= first.GetMaxY()) && (second.GetMaxY() >= first.GetMinY()) ) ){

            std::cout << "Scenario: There are overlapping elements in the frame! " << std::endl;
            return true;
        }

        return false;
    }

    return false;

}

bool Scenario::DoContain(Element big, Element small)
{
    // checks if the small one is within the big one
    return big.GetMinX()<=small.GetMinX() && big.GetMinY()<=small.GetMinY() && big.GetMaxX()>=small.GetMaxX() && big.GetMaxY()>=small.GetMaxY();
}

float Scenario::ComputeCenterDistance(Element first, Element second){

    // get the center points of the objects

    std::vector<int> first_center;
    first_center.push_back(first.GetCenterX());
    first_center.push_back(first.GetCenterY());

    std::vector<int> second_center;
    second_center.push_back(second.GetCenterX());
    second_center.push_back(second.GetCenterY());
    return ComputePointDistance(first_center, second_center);

}

float Scenario::ComputePointDistance(std::vector<int> first, std::vector<int> second){

    //compute distance with pythagorean theorem

    float first_sum = pow( (static_cast<float>(second.at(0)) - static_cast<float>(first.at(0))), 2.0);
    float second_sum = pow( (static_cast<float>(second.at(1)) - static_cast<float>(first.at(1))), 2.0);

    float distance = sqrt(first_sum + second_sum);

    return distance;

}
<commit_msg>Removed logical error from scenario analysation<commit_after>
// Projectname: amos-ss16-proj5
//
// Created on 03.06.2016.
// Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5
//
// This file is part of the AMOS Project 2016 @ FAU
// (Friedrich-Alexander University Erlangen-Nürnberg)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//

//std
#include <iostream>
#include <math.h>

#include "scenario.h"

float Scenario::ComputeDistance(Element first, Element second){

    std::vector<int> first_position = first.GetPosition();
    std::vector<int> second_position = second.GetPosition();

    return ComputePointDistance(first_position, second_position);

}

bool Scenario::DoOverlap(Element first, Element second){

    //determine whether the bounding box of the first element overlaps with the second one

   // std::cout << "SCENARIO::OVERLAP: first min, max x;y : " << first_min_x << " " << first_max_x << " " << first_min_y << " " << first_max_y <<std::endl;
   // std::cout << "SCENARIO::OVERLAP: second min, max x;y : " << second_min_x << " " << second_max_x << " " << second_min_y << " " << second_max_y <<std::endl;

    /*std::cout<< "In function DoOverlap: " << std::endl << "First Element positions: 1:" << first.GetMinX() << " " << first.GetMinY() << " 2: " << first.GetMaxX() << " " << first.GetMinY()
                << " 3: " << first.GetMaxX() << " " << first.GetMaxY() << " 4: " << first.GetMinX() << " " << first.GetMaxY()
                   << std::endl << "Second Element positions: 1:" <<
                      second.GetMinX() << " " << second.GetMinY() << " 2: " << second.GetMaxX() << " " << second.GetMinY()
                      << " 3: " << second.GetMaxX() << " " << second.GetMaxY() << " 4: " << second.GetMinX() << " " << second.GetMaxY() <<std::endl;
    */

    if( (first.GetMinX() <= second.GetMinX()) && (first.GetMaxX() >= second.GetMinX()) ||
            ( (first.GetMaxX() >= second.GetMaxX()) && (first.GetMinX() <= second.GetMaxX()) ) ){

        if( ( (second.GetMinY() >= first.GetMinY()) && (second.GetMinY() <= first.GetMaxY()) )
                ||  ( (second.GetMaxY() <= first.GetMaxY()) && (second.GetMaxY() >= first.GetMinY()) ) ){

            std::cout << "Scenario: There are overlapping elements in the frame! " << std::endl;
            return true;
        }

        return false;
    }

    return false;

}

bool Scenario::DoContain(Element big, Element small)
{
    // checks if the small one is within the big one
    return big.GetMinX()<=small.GetMinX() && big.GetMinY()<=small.GetMinY() && big.GetMaxX()>=small.GetMaxX() && big.GetMaxY()>=small.GetMaxY();
}

float Scenario::ComputeCenterDistance(Element first, Element second){

    // get the center points of the objects

    std::vector<int> first_center;
    first_center.push_back(first.GetCenterX());
    first_center.push_back(first.GetCenterY());

    std::vector<int> second_center;
    second_center.push_back(second.GetCenterX());
    second_center.push_back(second.GetCenterY());
    return ComputePointDistance(first_center, second_center);

}

float Scenario::ComputePointDistance(std::vector<int> first, std::vector<int> second){

    //compute distance with pythagorean theorem

    float first_sum = pow( (static_cast<float>(second.at(0)) - static_cast<float>(first.at(0))), 2.0);
    float second_sum = pow( (static_cast<float>(second.at(1)) - static_cast<float>(first.at(1))), 2.0);

    float distance = sqrt(first_sum + second_sum);

    return distance;

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmlbodyi.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: nn $ $Date: 2001-03-16 14:16:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_XMLBODYI_HXX
#define SC_XMLBODYI_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

class ScXMLImport;
class ScXMLChangeTrackingImportHelper;

class ScXMLBodyContext : public SvXMLImportContext
{
    rtl::OUString   sPassword;
    sal_Bool        bProtected : 1;

    ScXMLChangeTrackingImportHelper*    pChangeTrackingImportHelper;
    const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
    ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }

public:
    ScXMLBodyContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName,
                        const ::com::sun::star::uno::Reference<com::sun::star::xml::sax::XAttributeList>& xAttrList );
    virtual ~ScXMLBodyContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                                    const ::rtl::OUString& rLocalName,
                                                    const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );
    virtual void EndElement();
};

#endif

<commit_msg>INTEGRATION: CWS sab013 (1.5.388); FILE MERGED 2004/02/10 12:55:43 sab 1.5.388.1: #111055#; set defaults of calculation settings if there is no calculation settings element<commit_after>/*************************************************************************
 *
 *  $RCSfile: xmlbodyi.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: svesik $ $Date: 2004-04-20 13:57:05 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_XMLBODYI_HXX
#define SC_XMLBODYI_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

class ScXMLImport;
class ScXMLChangeTrackingImportHelper;

class ScXMLBodyContext : public SvXMLImportContext
{
    rtl::OUString   sPassword;
    sal_Bool        bProtected;
    sal_Bool        bHadCalculationSettings;

    ScXMLChangeTrackingImportHelper*    pChangeTrackingImportHelper;
    const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
    ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }

public:
    ScXMLBodyContext( ScXMLImport& rImport, USHORT nPrfx, const ::rtl::OUString& rLName,
                        const ::com::sun::star::uno::Reference<com::sun::star::xml::sax::XAttributeList>& xAttrList );
    virtual ~ScXMLBodyContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                                    const ::rtl::OUString& rLocalName,
                                                    const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );
    virtual void EndElement();
};

#endif

<|endoftext|>


<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

// 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

// C++ includes
#include <algorithm> // for std::min
#include <limits>

// Local Includes
#include "libmesh/dense_subvector.h"
#include "libmesh/dense_vector.h"
#include "libmesh/laspack_vector.h"
#include "libmesh/laspack_matrix.h"

#ifdef LIBMESH_HAVE_LASPACK

namespace libMesh
{

template <typename T>
T LaspackVector<T>::sum () const
{
  libmesh_assert (this->closed());

  T _sum = 0;

  const unsigned int n = this->size();

  for (unsigned int i=0; i!=n; ++i)
    _sum += (*this)(i);

  return _sum;
}

template <typename T>
Real LaspackVector<T>::l1_norm () const
{
  libmesh_assert (this->closed());

  return static_cast<Real>(l1Norm_V(const_cast<QVector*>(&_vec)));
}

template <typename T>
Real LaspackVector<T>::l2_norm () const
{
  libmesh_assert (this->closed());

  return static_cast<Real>(l2Norm_V(const_cast<QVector*>(&_vec)));
}

template <typename T>
Real LaspackVector<T>::linfty_norm () const
{
  libmesh_assert (this->closed());

  return static_cast<Real>(MaxNorm_V(const_cast<QVector*>(&_vec)));
}

template <typename T>
NumericVector<T>& LaspackVector<T>::operator += (const NumericVector<T>& v)
{
  libmesh_assert (this->closed());

  this->add(1., v);

  return *this;
}

template <typename T>
NumericVector<T>& LaspackVector<T>::operator -= (const NumericVector<T>& v)
{
  libmesh_assert (this->closed());

  this->add(-1., v);

  return *this;
}

template <typename T>
void LaspackVector<T>::reciprocal()
{
  const unsigned int n = this->size();

  for (unsigned int i=0; i<n; i++)
    {
      T v = (*this)(i);

      // Don't divide by zero!
      libmesh_assert_not_equal_to (v, T(0));

      this->set(i, 1. / v);
    }
}

template <typename T>
void LaspackVector<T>::add (const T v)
{
  const unsigned int n = this->size();

  for (unsigned int i=0; i<n; i++)
    this->add (i, v);

#ifndef NDEBUG
  this->_is_closed = false;
#endif
}

template <typename T>
void LaspackVector<T>::add (const NumericVector<T>& v)
{
  this->add (1., v);
}

template <typename T>
void LaspackVector<T>::add (const T a, const NumericVector<T>& v_in)
{
  // Make sure the vector passed in is really a LaspackVector
  const LaspackVector* v = libmesh_cast_ptr<const LaspackVector*>(&v_in);

#ifndef NDEBUG
  const bool was_closed = this->_is_closed;
#endif

  libmesh_assert(v);
  libmesh_assert_equal_to (this->size(), v->size());

  for (unsigned int i=0; i<v->size(); i++)
    this->add (i, a*(*v)(i));

#ifndef NDEBUG
  this->_is_closed = was_closed;
#endif
}

template <typename T>
void LaspackVector<T>::add_vector (const std::vector<T>& v,
				   const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert (!v.empty());
  libmesh_assert_equal_to (v.size(), dof_indices.size());

  for (unsigned int i=0; i<v.size(); i++)
    this->add (dof_indices[i], v[i]);
}

template <typename T>
void LaspackVector<T>::add_vector (const NumericVector<T>& V,
				   const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert_equal_to (V.size(), dof_indices.size());

  for (unsigned int i=0; i<V.size(); i++)
    this->add (dof_indices[i], V(i));
}

template <typename T>
void LaspackVector<T>::add_vector (const DenseVector<T>& V,
				   const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert_equal_to (V.size(), dof_indices.size());

  for (unsigned int i=0; i<V.size(); i++)
    this->add (dof_indices[i], V(i));
}

template <typename T>
void LaspackVector<T>::insert (const std::vector<T>& v,
			       const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert (!v.empty());
  libmesh_assert_equal_to (v.size(), dof_indices.size());

  for (unsigned int i=0; i<v.size(); i++)
    this->set (dof_indices[i], v[i]);
}

template <typename T>
void LaspackVector<T>::insert (const NumericVector<T>& V,
			       const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert_equal_to (V.size(), dof_indices.size());

  for (unsigned int i=0; i<V.size(); i++)
   this->set (dof_indices[i], V(i));
}

template <typename T>
void LaspackVector<T>::insert (const DenseVector<T>& V,
			       const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert_equal_to (V.size(), dof_indices.size());

  for (unsigned int i=0; i<V.size(); i++)
    this->set (dof_indices[i], V(i));
}

template <typename T>
void LaspackVector<T>::insert (const DenseSubVector<T>& V,
			       const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert_equal_to (V.size(), dof_indices.size());

  for (unsigned int i=0; i<V.size(); i++)
    this->set (dof_indices[i], V(i));
}

template <typename T>
void LaspackVector<T>::add_vector (const NumericVector<T> &vec_in,
				   const SparseMatrix<T> &mat_in)
{
  // Make sure the data passed in are really in Laspack types
  const LaspackVector<T>* vec = libmesh_cast_ptr<const LaspackVector<T>*>(&vec_in);
  const LaspackMatrix<T>* mat = libmesh_cast_ptr<const LaspackMatrix<T>*>(&mat_in);

  libmesh_assert(vec);
  libmesh_assert(mat);

  // += mat*vec
  AddAsgn_VV (&_vec, Mul_QV(const_cast<QMatrix*>(&mat->_QMat),
			    const_cast<QVector*>(&vec->_vec)));
}

template <typename T>
void LaspackVector<T>::add_vector_transpose (const NumericVector<T> &,
				             const SparseMatrix<T> &)
{
  libmesh_not_implemented();
}

template <typename T>
void LaspackVector<T>::scale (const T factor)
{
  libmesh_assert (this->initialized());

  Mul_SV (factor, &_vec);
}

template <typename T>
void LaspackVector<T>::abs()
{
  libmesh_assert (this->initialized());

  const unsigned int n = this->size();

  for (unsigned int i=0; i!=n; ++i)
    this->set(i,std::abs((*this)(i)));
}

template <typename T>
T LaspackVector<T>::dot (const NumericVector<T>& V) const
{
  libmesh_assert (this->initialized());

  // Make sure the NumericVector passed in is really a LaspackVector
  const LaspackVector<T>* v = libmesh_cast_ptr<const LaspackVector<T>*>(&V);
  libmesh_assert(v);

  return Mul_VV (const_cast<QVector*>(&(this->_vec)),
		 const_cast<QVector*>(&(v->_vec)));
}

template <typename T>
NumericVector<T>&
LaspackVector<T>::operator = (const T s)
{
  libmesh_assert (this->initialized());
  libmesh_assert (this->closed());

  V_SetAllCmp (&_vec, s);

  return *this;
}

template <typename T>
NumericVector<T>&
LaspackVector<T>::operator = (const NumericVector<T>& v_in)
{
  // Make sure the NumericVector passed in is really a LaspackVector
  const LaspackVector<T>* v =
    libmesh_cast_ptr<const LaspackVector<T>*>(&v_in);

  libmesh_assert(v);

  *this = *v;

  return *this;
}

template <typename T>
LaspackVector<T>&
LaspackVector<T>::operator = (const LaspackVector<T>& v)
{
  libmesh_assert (this->initialized());
  libmesh_assert (v.closed());
  libmesh_assert_equal_to (this->size(), v.size());

  if (v.size() != 0)
    Asgn_VV (const_cast<QVector*>(&_vec),
	     const_cast<QVector*>(&v._vec)
	     );

#ifndef NDEBUG
  this->_is_closed = true;
#endif

  return *this;
}

template <typename T>
NumericVector<T>&
LaspackVector<T>::operator = (const std::vector<T>& v)
{
  /**
   * Case 1:  The vector is the same size of
   * The global vector.  Only add the local components.
   */
  if (this->size() == v.size())
    for (unsigned int i=0; i<v.size(); i++)
      this->set (i, v[i]);

  else
    libmesh_error();

  return *this;
}

template <typename T>
void LaspackVector<T>::localize (NumericVector<T>& v_local_in) const
{
  // Make sure the NumericVector passed in is really a LaspackVector
  LaspackVector<T>* v_local =
    libmesh_cast_ptr<LaspackVector<T>*>(&v_local_in);

  libmesh_assert(v_local);

  *v_local = *this;
}

template <typename T>
void LaspackVector<T>::localize (NumericVector<T>& v_local_in,
				 const std::vector<unsigned int>& libmesh_dbg_var(send_list)) const
{
  // Make sure the NumericVector passed in is really a LaspackVector
  LaspackVector<T>* v_local =
    libmesh_cast_ptr<LaspackVector<T>*>(&v_local_in);

  libmesh_assert(v_local);
  libmesh_assert_less_equal (send_list.size(), v_local->size());

  *v_local = *this;
}

template <typename T>
void LaspackVector<T>::localize (const unsigned int libmesh_dbg_var(first_local_idx),
				 const unsigned int libmesh_dbg_var(last_local_idx),
				 const std::vector<unsigned int>& libmesh_dbg_var(send_list))
{
  libmesh_assert_equal_to (first_local_idx, 0);
  libmesh_assert_equal_to (last_local_idx+1, this->size());

  libmesh_assert_less_equal (send_list.size(), this->size());

#ifndef NDEBUG
  this->_is_closed = true;
#endif
}

template <typename T>
void LaspackVector<T>::localize (std::vector<T>& v_local) const

{
  v_local.resize(this->size());

  for (unsigned int i=0; i<v_local.size(); i++)
    v_local[i] = (*this)(i);
}

template <typename T>
void LaspackVector<T>::localize_to_one (std::vector<T>& v_local,
					const unsigned int libmesh_dbg_var(pid)) const
{
  libmesh_assert_equal_to (pid, 0);

  this->localize (v_local);
}

template <typename T>
void LaspackVector<T>::pointwise_mult (const NumericVector<T>& /*vec1*/,
				       const NumericVector<T>& /*vec2*/)
{
  libmesh_not_implemented();
}

template <typename T>
Real LaspackVector<T>::max() const
{
  libmesh_assert (this->initialized());
  if (!this->size())
    return -std::numeric_limits<Real>::max();

  Real max = libmesh_real((*this)(0));

  const unsigned int n = this->size();

  for (unsigned int i=1; i<n; i++)
    max = std::max (max, libmesh_real((*this)(i)));

  return max;
}

template <typename T>
Real LaspackVector<T>::min () const
{
  libmesh_assert (this->initialized());
  if (!this->size())
    return std::numeric_limits<Real>::max();

  Real min = libmesh_real((*this)(0));

  const unsigned int n = this->size();

  for (unsigned int i=1; i<n; i++)
    min = std::min (min, libmesh_real((*this)(i)));

  return min;
}

//------------------------------------------------------------------
// Explicit instantiations
template class LaspackVector<Number>;

} // namespace libMesh

#endif // #ifdef LIBMESH_HAVE_LASPACK
<commit_msg>LaspackVector::scale() bugfix<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

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

// 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

// C++ includes
#include <algorithm> // for std::min
#include <limits>

// Local Includes
#include "libmesh/dense_subvector.h"
#include "libmesh/dense_vector.h"
#include "libmesh/laspack_vector.h"
#include "libmesh/laspack_matrix.h"

#ifdef LIBMESH_HAVE_LASPACK

namespace libMesh
{

template <typename T>
T LaspackVector<T>::sum () const
{
  libmesh_assert (this->closed());

  T _sum = 0;

  const unsigned int n = this->size();

  for (unsigned int i=0; i!=n; ++i)
    _sum += (*this)(i);

  return _sum;
}

template <typename T>
Real LaspackVector<T>::l1_norm () const
{
  libmesh_assert (this->closed());

  return static_cast<Real>(l1Norm_V(const_cast<QVector*>(&_vec)));
}

template <typename T>
Real LaspackVector<T>::l2_norm () const
{
  libmesh_assert (this->closed());

  return static_cast<Real>(l2Norm_V(const_cast<QVector*>(&_vec)));
}

template <typename T>
Real LaspackVector<T>::linfty_norm () const
{
  libmesh_assert (this->closed());

  return static_cast<Real>(MaxNorm_V(const_cast<QVector*>(&_vec)));
}

template <typename T>
NumericVector<T>& LaspackVector<T>::operator += (const NumericVector<T>& v)
{
  libmesh_assert (this->closed());

  this->add(1., v);

  return *this;
}

template <typename T>
NumericVector<T>& LaspackVector<T>::operator -= (const NumericVector<T>& v)
{
  libmesh_assert (this->closed());

  this->add(-1., v);

  return *this;
}

template <typename T>
void LaspackVector<T>::reciprocal()
{
  const unsigned int n = this->size();

  for (unsigned int i=0; i<n; i++)
    {
      T v = (*this)(i);

      // Don't divide by zero!
      libmesh_assert_not_equal_to (v, T(0));

      this->set(i, 1. / v);
    }
}

template <typename T>
void LaspackVector<T>::add (const T v)
{
  const unsigned int n = this->size();

  for (unsigned int i=0; i<n; i++)
    this->add (i, v);

#ifndef NDEBUG
  this->_is_closed = false;
#endif
}

template <typename T>
void LaspackVector<T>::add (const NumericVector<T>& v)
{
  this->add (1., v);
}

template <typename T>
void LaspackVector<T>::add (const T a, const NumericVector<T>& v_in)
{
  // Make sure the vector passed in is really a LaspackVector
  const LaspackVector* v = libmesh_cast_ptr<const LaspackVector*>(&v_in);

#ifndef NDEBUG
  const bool was_closed = this->_is_closed;
#endif

  libmesh_assert(v);
  libmesh_assert_equal_to (this->size(), v->size());

  for (unsigned int i=0; i<v->size(); i++)
    this->add (i, a*(*v)(i));

#ifndef NDEBUG
  this->_is_closed = was_closed;
#endif
}

template <typename T>
void LaspackVector<T>::add_vector (const std::vector<T>& v,
				   const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert (!v.empty());
  libmesh_assert_equal_to (v.size(), dof_indices.size());

  for (unsigned int i=0; i<v.size(); i++)
    this->add (dof_indices[i], v[i]);
}

template <typename T>
void LaspackVector<T>::add_vector (const NumericVector<T>& V,
				   const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert_equal_to (V.size(), dof_indices.size());

  for (unsigned int i=0; i<V.size(); i++)
    this->add (dof_indices[i], V(i));
}

template <typename T>
void LaspackVector<T>::add_vector (const DenseVector<T>& V,
				   const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert_equal_to (V.size(), dof_indices.size());

  for (unsigned int i=0; i<V.size(); i++)
    this->add (dof_indices[i], V(i));
}

template <typename T>
void LaspackVector<T>::insert (const std::vector<T>& v,
			       const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert (!v.empty());
  libmesh_assert_equal_to (v.size(), dof_indices.size());

  for (unsigned int i=0; i<v.size(); i++)
    this->set (dof_indices[i], v[i]);
}

template <typename T>
void LaspackVector<T>::insert (const NumericVector<T>& V,
			       const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert_equal_to (V.size(), dof_indices.size());

  for (unsigned int i=0; i<V.size(); i++)
   this->set (dof_indices[i], V(i));
}

template <typename T>
void LaspackVector<T>::insert (const DenseVector<T>& V,
			       const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert_equal_to (V.size(), dof_indices.size());

  for (unsigned int i=0; i<V.size(); i++)
    this->set (dof_indices[i], V(i));
}

template <typename T>
void LaspackVector<T>::insert (const DenseSubVector<T>& V,
			       const std::vector<unsigned int>& dof_indices)
{
  libmesh_assert_equal_to (V.size(), dof_indices.size());

  for (unsigned int i=0; i<V.size(); i++)
    this->set (dof_indices[i], V(i));
}

template <typename T>
void LaspackVector<T>::add_vector (const NumericVector<T> &vec_in,
				   const SparseMatrix<T> &mat_in)
{
  // Make sure the data passed in are really in Laspack types
  const LaspackVector<T>* vec = libmesh_cast_ptr<const LaspackVector<T>*>(&vec_in);
  const LaspackMatrix<T>* mat = libmesh_cast_ptr<const LaspackMatrix<T>*>(&mat_in);

  libmesh_assert(vec);
  libmesh_assert(mat);

  // += mat*vec
  AddAsgn_VV (&_vec, Mul_QV(const_cast<QMatrix*>(&mat->_QMat),
			    const_cast<QVector*>(&vec->_vec)));
}

template <typename T>
void LaspackVector<T>::add_vector_transpose (const NumericVector<T> &,
				             const SparseMatrix<T> &)
{
  libmesh_not_implemented();
}

template <typename T>
void LaspackVector<T>::scale (const T factor)
{
  libmesh_assert (this->initialized());

  Asgn_VV(&_vec, Mul_SV (factor, &_vec));
}

template <typename T>
void LaspackVector<T>::abs()
{
  libmesh_assert (this->initialized());

  const unsigned int n = this->size();

  for (unsigned int i=0; i!=n; ++i)
    this->set(i,std::abs((*this)(i)));
}

template <typename T>
T LaspackVector<T>::dot (const NumericVector<T>& V) const
{
  libmesh_assert (this->initialized());

  // Make sure the NumericVector passed in is really a LaspackVector
  const LaspackVector<T>* v = libmesh_cast_ptr<const LaspackVector<T>*>(&V);
  libmesh_assert(v);

  return Mul_VV (const_cast<QVector*>(&(this->_vec)),
		 const_cast<QVector*>(&(v->_vec)));
}

template <typename T>
NumericVector<T>&
LaspackVector<T>::operator = (const T s)
{
  libmesh_assert (this->initialized());
  libmesh_assert (this->closed());

  V_SetAllCmp (&_vec, s);

  return *this;
}

template <typename T>
NumericVector<T>&
LaspackVector<T>::operator = (const NumericVector<T>& v_in)
{
  // Make sure the NumericVector passed in is really a LaspackVector
  const LaspackVector<T>* v =
    libmesh_cast_ptr<const LaspackVector<T>*>(&v_in);

  libmesh_assert(v);

  *this = *v;

  return *this;
}

template <typename T>
LaspackVector<T>&
LaspackVector<T>::operator = (const LaspackVector<T>& v)
{
  libmesh_assert (this->initialized());
  libmesh_assert (v.closed());
  libmesh_assert_equal_to (this->size(), v.size());

  if (v.size() != 0)
    Asgn_VV (const_cast<QVector*>(&_vec),
	     const_cast<QVector*>(&v._vec)
	     );

#ifndef NDEBUG
  this->_is_closed = true;
#endif

  return *this;
}

template <typename T>
NumericVector<T>&
LaspackVector<T>::operator = (const std::vector<T>& v)
{
  /**
   * Case 1:  The vector is the same size of
   * The global vector.  Only add the local components.
   */
  if (this->size() == v.size())
    for (unsigned int i=0; i<v.size(); i++)
      this->set (i, v[i]);

  else
    libmesh_error();

  return *this;
}

template <typename T>
void LaspackVector<T>::localize (NumericVector<T>& v_local_in) const
{
  // Make sure the NumericVector passed in is really a LaspackVector
  LaspackVector<T>* v_local =
    libmesh_cast_ptr<LaspackVector<T>*>(&v_local_in);

  libmesh_assert(v_local);

  *v_local = *this;
}

template <typename T>
void LaspackVector<T>::localize (NumericVector<T>& v_local_in,
				 const std::vector<unsigned int>& libmesh_dbg_var(send_list)) const
{
  // Make sure the NumericVector passed in is really a LaspackVector
  LaspackVector<T>* v_local =
    libmesh_cast_ptr<LaspackVector<T>*>(&v_local_in);

  libmesh_assert(v_local);
  libmesh_assert_less_equal (send_list.size(), v_local->size());

  *v_local = *this;
}

template <typename T>
void LaspackVector<T>::localize (const unsigned int libmesh_dbg_var(first_local_idx),
				 const unsigned int libmesh_dbg_var(last_local_idx),
				 const std::vector<unsigned int>& libmesh_dbg_var(send_list))
{
  libmesh_assert_equal_to (first_local_idx, 0);
  libmesh_assert_equal_to (last_local_idx+1, this->size());

  libmesh_assert_less_equal (send_list.size(), this->size());

#ifndef NDEBUG
  this->_is_closed = true;
#endif
}

template <typename T>
void LaspackVector<T>::localize (std::vector<T>& v_local) const

{
  v_local.resize(this->size());

  for (unsigned int i=0; i<v_local.size(); i++)
    v_local[i] = (*this)(i);
}

template <typename T>
void LaspackVector<T>::localize_to_one (std::vector<T>& v_local,
					const unsigned int libmesh_dbg_var(pid)) const
{
  libmesh_assert_equal_to (pid, 0);

  this->localize (v_local);
}

template <typename T>
void LaspackVector<T>::pointwise_mult (const NumericVector<T>& /*vec1*/,
				       const NumericVector<T>& /*vec2*/)
{
  libmesh_not_implemented();
}

template <typename T>
Real LaspackVector<T>::max() const
{
  libmesh_assert (this->initialized());
  if (!this->size())
    return -std::numeric_limits<Real>::max();

  Real max = libmesh_real((*this)(0));

  const unsigned int n = this->size();

  for (unsigned int i=1; i<n; i++)
    max = std::max (max, libmesh_real((*this)(i)));

  return max;
}

template <typename T>
Real LaspackVector<T>::min () const
{
  libmesh_assert (this->initialized());
  if (!this->size())
    return std::numeric_limits<Real>::max();

  Real min = libmesh_real((*this)(0));

  const unsigned int n = this->size();

  for (unsigned int i=1; i<n; i++)
    min = std::min (min, libmesh_real((*this)(i)));

  return min;
}

//------------------------------------------------------------------
// Explicit instantiations
template class LaspackVector<Number>;

} // namespace libMesh

#endif // #ifdef LIBMESH_HAVE_LASPACK
<|endoftext|>