<commit_before>
// The copyright in this software is being made available under the 2-clauses
// BSD License, included below. This software may be subject to other third
// party and contributor rights, including patent rights, and no such rights
// are granted under this license.
//  *
// Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
// Copyright (c) 2002-2014, Professor Benoit Macq
// Copyright (c) 2003-2014, Antonin Descampe
// Copyright (c) 2003-2009, Francois-Olivier Devaux
// Copyright (c) 2005, Herve Drolon, FreeImage Team
// Copyright (c) 2002-2003, Yannick Verschueren
// Copyright (c) 2001-2003, David Janssens
// Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France
// Copyright (c) 2012, CS Systemes d'Information, France
//  *
// All rights reserved.
//  *
// 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.
//  *
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `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 COPYRIGHT OWNER OR CONTRIBUTORS 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.

// copies of a few library tools

#include "convert_helper.h"

const char* opj_version(void)
{
    return "2.3.1";
}

static int are_comps_similar(opj_image_t * image)
{
    unsigned int i;
    for (i = 1; i < image->numcomps; i++) {
        if (image->comps[0].dx != image->comps[i].dx ||
                image->comps[0].dy != image->comps[i].dy ||
                (i <= 2 &&
                 (image->comps[0].prec != image->comps[i].prec ||
                  image->comps[0].sgnd != image->comps[i].sgnd))) {
            return OPJ_FALSE;
        }
    }
    return OPJ_TRUE;
}

int imagetopnm(opj_image_t * image, const char *outfile, int force_split)
{
    int *red, *green, *blue, *alpha;
    int wr, hr, max;
    int i;
    unsigned int compno, ncomp;
    int adjustR, adjustG, adjustB, adjustA;
    int fails, two, want_gray, has_alpha, triple;
    int prec, v;
    FILE *fdest = NULL;
    const char *tmp = outfile;
    char *destname;

    alpha = NULL;

    if ((prec = (int)image->comps[0].prec) > 16) {
        fprintf(stderr, "%s:%d:imagetopnm\n\tprecision %d is larger than 16"
                "\n\t: refused.\n", __FILE__, __LINE__, prec);
        return 1;
    }

    two = has_alpha = 0;
    fails = 1;
    ncomp = image->numcomps;

    while (*tmp) {
        ++tmp;
    }
    tmp -= 2;
    want_gray = (*tmp == 'g' || *tmp == 'G');
    ncomp = image->numcomps;

    if (want_gray) {
        ncomp = 1;
    }

    if ((force_split == 0) && ncomp >= 2 &&
            are_comps_similar(image)) {
        fdest = fopen(outfile, "wb");

        if (!fdest) {
            fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
            return fails;
        }
        two = (prec > 8);
        triple = (ncomp > 2);
        wr = (int)image->comps[0].w;
        hr = (int)image->comps[0].h;
        max = (1 << prec) - 1;
        has_alpha = (ncomp == 4 || ncomp == 2);

        red = image->comps[0].data;
        if (red == NULL) {
            fprintf(stderr,
                    "imagetopnm: planes[%d] == NULL.\n", 0);
            fprintf(stderr, "\tAborting\n");
            fclose(fdest);
            return fails;
        }

        if (triple) {
            green = image->comps[1].data;
            blue = image->comps[2].data;
            for (i = 1; i <= 2; i++) {
                if (image->comps[i].data == NULL) {
                    fprintf(stderr,
                            "imagetopnm: planes[%d] == NULL.\n", i);
                    fprintf(stderr, "\tAborting\n");
                    fclose(fdest);
                    return fails;
                }
            }
        } else {
            green = blue = NULL;
        }

        if (has_alpha) {
            const char *tt = (triple ? "RGB_ALPHA" : "GRAYSCALE_ALPHA");

            fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %u\n"
                    "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
                    wr, hr, ncomp, max, tt);
            alpha = image->comps[ncomp - 1].data;
            adjustA = (image->comps[ncomp - 1].sgnd ?
                       1 << (image->comps[ncomp - 1].prec - 1) : 0);
        } else {
            fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
                    opj_version(), wr, hr, max);
            adjustA = 0;
        }
        adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);

        if (triple) {
            adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
            adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
        } else {
            adjustG = adjustB = 0;
        }

        for (i = 0; i < wr * hr; ++i) {
            if (two) {
                v = *red + adjustR;
                ++red;
                if (v > 65535) {
                    v = 65535;
                } else if (v < 0) {
                    v = 0;
                }

                /* netpbm: */
                fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);

                if (triple) {
                    v = *green + adjustG;
                    ++green;
                    if (v > 65535) {
                        v = 65535;
                    } else if (v < 0) {
                        v = 0;
                    }

                    /* netpbm: */
                    fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);

                    v =  *blue + adjustB;
                    ++blue;
                    if (v > 65535) {
                        v = 65535;
                    } else if (v < 0) {
                        v = 0;
                    }

                    /* netpbm: */
                    fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);

                }/* if(triple) */

                if (has_alpha) {
                    v = *alpha + adjustA;
                    ++alpha;
                    if (v > 65535) {
                        v = 65535;
                    } else if (v < 0) {
                        v = 0;
                    }

                    /* netpbm: */
                    fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
                }
                continue;

            }   /* if(two) */

            /* prec <= 8: */
            v = *red++;
            if (v > 255) {
                v = 255;
            } else if (v < 0) {
                v = 0;
            }

            fprintf(fdest, "%c", (unsigned char)v);
            if (triple) {
                v = *green++;
                if (v > 255) {
                    v = 255;
                } else if (v < 0) {
                    v = 0;
                }

                fprintf(fdest, "%c", (unsigned char)v);
                v = *blue++;
                if (v > 255) {
                    v = 255;
                } else if (v < 0) {
                    v = 0;
                }

                fprintf(fdest, "%c", (unsigned char)v);
            }
            if (has_alpha) {
                v = *alpha++;
                if (v > 255) {
                    v = 255;
                } else if (v < 0) {
                    v = 0;
                }

                fprintf(fdest, "%c", (unsigned char)v);
            }
        }   /* for(i */

        fclose(fdest);
        return 0;
    }

    /* YUV or MONO: */

    if (image->numcomps > ncomp) {
        fprintf(stderr, "WARNING -> [PGM file] Only the first component\n");
        fprintf(stderr, "           is written to the file\n");
    }
    destname = (char*)malloc(strlen(outfile) + 8);
    if (destname == NULL) {
        fprintf(stderr, "imagetopnm: memory out\n");
        return 1;
    }
    for (compno = 0; compno < ncomp; compno++) {
        if (ncomp > 1) {
            /*sprintf(destname, "%d.%s", compno, outfile);*/
            const size_t olen = strlen(outfile);
            const size_t dotpos = olen - 4;

            strncpy(destname, outfile, dotpos);
            sprintf(destname + dotpos, "_%u.pgm", compno);
        } else {
            sprintf(destname, "%s", outfile);
        }

        fdest = fopen(destname, "wb");
        if (!fdest) {
            fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
            free(destname);
            return 1;
        }
        wr = (int)image->comps[compno].w;
        hr = (int)image->comps[compno].h;
        prec = (int)image->comps[compno].prec;
        max = (1 << prec) - 1;

        fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
                opj_version(), wr, hr, max);

        red = image->comps[compno].data;

        if (!red) {
            fclose(fdest);
            continue;
        }

        adjustR =
            (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);

        if (prec > 8) {
            for (i = 0; i < wr * hr; i++) {
                v = *red + adjustR;
                ++red;
                if (v > 65535) {
                    v = 65535;
                } else if (v < 0) {
                    v = 0;
                }

                /* netpbm: */
                fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);

                if (has_alpha) {
                    v = *alpha++;
                    if (v > 65535) {
                        v = 65535;
                    } else if (v < 0) {
                        v = 0;
                    }

                    /* netpbm: */
                    fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
                }
            }/* for(i */
        } else { /* prec <= 8 */
            for (i = 0; i < wr * hr; ++i) {
                v = *red + adjustR;
                ++red;
                if (v > 255) {
                    v = 255;
                } else if (v < 0) {
                    v = 0;
                }
                fprintf(fdest, "%c", (unsigned char)v);
            }
        }
        fclose(fdest);
    } /* for (compno */
    free(destname);

    return 0;
}/* imagetopnm() */
<commit_msg>fixed typo<commit_after>
// copies of a few library tools

#include "convert_helper.h"

const char* opj_version(void)
{
    return "2.3.1";
}

static int are_comps_similar(opj_image_t * image)
{
    unsigned int i;
    for (i = 1; i < image->numcomps; i++) {
        if (image->comps[0].dx != image->comps[i].dx ||
                image->comps[0].dy != image->comps[i].dy ||
                (i <= 2 &&
                 (image->comps[0].prec != image->comps[i].prec ||
                  image->comps[0].sgnd != image->comps[i].sgnd))) {
            return OPJ_FALSE;
        }
    }
    return OPJ_TRUE;
}

int imagetopnm(opj_image_t * image, const char *outfile, int force_split)
{
    int *red, *green, *blue, *alpha;
    int wr, hr, max;
    int i;
    unsigned int compno, ncomp;
    int adjustR, adjustG, adjustB, adjustA;
    int fails, two, want_gray, has_alpha, triple;
    int prec, v;
    FILE *fdest = NULL;
    const char *tmp = outfile;
    char *destname;

    alpha = NULL;

    if ((prec = (int)image->comps[0].prec) > 16) {
        fprintf(stderr, "%s:%d:imagetopnm\n\tprecision %d is larger than 16"
                "\n\t: refused.\n", __FILE__, __LINE__, prec);
        return 1;
    }

    two = has_alpha = 0;
    fails = 1;
    ncomp = image->numcomps;

    while (*tmp) {
        ++tmp;
    }
    tmp -= 2;
    want_gray = (*tmp == 'g' || *tmp == 'G');
    ncomp = image->numcomps;

    if (want_gray) {
        ncomp = 1;
    }

    if ((force_split == 0) && ncomp >= 2 &&
            are_comps_similar(image)) {
        fdest = fopen(outfile, "wb");

        if (!fdest) {
            fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile);
            return fails;
        }
        two = (prec > 8);
        triple = (ncomp > 2);
        wr = (int)image->comps[0].w;
        hr = (int)image->comps[0].h;
        max = (1 << prec) - 1;
        has_alpha = (ncomp == 4 || ncomp == 2);

        red = image->comps[0].data;
        if (red == NULL) {
            fprintf(stderr,
                    "imagetopnm: planes[%d] == NULL.\n", 0);
            fprintf(stderr, "\tAborting\n");
            fclose(fdest);
            return fails;
        }

        if (triple) {
            green = image->comps[1].data;
            blue = image->comps[2].data;
            for (i = 1; i <= 2; i++) {
                if (image->comps[i].data == NULL) {
                    fprintf(stderr,
                            "imagetopnm: planes[%d] == NULL.\n", i);
                    fprintf(stderr, "\tAborting\n");
                    fclose(fdest);
                    return fails;
                }
            }
        } else {
            green = blue = NULL;
        }

        if (has_alpha) {
            const char *tt = (triple ? "RGB_ALPHA" : "GRAYSCALE_ALPHA");

            fprintf(fdest, "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %u\n"
                    "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n", opj_version(),
                    wr, hr, ncomp, max, tt);
            alpha = image->comps[ncomp - 1].data;
            adjustA = (image->comps[ncomp - 1].sgnd ?
                       1 << (image->comps[ncomp - 1].prec - 1) : 0);
        } else {
            fprintf(fdest, "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
                    opj_version(), wr, hr, max);
            adjustA = 0;
        }
        adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);

        if (triple) {
            adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
            adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
        } else {
            adjustG = adjustB = 0;
        }

        for (i = 0; i < wr * hr; ++i) {
            if (two) {
                v = *red + adjustR;
                ++red;
                if (v > 65535) {
                    v = 65535;
                } else if (v < 0) {
                    v = 0;
                }

                /* netpbm: */
                fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);

                if (triple) {
                    v = *green + adjustG;
                    ++green;
                    if (v > 65535) {
                        v = 65535;
                    } else if (v < 0) {
                        v = 0;
                    }

                    /* netpbm: */
                    fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);

                    v =  *blue + adjustB;
                    ++blue;
                    if (v > 65535) {
                        v = 65535;
                    } else if (v < 0) {
                        v = 0;
                    }

                    /* netpbm: */
                    fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);

                }/* if(triple) */

                if (has_alpha) {
                    v = *alpha + adjustA;
                    ++alpha;
                    if (v > 65535) {
                        v = 65535;
                    } else if (v < 0) {
                        v = 0;
                    }

                    /* netpbm: */
                    fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
                }
                continue;

            }   /* if(two) */

            /* prec <= 8: */
            v = *red++;
            if (v > 255) {
                v = 255;
            } else if (v < 0) {
                v = 0;
            }

            fprintf(fdest, "%c", (unsigned char)v);
            if (triple) {
                v = *green++;
                if (v > 255) {
                    v = 255;
                } else if (v < 0) {
                    v = 0;
                }

                fprintf(fdest, "%c", (unsigned char)v);
                v = *blue++;
                if (v > 255) {
                    v = 255;
                } else if (v < 0) {
                    v = 0;
                }

                fprintf(fdest, "%c", (unsigned char)v);
            }
            if (has_alpha) {
                v = *alpha++;
                if (v > 255) {
                    v = 255;
                } else if (v < 0) {
                    v = 0;
                }

                fprintf(fdest, "%c", (unsigned char)v);
            }
        }   /* for(i */

        fclose(fdest);
        return 0;
    }

    /* YUV or MONO: */

    if (image->numcomps > ncomp) {
        fprintf(stderr, "WARNING -> [PGM file] Only the first component\n");
        fprintf(stderr, "           is written to the file\n");
    }
    destname = (char*)malloc(strlen(outfile) + 8);
    if (destname == NULL) {
        fprintf(stderr, "imagetopnm: memory out\n");
        return 1;
    }
    for (compno = 0; compno < ncomp; compno++) {
        if (ncomp > 1) {
            /*sprintf(destname, "%d.%s", compno, outfile);*/
            const size_t olen = strlen(outfile);
            const size_t dotpos = olen - 4;

            strncpy(destname, outfile, dotpos);
            sprintf(destname + dotpos, "_%u.pgm", compno);
        } else {
            sprintf(destname, "%s", outfile);
        }

        fdest = fopen(destname, "wb");
        if (!fdest) {
            fprintf(stderr, "ERROR -> failed to open %s for writing\n", destname);
            free(destname);
            return 1;
        }
        wr = (int)image->comps[compno].w;
        hr = (int)image->comps[compno].h;
        prec = (int)image->comps[compno].prec;
        max = (1 << prec) - 1;

        fprintf(fdest, "P5\n#OpenJPEG-%s\n%d %d\n%d\n",
                opj_version(), wr, hr, max);

        red = image->comps[compno].data;

        if (!red) {
            fclose(fdest);
            continue;
        }

        adjustR =
            (image->comps[compno].sgnd ? 1 << (image->comps[compno].prec - 1) : 0);

        if (prec > 8) {
            for (i = 0; i < wr * hr; i++) {
                v = *red + adjustR;
                ++red;
                if (v > 65535) {
                    v = 65535;
                } else if (v < 0) {
                    v = 0;
                }

                /* netpbm: */
                fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);

                if (has_alpha) {
                    v = *alpha++;
                    if (v > 65535) {
                        v = 65535;
                    } else if (v < 0) {
                        v = 0;
                    }

                    /* netpbm: */
                    fprintf(fdest, "%c%c", (unsigned char)(v >> 8), (unsigned char)v);
                }
            }/* for(i */
        } else { /* prec <= 8 */
            for (i = 0; i < wr * hr; ++i) {
                v = *red + adjustR;
                ++red;
                if (v > 255) {
                    v = 255;
                } else if (v < 0) {
                    v = 0;
                }
                fprintf(fdest, "%c", (unsigned char)v);
            }
        }
        fclose(fdest);
    } /* for (compno */
    free(destname);

    return 0;
}/* imagetopnm() */
<|endoftext|>


<commit_before><commit_msg>Mark URLRequestTestFTP.FTPGetTestAnonymous as flaky.<commit_after><|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2010 Artem Pavlenko
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

// mapnik
#include <mapnik/svg/marker_cache.hpp>
#include <mapnik/svg/svg_parser.hpp>

// boost
#include <boost/assert.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>

namespace mapnik
{

boost::unordered_map<std::string, path_ptr> marker_cache::cache_;

bool marker_cache::insert (std::string const& uri, path_ptr path)
{
#ifdef MAPNIK_THREADSAFE
    mutex::scoped_lock lock(mutex_);
#endif
    return cache_.insert(std::make_pair(uri,path)).second;
}

boost::optional<path_ptr> marker_cache::find(std::string const& uri, bool update_cache)
{
#ifdef MAPNIK_THREADSAFE
    mutex::scoped_lock lock(mutex_);
#endif
    typedef boost::unordered_map<std::string, path_ptr>::const_iterator iterator_type;
    boost::optional<path_ptr> result;
    iterator_type itr = cache_.find(uri);
    if (itr != cache_.end())
    {
	result.reset(itr->second);
	return result;
    }

    // we can't find marker in cache, lets try to load it from filesystem
    boost::filesystem::path path(uri);
    if (exists(path))
    {
	try
	{
	    mapnik::path_ptr marker(new agg::svg::path_renderer);
	    svg::svg_parser p(*marker);
	    p.parse(uri);
	    marker->arrange_orientations();
	    double lox,loy,hix,hiy;
	    marker->bounding_rect(&lox, &loy, &hix, &hiy); //TODO: store bbox!
	    if (update_cache)
	    {
		cache_.insert(std::make_pair(uri,marker));
	    }
	}
	catch (...)
	{
	    std::cerr << "Exception caught while loading SVG: " << uri << std::endl;
	}
    }
    else
    {
        std::cerr << "### WARNING SVG does not exist: " << uri << std::endl;
    }
    return result;
}

#ifdef MAPNIK_THREADSAFE
   boost::mutex marker_cache::mutex_;
#endif

}
<commit_msg>make sure to return marker from cache, as noticed by Herm and mentioned in #553<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2010 Artem Pavlenko
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

// mapnik
#include <mapnik/svg/marker_cache.hpp>
#include <mapnik/svg/svg_parser.hpp>

// boost
#include <boost/assert.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>

namespace mapnik
{

boost::unordered_map<std::string, path_ptr> marker_cache::cache_;

bool marker_cache::insert (std::string const& uri, path_ptr path)
{
#ifdef MAPNIK_THREADSAFE
    mutex::scoped_lock lock(mutex_);
#endif
    return cache_.insert(std::make_pair(uri,path)).second;
}

boost::optional<path_ptr> marker_cache::find(std::string const& uri, bool update_cache)
{
#ifdef MAPNIK_THREADSAFE
    mutex::scoped_lock lock(mutex_);
#endif
    typedef boost::unordered_map<std::string, path_ptr>::const_iterator iterator_type;
    boost::optional<path_ptr> result;
    iterator_type itr = cache_.find(uri);
    if (itr != cache_.end())
    {
	result.reset(itr->second);
	return result;
    }

    // we can't find marker in cache, lets try to load it from filesystem
    boost::filesystem::path path(uri);
    if (exists(path))
    {
	try
	{
	    mapnik::path_ptr marker(new agg::svg::path_renderer);
	    svg::svg_parser p(*marker);
	    p.parse(uri);
	    marker->arrange_orientations();
	    double lox,loy,hix,hiy;
	    marker->bounding_rect(&lox, &loy, &hix, &hiy); //TODO: store bbox!
	    if (update_cache)
	    {
		cache_.insert(std::make_pair(uri,marker));
            }
            return marker;
	}
	catch (...)
	{
	    std::cerr << "Exception caught while loading SVG: " << uri << std::endl;
	}
    }
    else
    {
        std::cerr << "### WARNING SVG does not exist: " << uri << std::endl;
    }
    return result;
}

#ifdef MAPNIK_THREADSAFE
   boost::mutex marker_cache::mutex_;
#endif

}
<|endoftext|>


<commit_before>#ifndef HEADER_GUARD_LEVEL_H
#define HEADER_GUARD_LEVEL_H

#include <vector>

#include "sdl/texture.hh"

#include "tile.hh"
#include "entity.hh"

namespace czipperz {
struct level {
    sdl::texture textures[4];
    std::vector<czipperz::platform> platforms;
    std::vector<czipperz::door> doors;

    level(sdl::texture front, sdl::texture right, sdl::texture back,
          sdl::texture left)
        : textures({std::move(front), std::move(right),
                   std::move(back), std::move(left)}) {}
};
}

#endif
<commit_msg>Stop using GNU array extension<commit_after>#ifndef HEADER_GUARD_LEVEL_H
#define HEADER_GUARD_LEVEL_H

#include <vector>

#include "sdl/texture.hh"

#include "tile.hh"
#include "entity.hh"

namespace czipperz {
struct level {
    sdl::texture textures[4];
    std::vector<czipperz::platform> platforms;
    std::vector<czipperz::door> doors;

    level(sdl::texture front, sdl::texture right, sdl::texture back,
          sdl::texture left)
        : textures{std::move(front), std::move(right),
                   std::move(back), std::move(left)} {}
};
}

#endif
<|endoftext|>


<commit_before>#include "cpp_std_11.h"

#include <SFML/Graphics.hpp>
#include <iostream>
#include "GameScreenState.hpp"
#include "MenuScreenState.hpp"
#include "ScreenStack.hpp"

int main(int argc, char** argv)
{
	sf::RenderWindow window;
	sf::String window_title = "Bamboo Painter";
	sf::VideoMode window_mode (800,600);

	window.create(window_mode, window_title);
	window.setFramerateLimit(60);

	ScreenStack screenStack;
	screenStack.registerState(ScreenState::Menu, make_unique<MenuScreenState>());
//	screenStack.registerState(ScreenState::Game, make_unique<GameScreenState>());

//	screenStack.pushState(ScreenState::Game);
	screenStack.pushState(ScreenState::Menu);
	sf::Event event;
    sf::Clock clock;

	while (window.isOpen()) {
	    while (window.pollEvent(event)) {
	        if (event.type == sf::Event::Closed)
                window.close();
            else
				//menu_screen_state.event(window, event);
                screenStack.onEvent(window, event);
	    }

	    window.clear();
	    screenStack.onDraw(window);
		//menu_screen_state.render(window);
	    window.display();
		//screenStack.window_update(window);
		screenStack.onUpdate(clock.getElapsedTime());
		//menu_screen_state.update(clock.getElapsedTime());
        clock.restart();

	}
}
<commit_msg>Fix window title<commit_after>#include "cpp_std_11.h"

#include <SFML/Graphics.hpp>
#include <iostream>
#include "GameScreenState.hpp"
#include "MenuScreenState.hpp"
#include "ScreenStack.hpp"

int main(int argc, char** argv)
{
	sf::RenderWindow window;
	sf::String window_title = "Ludum Dare 35";
	sf::VideoMode window_mode (800,600);

	window.create(window_mode, window_title);
	window.setFramerateLimit(60);

	ScreenStack screenStack;
	screenStack.registerState(ScreenState::Menu, make_unique<MenuScreenState>());
//	screenStack.registerState(ScreenState::Game, make_unique<GameScreenState>());

//	screenStack.pushState(ScreenState::Game);
	screenStack.pushState(ScreenState::Menu);
	sf::Event event;
    sf::Clock clock;

	while (window.isOpen()) {
	    while (window.pollEvent(event)) {
	        if (event.type == sf::Event::Closed)
                window.close();
            else
				//menu_screen_state.event(window, event);
                screenStack.onEvent(window, event);
	    }

	    window.clear();
	    screenStack.onDraw(window);
		//menu_screen_state.render(window);
	    window.display();
		//screenStack.window_update(window);
		screenStack.onUpdate(clock.getElapsedTime());
		//menu_screen_state.update(clock.getElapsedTime());
        clock.restart();

	}
}
<|endoftext|>


<commit_before>#include "includes.hpp"
#include "interface.hpp"

namespace ProjectInfo {
const char* const projectName = "Kiwano";
const char* const versionString = "0.1";
const int versionNumber = 0x10000;
}

class MainWindow : public DocumentWindow {
	user_interface itf;
	base::lisp gl;
	JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow);

public:
	MainWindow(String name) : DocumentWindow(name, Colours::lightgrey, DocumentWindow::allButtons),
							  itf(gl) {
		//setUsingNativeTitleBar(true); // TODO: fix blink on startup
		setContentOwned(&itf, false);
		setSize(800, 600);
		setTopLeftPosition(200, 200);
		setResizable(true, true);
		setVisible(true);

		// initialize playback
		playback::init();

		// initialize GLISP
		using namespace std::placeholders;
		gl.init();

		// GUI
		gl.addProcedure("create-playlist", std::bind(&user_interface::create_playlist, &itf, _1, _2));
		gl.addProcedure("create-layout", std::bind(&user_interface::create_layout, &itf, _1, _2));
		gl.addProcedure("create-interpreter", std::bind(&user_interface::create_interpreter, &itf, _1, _2));
		gl.addProcedure("create-tabs", std::bind(&user_interface::create_tabs, &itf, _1, _2));
		gl.addProcedure("create-audio-settings", std::bind(&user_interface::create_audio_settings, &itf, _1, _2));
		gl.addProcedure("create-text-button", std::bind(&user_interface::create_text_button, &itf, _1, _2));
		gl.addProcedure("layout-add-component", std::bind(&user_interface::layout_add_component, &itf, _1, _2));
		gl.addProcedure("layout-remove-component", std::bind(&user_interface::layout_remove_component, &itf, _1, _2));
		gl.addProcedure("layout-add-splitter", std::bind(&user_interface::layout_add_splitter, &itf, _1, _2));
		gl.addProcedure("layout-get-splitter-count", std::bind(&user_interface::layout_get_splitters_count, &itf, _1, _2));
		gl.addProcedure("layout-remove-splitter", std::bind(&user_interface::layout_remove_splitter, &itf, _1, _2));
		gl.addProcedure("tabs-add-component", std::bind(&user_interface::tabs_add_component, &itf, _1, _2));
		gl.addProcedure("set-main-component", std::bind(&user_interface::set_main_component, &itf, _1, _2));
		gl.addProcedure("refresh-interface", std::bind(&user_interface::refresh_interface, &itf, _1, _2));

		// GUI event binding
		gl.addProcedure("bind-mouse-click", std::bind(&user_interface::bind_mouse_listener<mouseUpListener>, &itf, _1, _2));
		gl.addProcedure("bind-mouse-double-click", std::bind(&user_interface::bind_mouse_listener<mouseDoubleClickListener>, &itf, _1, _2));
		gl.addProcedure("unbind-mouse", std::bind(&user_interface::unbind_mouse_listener, &itf, _1, _2));

		gl.addProcedure("playlist-get-selected", std::bind(&user_interface::playlist_get_selected, &itf, _1, _2));

		// playback API
		gl.addProcedure("playback-set-file", std::bind(&playback::set_file, std::ref(gl), _1, _2));
		gl.addProcedure("playback-unload-file", std::bind(&playback::unload_file, std::ref(gl), _1, _2));
		gl.addProcedure("playback-start", std::bind(&playback::start, std::ref(gl), _1, _2));
		gl.addProcedure("playback-stop", std::bind(&playback::stop, std::ref(gl), _1, _2));
		gl.addProcedure("playback-seek", std::bind(&playback::seek, std::ref(gl), _1, _2));
		gl.addProcedure("playback-length", std::bind(&playback::length, std::ref(gl), _1, _2));
		gl.addProcedure("playback-get-pos", std::bind(&playback::get_pos, std::ref(gl), _1, _2));
		gl.addProcedure("playback-is-playing", std::bind(&playback::is_playing, std::ref(gl), _1, _2));

		// test
		gl.eval("(defun on-playlist-click (item-str) (playback-set-file item-str) (playback-start) )");

		// prepare settings folder
		base::string appPath = base::fs::getUserDirectory() + "/.kiwano";
		base::fs::createFolderTree(appPath);
		base::fs::open(appPath);

		// load ELISP config file
		gl.eval(base::toStr(base::fs::load("init.lisp")));
	}

	void closeButtonPressed() override {
		base::fs::close();
		gl.close();
		playback::shutdown();
		JUCEApplication::getInstance()->systemRequestedQuit();
	}
};

class KiwanoApplication : public JUCEApplication {
    ScopedPointer<MainWindow> mainWindow;

public:
    KiwanoApplication() {}

    const String getApplicationName() override { return ProjectInfo::projectName; }
    const String getApplicationVersion() override { return ProjectInfo::versionString; }
    bool moreThanOneInstanceAllowed() override { return false; }

    void initialise(const String& commandLine) override {
        mainWindow = new MainWindow(getApplicationName());
    }

    void shutdown() override {
        mainWindow = nullptr;
    }

    void systemRequestedQuit() override {
        quit();
    }

    void anotherInstanceStarted (const String& commandLine) override {
    }
};

START_JUCE_APPLICATION(KiwanoApplication);

// TODO: load config from file
<commit_msg>+ TODOs<commit_after>#include "includes.hpp"
#include "interface.hpp"

namespace ProjectInfo {
const char* const projectName = "Kiwano";
const char* const versionString = "0.1";
const int versionNumber = 0x10000;
}

class MainWindow : public DocumentWindow {
	user_interface itf;
	base::lisp gl;
	JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow);

public:
	MainWindow(String name) : DocumentWindow(name, Colours::lightgrey, DocumentWindow::allButtons),
							  itf(gl) {
		//setUsingNativeTitleBar(true); // TODO: fix blink on startup
		setContentOwned(&itf, false);
		setSize(800, 600);
		setTopLeftPosition(200, 200);
		setResizable(true, true);
		setVisible(true);

		// initialize playback
		playback::init();

		// initialize GLISP
		using namespace std::placeholders;
		gl.init();

		// GUI
		gl.addProcedure("create-playlist", std::bind(&user_interface::create_playlist, &itf, _1, _2));
		gl.addProcedure("create-layout", std::bind(&user_interface::create_layout, &itf, _1, _2));
		gl.addProcedure("create-interpreter", std::bind(&user_interface::create_interpreter, &itf, _1, _2));
		gl.addProcedure("create-tabs", std::bind(&user_interface::create_tabs, &itf, _1, _2));
		gl.addProcedure("create-audio-settings", std::bind(&user_interface::create_audio_settings, &itf, _1, _2));
		gl.addProcedure("create-text-button", std::bind(&user_interface::create_text_button, &itf, _1, _2));
		gl.addProcedure("layout-add-component", std::bind(&user_interface::layout_add_component, &itf, _1, _2));
		gl.addProcedure("layout-remove-component", std::bind(&user_interface::layout_remove_component, &itf, _1, _2));
		gl.addProcedure("layout-add-splitter", std::bind(&user_interface::layout_add_splitter, &itf, _1, _2));
		gl.addProcedure("layout-get-splitter-count", std::bind(&user_interface::layout_get_splitters_count, &itf, _1, _2));
		gl.addProcedure("layout-remove-splitter", std::bind(&user_interface::layout_remove_splitter, &itf, _1, _2));
		gl.addProcedure("tabs-add-component", std::bind(&user_interface::tabs_add_component, &itf, _1, _2));
		gl.addProcedure("set-main-component", std::bind(&user_interface::set_main_component, &itf, _1, _2));
		gl.addProcedure("refresh-interface", std::bind(&user_interface::refresh_interface, &itf, _1, _2));

		// GUI event binding
		gl.addProcedure("bind-mouse-click", std::bind(&user_interface::bind_mouse_listener<mouseUpListener>, &itf, _1, _2));
		gl.addProcedure("bind-mouse-double-click", std::bind(&user_interface::bind_mouse_listener<mouseDoubleClickListener>, &itf, _1, _2));
		gl.addProcedure("unbind-mouse", std::bind(&user_interface::unbind_mouse_listener, &itf, _1, _2));

		gl.addProcedure("playlist-get-selected", std::bind(&user_interface::playlist_get_selected, &itf, _1, _2));

		// playback API
		gl.addProcedure("playback-set-file", std::bind(&playback::set_file, std::ref(gl), _1, _2));
		gl.addProcedure("playback-unload-file", std::bind(&playback::unload_file, std::ref(gl), _1, _2));
		gl.addProcedure("playback-start", std::bind(&playback::start, std::ref(gl), _1, _2));
		gl.addProcedure("playback-stop", std::bind(&playback::stop, std::ref(gl), _1, _2));
		gl.addProcedure("playback-seek", std::bind(&playback::seek, std::ref(gl), _1, _2));
		gl.addProcedure("playback-length", std::bind(&playback::length, std::ref(gl), _1, _2));
		gl.addProcedure("playback-get-pos", std::bind(&playback::get_pos, std::ref(gl), _1, _2));
		gl.addProcedure("playback-is-playing", std::bind(&playback::is_playing, std::ref(gl), _1, _2));

		// test
		gl.eval("(defun on-playlist-click (item-str) (playback-set-file item-str) (playback-start) )");

		// prepare settings folder
		base::string appPath = base::fs::getUserDirectory() + "/.kiwano";
		base::fs::createFolderTree(appPath);
		base::fs::open(appPath);

		// load ELISP config file
		gl.eval(base::toStr(base::fs::load("init.lisp")));
	}

	void closeButtonPressed() override {
		base::fs::close();
		gl.close();
		playback::shutdown();
		JUCEApplication::getInstance()->systemRequestedQuit();
	}
};

class KiwanoApplication : public JUCEApplication {
    ScopedPointer<MainWindow> mainWindow;

public:
    KiwanoApplication() {}

    const String getApplicationName() override { return ProjectInfo::projectName; }
    const String getApplicationVersion() override { return ProjectInfo::versionString; }
    bool moreThanOneInstanceAllowed() override { return false; }

    void initialise(const String& commandLine) override {
        mainWindow = new MainWindow(getApplicationName());
    }

    void shutdown() override {
        mainWindow = nullptr;
    }

    void systemRequestedQuit() override {
        quit();
    }

    void anotherInstanceStarted (const String& commandLine) override {
    }
};

START_JUCE_APPLICATION(KiwanoApplication);

// TODO: load default config
<|endoftext|>


<commit_before>//Standard libraries
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <vector>

//Third parties libraries

//Local Includes
#include "macro.h"
#include "io_utils.h"
#include "sequential_trim_simulator.h"
#include "queued_trim_simulator.h"
#include "command.h"
#include "trim_command.h"
#include "io_command.h"

std::string version="0.0.1";

void printHelp()	{
	std::clog<< "\nNAME\n"
				"\tTS - Trim_Simulator-"<<version<<"\n\n"
				"SYNOPSIS\n"
				"\tTS [OPTION]... DIRECTORY\n"
				"\n"
				"DESCRIPTION\n"
				"\tLinux Trim Simulator\n\n"
				"\t-help, --help\n\t\tTrim Simulator Description\n\n"
				;
}//end printHelp

std::vector<Command*> procedurePraser(std::string procedureFilePath)	{
	// vector of command based on the input file
	std::vector<Command*> procedure;
	// open the input file
	std::ifstream commandFilePtr(procedureFilePath.c_str(), std::ifstream::in);
	// if open successfully
	if(commandFilePtr)	{
		double issueTime;
		char commandType;
		// read everyline
		while(commandFilePtr >> issueTime >> commandType)	{
			// create command based on command type
			if(commandType == 'T')	{
				procedure.push_back(new Trim_Command(issueTime));
			}
			else	{
				procedure.push_back(new IO_Command(issueTime, commandType));
			}
		}
	}

	return procedure;
}

int main(int argc, char** argv)	{
	// check if there are more than 2 arguements
	if(argc<2)	{
		usage_message("Trim_Simulator-"+version+"[options] <Simulation Mode>\n");
	}

	//simulation mode variables
	bool sequential_trim=false;
	bool queued_trim=false;
	bool new_trim=false;

	double readProcessTime = CLOCK_SPEED * 25.0,
		   writeProcessTime = CLOCK_SPEED * 200.0,
		   trimProcessTime = CLOCK_SPEED * 2000.0;

	std::string procedureFilePath = "";

	/*Parse the command line and load all input files*/
	for(int i=1;i<argc;i++)	{
		if(argv[i][0]=='-')	{
			if((strcasecmp(argv[i]+1,"help")==0)||(strcasecmp(argv[i]+1,"h")==0)||(strcasecmp(argv[i]+1,"-help")==0))	{
				printHelp();
				return 0;
			}//end if strcasecmp
			else if((strcasecmp(argv[i]+1,"s")==0)|| (strcasecmp(argv[i]+1,"-sequential")==0))	{
				sequential_trim=true;
			}//end else if
			else if((strcasecmp(argv[i]+1,"q")==0)|| (strcasecmp(argv[i]+1,"-queued")==0))	{
				queued_trim=true;
			}//end else if
			else if((strcasecmp(argv[i]+1,"n")==0)|| (strcasecmp(argv[i]+1,"-new_trim")==0))	{
				new_trim=true;
			}//end else if
			else if((strcasecmp(argv[i]+1,"p")==0)|| (strcasecmp(argv[i]+1,"-procedure")==0))	{
				++i;
				if(i<argc)	{
					procedureFilePath = argv[i];
				}//end if
				else
					std::cerr<<"Dangling -p or --procedure flag on command line\n";
			}
		}
	}//end for

	//simulation process code
	std::vector<Command*> commands;

	if(procedureFilePath != "")	{
		//prase all the procedure line
		commands = procedurePraser(procedureFilePath);

		if(sequential_trim)	{
			Sequential_Trim_Simulator* sts = new Sequential_Trim_Simulator(commands);
			sts->startSimulation(readProcessTime, writeProcessTime, trimProcessTime);
		}

		if(queued_trim)	{
			Queued_Trim_Simulator* qts = new Queued_Trim_Simulator(commands);
			qts->startSimulation(readProcessTime, writeProcessTime, trimProcessTime);
		}

		if(new_trim)	{

		}
	}

	for(int i = 0; i < commands.size(); i++)	{
		delete commands[i];
	}
	commands.clear();

	return 0;
}

<commit_msg>new praser<commit_after>//Standard libraries
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <vector>

//Third parties libraries

//Local Includes
#include "macro.h"
#include "io_utils.h"
#include "sequential_trim_simulator.h"
#include "queued_trim_simulator.h"
#include "command.h"
#include "trim_command.h"
#include "io_command.h"

std::string version="0.0.1";

void printHelp()	{
	std::clog<< "\nNAME\n"
				"\tTS - Trim_Simulator-"<<version<<"\n\n"
				"SYNOPSIS\n"
				"\tTS [OPTION]... DIRECTORY\n"
				"\n"
				"DESCRIPTION\n"
				"\tLinux Trim Simulator\n\n"
				"\t-help, --help\n\t\tTrim Simulator Description\n\n"
				;
}//end printHelp

void praseStatistic(std::string statisticFilePath, double& readProcessTime,
					double& writeProcessTime, double& trimProcessTime)	{
	// open the input file
	std::ifstream filePtr(statisticFilePath.c_str(), std::ifstream::in);
	if(filePtr)	{
		char commandType;
		double time;
		while(filePtr >> commandType >> time)	{
			if(commandType == "T")
				trimProcessTime = time;
			else if(commandType == "W")
				writeProcessTime = time;
			else if(commandType == "R")
				readProcessTime = time;
		}
	}
}

void procedurePraser(std::string procedureFilePath, std::vector<Command*>& procedure)	{
	// open the input file
	std::ifstream filePtr(procedureFilePath.c_str(), std::ifstream::in);
	// if open successfully
	if(filePtr)	{
		double issueTime;
		char commandType;
		// read everyline
		while(filePtr >> issueTime >> commandType)	{
			// create command based on command type
			if(commandType == 'T')	{
				procedure.push_back(new Trim_Command(issueTime));
			}
			else	{
				procedure.push_back(new IO_Command(issueTime, commandType));
			}
		}
	}
}

int main(int argc, char** argv)	{
	// check if there are more than 2 arguements
	if(argc<2)	{
		usage_message("Trim_Simulator-"+version+"[options] <Simulation Mode>\n");
	}

	//input file path variables
	std::string statisticFilePath = "";
	std::string procedureFilePath = "";

	// simulation statistic variables
	double readProcessTime = -1;
	double writeProcessTime = -1;
	double trimProcessTime = -1;

	//simulation variables
	int concurrent_command = 1;
	bool sequential_trim=false;
	bool queued_trim=false;
	bool new_trim=false;

	/*Parse the command line and load all input files*/
	for(int i=1;i<argc;i++)	{
		if(argv[i][0]=='-')	{
			if((strcasecmp(argv[i]+1,"help")==0)||(strcasecmp(argv[i]+1,"h")==0)||(strcasecmp(argv[i]+1,"-help")==0))	{
				printHelp();
				return 0;
			}//end if strcasecmp
			else if((strcasecmp(argv[i]+1,"s")==0)|| (strcasecmp(argv[i]+1,"-statistic")==0))	{
				++i;
				if(i<argc)	{
					statisticFilePath = argv[i];
				}//end if
				else
					std::cerr<<"Dangling -s or --statistic flag on command line\n";
			}
			else if((strcasecmp(argv[i]+1,"p")==0)|| (strcasecmp(argv[i]+1,"-procedure")==0))	{
				++i;
				if(i<argc)	{
					procedureFilePath = argv[i];
				}//end if
				else
					std::cerr<<"Dangling -p or --procedure flag on command line\n";
			}
			else if((strcasecmp(argv[i]+1,"c")==0)|| (strcasecmp(argv[i]+1,"-concurrent")==0))	{
				++i;
				if(i<argc)	{
					concurrent_command = argv[i];
				}//end if
				else
					std::cerr<<"Dangling -c or --concurrent flag on command line\n";
			}

			else if((strcasecmp(argv[i]+1,"sq")==0)|| (strcasecmp(argv[i]+1,"-sequential")==0))	{
				sequential_trim=true;
			}//end else if
			else if((strcasecmp(argv[i]+1,"q")==0)|| (strcasecmp(argv[i]+1,"-queued")==0))	{
				queued_trim=true;
			}//end else if
			else if((strcasecmp(argv[i]+1,"n")==0)|| (strcasecmp(argv[i]+1,"-new_trim")==0))	{
				new_trim=true;
			}//end else if
		}
	}//end for

	if(statisticFilePath == "" || procedureFilePath == "")	{
		printHelp();
		return -1;
	}

	//simulation process code
	std::vector<Command*> commands;
	praseStatistic(statisticFilePath, readProcessTime, writeProcessTime, trimProcessTime);
	procedurePraser(procedureFilePath, commands);
	if(readProcessTime == -1 || writeProcessTime == -1 || trimProcessTime == -1 || commands.size() < 1)	{
		printHelp();
		return -1;
	}

	if(sequential_trim)	{
		Sequential_Trim_Simulator* sts = new Sequential_Trim_Simulator(commands);
		sts->startSimulation(readProcessTime, writeProcessTime, trimProcessTime);
	}

	if(queued_trim)	{
		Queued_Trim_Simulator* qts = new Queued_Trim_Simulator(commands);
		qts->startSimulation(readProcessTime, writeProcessTime, trimProcessTime);
	}

	if(new_trim)	{

	}

	/*
		clean up
	*/
	// delete all command pointers
	for(int i = 0; i < commands.size(); i++)	{
		delete commands[i];
	}
	commands.clear();

	return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <memory>
#include <vector>

/*  Neste problema, pede-se para armazenar, gerenciar e buscar por
    indivíduos definidos por
        um identificador único (inteiro)
        Primeiro nome
        último nome,
        data de nascimento
        telefone.
*/
struct Person
{
    Person( int _id = 0,
            const std::string &_first_name = "",
            const std::string &_last_name = "",
            const std::string &_birthday = "",
            const std::string &_phone = ""):
        id(_id),
        first_name(_first_name),
        last_name(_last_name),
        birthday(_birthday),
        phone(_phone)
        {
        }
    int id;
    std::string first_name;
    std::string last_name;
    std::string birthday;
    std::string phone;
    std::shared_ptr<Person> collision;
};

typedef std::shared_ptr<Person> Person_ptr;
typedef std::vector<Person_ptr> HashTable;

class PersonManager
{
    public:
        PersonManager(void):
            max_elements(503),
            id_table(max_elements),
            fn_table(max_elements),
            ln_table(max_elements),
            birth_table(max_elements),
            phone_table(max_elements)
        {
        }

        /*  somente imprime na saída quando ocorre erro na inserção de um individuo,
            ocorrida na inserção de individuo com identificador duplicado.
        */
        void add(int id,
            const std::string &first_name,
            const std::string &last_name,
            const std::string &birthday,
            const std::string &phone)
        {
            if((id < 0) || (id > max_elements))
            {
                std::cout << "invalid id" << std::endl;
                return;
            }

            if(id_table[id] != NULL)
            {
                std::cout << "ID " << id << " ja cadastrado." << std::endl;
            }

            std::shared_ptr<Person> person(new Person(id,first_name,last_name,birthday,phone));

            id_table[id] = person;

            unsigned int hash_number = hash(first_name);

            insert_on_table(fn_table,person,hash_number);

            hash_number = hash(last_name);
            insert_on_table(ln_table,person,hash_number);

            hash_number = hash(birthday);
            insert_on_table(birth_table,person,hash_number);

            hash_number = hash(phone);
            insert_on_table(phone_table,person,hash_number);
        }

        /*  O comando ''del'' remove todos dados relacionados a um determinado identificador,
            e retorna erro se não existir individuo com o identificador fornecido.
        */
        void del(int id)
        {
            if((id < 0) || (id > max_elements) || (id_table[id] == NULL))
            {
                std::cout << "ID " << id << " nao existente" << std::endl;
                return;
            }

            remove_from_table(fn_table,id_table[id],hash(id_table[id]->first_name));
            remove_from_table(ln_table,id_table[id],hash(id_table[id]->last_name));
            remove_from_table(birth_table,id_table[id],hash(id_table[id]->birthday));
            remove_from_table(phone_table,id_table[id],hash(id_table[id]->phone));
            id_table[id].reset();
        }

        void info(int id)
        {
            if((id < 0) || (id > max_elements) || (id_table[id] == NULL))
            {
                std::cout << "ID " << id << " nao existente." << std::endl;
                return;
            }

            std::cout << id_table[id]->first_name << " "
                      << id_table[id]->last_name << " "
                      << id_table[id]->birthday << " "
                      << id_table[id]->phone << std::endl;
        }
    private:
        const unsigned int max_elements; // Large prime number chosen
        HashTable id_table;
        HashTable fn_table;
        HashTable ln_table;
        HashTable birth_table;
        HashTable phone_table;

        unsigned int hash(const std::string &str)
        {
            unsigned int hash_number = 0;
            unsigned int mult = 1;

            for(char c : str)
            {
                hash_number += c * mult;
                ++mult;
            }

            return hash_number % max_elements;
        }

        void insert_on_table(HashTable &table,Person_ptr person,unsigned int hash_number)
        {
            if(table[hash_number] != NULL)
            {
                person->collision = table[hash_number];
            }

            table[hash_number] = person;
        }

        void remove_from_table(HashTable &table,Person_ptr person,unsigned int hash_number)
        {
            if(table[hash_number] != NULL)
            {
                Person_ptr last_person;
                Person_ptr people_itr = table[hash_number];
                do
                {
                    if(people_itr->id == person->id)
                    {
                        break;
                    }
                    last_person = people_itr;
                    people_itr = people_itr->collision;
                }while(people_itr != NULL);

                if(last_person != NULL)
                {
                    last_person->collision = people_itr->collision;
                    people_itr.reset();
                }
                else
                {
                    table[hash_number] = table[hash_number]->collision;
                }
            }
        }
};

int main(void)
{
    return 0;
}
<commit_msg>Command split working<commit_after>#include <iostream>
#include <string>
#include <memory>
#include <vector>

/*  Neste problema, pede-se para armazenar, gerenciar e buscar por
    indivíduos definidos por
        um identificador único (inteiro)
        Primeiro nome
        último nome,
        data de nascimento
        telefone.
*/
struct Person
{
    Person( int _id = 0,
            const std::string &_first_name = "",
            const std::string &_last_name = "",
            const std::string &_birthday = "",
            const std::string &_phone = ""):
        id(_id),
        first_name(_first_name),
        last_name(_last_name),
        birthday(_birthday),
        phone(_phone)
        {
        }
    int id;
    std::string first_name;
    std::string last_name;
    std::string birthday;
    std::string phone;
    std::shared_ptr<Person> collision;
};

typedef std::shared_ptr<Person> Person_ptr;
typedef std::vector<Person_ptr> HashTable;

class PersonManager
{
    public:
        PersonManager(void):
            max_elements(503),
            id_table(max_elements),
            fn_table(max_elements),
            ln_table(max_elements),
            birth_table(max_elements),
            phone_table(max_elements)
        {
        }

        void execute(std::string line)
        {
            unsigned int first_space = line.find(" ");
            std::string args = line.substr(first_space+1);
            std::string function = line.erase(first_space);

            std::cout << "function: [" << function << "]" << std::endl;
            std::cout << "args: [" << args << "]" << std::endl;
        }

        /*  somente imprime na saída quando ocorre erro na inserção de um individuo,
            ocorrida na inserção de individuo com identificador duplicado.
        */
        void add(int id,
            const std::string &first_name,
            const std::string &last_name,
            const std::string &birthday,
            const std::string &phone)
        {
            if((id < 0) || (id > max_elements))
            {
                std::cout << "invalid id" << std::endl;
                return;
            }

            if(id_table[id] != NULL)
            {
                std::cout << "ID " << id << " ja cadastrado." << std::endl;
            }

            std::shared_ptr<Person> person(new Person(id,first_name,last_name,birthday,phone));

            id_table[id] = person;

            unsigned int hash_number = hash(first_name);

            insert_on_table(fn_table,person,hash_number);

            hash_number = hash(last_name);
            insert_on_table(ln_table,person,hash_number);

            hash_number = hash(birthday);
            insert_on_table(birth_table,person,hash_number);

            hash_number = hash(phone);
            insert_on_table(phone_table,person,hash_number);
        }

        /*  O comando ''del'' remove todos dados relacionados a um determinado identificador,
            e retorna erro se não existir individuo com o identificador fornecido.
        */
        void del(int id)
        {
            if((id < 0) || (id > max_elements) || (id_table[id] == NULL))
            {
                std::cout << "ID " << id << " nao existente" << std::endl;
                return;
            }

            remove_from_table(fn_table,id_table[id],hash(id_table[id]->first_name));
            remove_from_table(ln_table,id_table[id],hash(id_table[id]->last_name));
            remove_from_table(birth_table,id_table[id],hash(id_table[id]->birthday));
            remove_from_table(phone_table,id_table[id],hash(id_table[id]->phone));
            id_table[id].reset();
        }

        void info(int id)
        {
            if((id < 0) || (id > max_elements) || (id_table[id] == NULL))
            {
                std::cout << "ID " << id << " nao existente." << std::endl;
                return;
            }

            std::cout << id_table[id]->first_name << " "
                      << id_table[id]->last_name << " "
                      << id_table[id]->birthday << " "
                      << id_table[id]->phone << std::endl;
        }

        /*  O comando ''query'' realiza uma busca nos indivíduos cadastrados.
            Conforme as seguintes tags de busca:

            fn: Primeiro nome
            ln: Ultimo nome
            bd: Data de nascimento
            pn: Telefone
        */
        void query(const std::string &query_str)
        {
            std::cout << "Entrou na query" << std::endl;
        }
    private:
        const unsigned int max_elements; // Large prime number chosen
        HashTable id_table;
        HashTable fn_table;
        HashTable ln_table;
        HashTable birth_table;
        HashTable phone_table;

        unsigned int hash(const std::string &str)
        {
            unsigned int hash_number = 0;
            unsigned int mult = 1;

            for(char c : str)
            {
                hash_number += c * mult;
                ++mult;
            }

            return hash_number % max_elements;
        }

        void insert_on_table(HashTable &table,Person_ptr person,unsigned int hash_number)
        {
            if(table[hash_number] != NULL)
            {
                person->collision = table[hash_number];
            }

            table[hash_number] = person;
        }

        void remove_from_table(HashTable &table,Person_ptr person,unsigned int hash_number)
        {
            if(table[hash_number] != NULL)
            {
                Person_ptr last_person;
                Person_ptr people_itr = table[hash_number];
                do
                {
                    if(people_itr->id == person->id)
                    {
                        break;
                    }
                    last_person = people_itr;
                    people_itr = people_itr->collision;
                }while(people_itr != NULL);

                if(last_person != NULL)
                {
                    last_person->collision = people_itr->collision;
                    people_itr.reset();
                }
                else
                {
                    table[hash_number] = table[hash_number]->collision;
                }
            }
        }
};

int main(void)
{
    char input[2048];
    unsigned int chars_read;
    PersonManager manager;

    do
    {
        std::cin.getline(input,2048);
        chars_read = std::cin.gcount();
        input[chars_read] = '\0';
        if(chars_read > 0)
        {
            manager.execute(input);
        }
    }while(chars_read > 0);
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <math.h>
//#include <algoritm.h>

using namespace std;

//TO DO:
//* make queueing function
//* make seach function
//* figure out how to que all things

//general search function to use with search algorithms
vector < vector <int> > generalSearch( vector < vector<int> > problem /*queueing function*/ );

//function to check if the matrix matches the goal state
bool checkIfGoal(vector <vector <int> > M);

int main(){
    vector < vector <int> > matrix;
    vector < vector <int> > goal;

    //make goal matrix to visualize
    goal.push_back(std::vector<int>(3, 1));
    goal.push_back(std::vector<int>(3, 2));
    goal.push_back(std::vector<int>(3, 3));

    goal[0][0]=1;
    goal[0][1]=2;
    goal[0][2]=3;
    goal[1][0]=4;
    goal[1][1]=5;
    goal[1][2]=6;
    goal[2][0]=7;
    goal[2][1]=8;
    goal[2][2]=0;

    cout << "Outputting goal matrix: " << endl;
    int a,b;
    for(b = 0; b < 3; ++b)
    {
        for(a = 0; a < 3; ++a)
            cout << goal[b][a] << "\t" ;
        cout<<endl;
    }

    //make matrix for 8puzzle
    matrix.push_back(std::vector<int>(3, 1));
    matrix.push_back(std::vector<int>(3, 2));
    matrix.push_back(std::vector<int>(3, 3));

    matrix[0][0]=1;
    matrix[0][1]=2;
    matrix[0][2]=3;
    matrix[1][0]=4;
    matrix[1][1]=5;
    matrix[1][2]=6;
    matrix[2][0]=7;
    matrix[2][1]=8;
    matrix[2][2]=0;

    cout << "Outputting regular matrix: " << endl;
    int c,d;
    for(d = 0; d < 3; ++d)
    {
        for(c = 0; c < 3; ++c)
            cout << matrix[d][c] << "\t" ;
        cout<<endl;
    }

    //checking if goal matches matrix with function
    cout << "8 Tile matches goal state? " << checkIfGoal(matrix) << endl;

    return 0;
}

bool checkIfGoal(vector <vector <int> > M)
{
    if(M[0][0] ==1 && M[0][1] ==2 && M[0][2] ==3 && M[1][0] ==4 && M[1][1] == 5 && M[1][2] == 6 && M[2][0] == 7 && M[2][1] == 8 && M[2][2] == 0)
        return true;
    return false;
}

<commit_msg>added working operators and wrote out some of the seaarch function<commit_after>#include <iostream>
#include <vector>
#include<queue>
#include <math.h>
//#include <algoritm.h>

using namespace std;

    struct Matrix{
        vector < vector <int> > problem;
        vector < vector <int> > goal;
        int fn;
        int gn;
        int hn;
    };

    class Compare_Values    {
        public:
            bool operator()(Matrix& M1, Matrix& M2){
                if(M1.fn != 0){
                    if(M1.fn < M2.fn) return true;
                }
                else{
                    if(M1.gn < M2.gn) return true;
                }
                return false;
            }
    };

//TO DO:
//* make queueing function
//* make seach function
//* figure out how to que all things
//* make function to expand nodes with all different operators
//* make functions for operators to move the blank tile

//OPERATORS: i and j are values you want to move blank to
void UP(Matrix& M, int i, int j){
    int temp = M.problem[i][j];
    M.problem[i][j] = 0;
    M.problem[i+1][j] = temp;
    return;
}

void DN(Matrix& M, int i, int j){
    int temp = M.problem[i][j];
    M.problem[i][j] = 0;
    M.problem[i-1][j] = temp;
    return;
}

void RT(Matrix& M, int i, int j){
    int temp = M.problem[i][j];
    M.problem[i][j] = 0;
    M.problem[i][j-1] = temp;
    return;
}

void LF(Matrix& M, int i, int j){
    int temp = M.problem[i][j];
    M.problem[i][j] = 0;
    M.problem[i][j+1] = temp;
    return;
}

//void expand(Matrix& M,

//function to expand nodes with operators (current node, operators)
//returns queue of matricies (all possible ways to move the blank)

//Uniform Cost Search function (nodes(queue), expand)
//returns a queue in order of g(n)
//priority_queue<

//A* Mattahatan Search Function
//returns a queue in order of f(n) = g(n) + f(n)

//A* Misplaced Tile function
//returns a queue in order of f(n) = g(n) + f(n)

//general search function to use with search algorithms
void/*Matrix*/ generalSearch( Matrix m /*queueing function*/ );

//function to check if the matrix matches the goal state
bool checkIfGoal(vector < vector<int> >  M);

int main(){

    Matrix M;

    //make goal matrix to visualize
    M.goal.push_back(std::vector<int>(3, 1));
    M.goal.push_back(std::vector<int>(3, 2));
    M.goal.push_back(std::vector<int>(3, 3));

    M.goal[0][0]=1;
    M.goal[0][1]=2;
    M.goal[0][2]=3;
    M.goal[1][0]=4;
    M.goal[1][1]=5;
    M.goal[1][2]=6;
    M.goal[2][0]=7;
    M.goal[2][1]=8;
    M.goal[2][2]=0;

    cout << "Outputting goal matrix: " << endl;
    int a,b;
    for(b = 0; b < 3; ++b)
    {
        for(a = 0; a < 3; ++a)
            cout << M.goal[b][a] << "\t" ;
        cout<<endl;
    }

    //make matrix for 8puzzle
    M.problem.push_back(std::vector<int>(3, 1));
    M.problem.push_back(std::vector<int>(3, 2));
    M.problem.push_back(std::vector<int>(3, 3));

    M.problem[0][0]=1;
    M.problem[0][1]=2;
    M.problem[0][2]=3;
    M.problem[1][0]=4;
    M.problem[1][1]=5;
    M.problem[1][2]=6;
    M.problem[2][0]=7;
    M.problem[2][1]=8;
    M.problem[2][2]=0;

    cout << "Outputting regular matrix: " << endl;
    int c,d;
    for(d = 0; d < 3; ++d)
    {
        for(c = 0; c < 3; ++c)
            cout << M.problem[d][c] << "\t" ;
        cout<<endl;
    }

    LF(M, 2,1);

    cout << "Outputting fixed matrix: " << endl;
    for(d = 0; d < 3; ++d)
    {
        for(c = 0; c < 3; ++c)
            cout << M.problem[d][c] << "\t" ;
        cout<<endl;
    }

    //checking if goal matches matrix with function
    cout << "8 Tile matches goal state? " << checkIfGoal(M.problem) << endl;

    //generalSearch(M);

    /*cout << "Outputting search problem matrix: " << endl;
    int e,f;
    for(f = 0; f < 3; ++f)
    {
        for(e = 0; e < 3; ++e)
            cout << M1.problem[f][e] << "\t" ;
        cout<<endl;
    }*/

    return 0;
}

bool checkIfGoal(vector <vector<int> > M)
{
    if(M[0][0] ==1 && M[0][1] ==2 && M[0][2] ==3 && M[1][0] ==4 && M[1][1] == 5 && M[1][2] == 6 && M[2][0] == 7 && M[2][1] == 8 && M[2][2] == 0)
        return true;
    return false;
}
//void Matrix generalSearch( Matrix& m /*queueing function*/ ){
/*    priority_queue <Matrix, vector<Matrix>, Compare_Values> nodes;

    nodes.push(m);
    if(nodes.empty())
        return "failure";
    do{
        cout << "Nodes is now: " << endl;
        int e,f;
        for(f = 0; f < 3; ++f)
        {
            for(e = 0; e < 3; ++e)
                cout << nodes.top().problem[f][e] << "\t" ;
            cout<<endl;
        }

        if(nodes.empty()) return failure;

        //return nodes.top();
    }while(!nodes.empty);
}*/

<|endoftext|>


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

#include "Tools/types.h"
#include "Tools/params.h"
#include "Tools/Arguments_reader.hpp"
#include "Tools/Display/bash_tools.h"
#include "Tools/Perf/MIPP/mipp.h"

#include "Launcher/Launcher.hpp"

#include "Launcher/BFER/Polar/Launcher_BFER_polar.hpp"
#include "Launcher/BFER/Turbo/Launcher_BFER_turbo.hpp"
#include "Launcher/BFER/LDPC/Launcher_BFER_LDPC.hpp"
#include "Launcher/BFER/RSC/Launcher_BFER_RSC.hpp"
#include "Launcher/BFER/RA/Launcher_BFER_RA.hpp"
#include "Launcher/BFER/Repetition/Launcher_BFER_repetition.hpp"
#include "Launcher/BFER/Uncoded/Launcher_BFER_uncoded.hpp"

#include "Launcher/BFERI/RSC/Launcher_BFERI_RSC.hpp"
#include "Launcher/BFERI/LDPC/Launcher_BFERI_LDPC.hpp"
#include "Launcher/BFERI/Uncoded/Launcher_BFERI_uncoded.hpp"

#include "Launcher/EXIT/Polar/Launcher_EXIT_polar.hpp"
#include "Launcher/EXIT/RSC/Launcher_EXIT_RSC.hpp"

#include "Launcher/GEN/Polar/Launcher_GEN_polar.hpp"

#include "main.h"

void print_version()
{
#if defined(_WIN64) || defined(_WIN32) || defined(WIN32) || defined(__MINGW32__)
	std::string os = "Windows";
#elif defined(__linux__) || defined(__linux)
	std::string os = "Linux";
#elif defined(__APPLE__)
	std::string os = "Mac OS X";
#else
	std::string os = "Unknown OS";
#endif

#if defined(__x86_64) || defined(__x86_64__) || defined(_WIN64) || defined(__aarch64__)
	std::string prec = " 64-bit";
#elif defined(__i386) || defined(__i386__) || defined(i386) || defined(_WIN32) || defined(__ARM_ARCH_7__)
	std::string prec = " 32-bit";
#else
	std::string prec = "";
#endif

#if defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC)
	std::string compiler = "icpc";
#if defined(__INTEL_COMPILER)
	std::string compiler_version = std::to_string(__INTEL_COMPILER);
#elif defined(__ICL)
	std::string compiler_version = std::to_string(__ICL);
#else
	std::string compiler_version = std::to_string(__ICC);
#endif
	compiler_version = compiler_version.substr(0,2) + "." + compiler_version.substr(2,compiler_version.size());
#elif defined(__clang__) || defined(__llvm__)
	std::string compiler = "clang++";
	std::string compiler_version = std::to_string(__clang_major__);
	compiler_version += "." + std::to_string(__clang_minor__);
#elif defined(__GNUG__) || (defined(__GNUC__) && defined(__cplusplus))
	std::string compiler = "g++";
	std::string compiler_version = std::to_string(__GNUC__);
	compiler_version += "." + std::to_string(__GNUC_MINOR__);
#elif defined(_MSC_VER)
	std::string compiler = "MSVC++";
	std::string compiler_version = std::to_string(_MSC_VER);
#else
	std::string compiler = "Unknown compiler";
	std::string compiler_version = "";
#endif
	std::string affect_version = "1.0.0";

	std::cout << "aff3ct (" << os << prec << ", " << compiler << " " << compiler_version << ", "
	          << mipp::IntructionsType << ") " << affect_version << std::endl;
	std::cout << "Copyright (c) 2016 - MIT license."                                           << std::endl;
	std::cout << "This is free software; see the source for copying conditions.  There is NO"  << std::endl;
	std::cout << "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." << std::endl;
	exit(EXIT_SUCCESS);
}

#ifdef MULTI_PREC
void read_arguments(const int argc, const char** argv, std::string &code_type, std::string &simu_type, int &prec)
#else
void read_arguments(const int argc, const char** argv, std::string &code_type, std::string &simu_type)
#endif
{
	using namespace std::chrono;

	std::map<std::vector<std::string>, std::vector<std::string>> req_args, opt_args;
	Arguments_reader ar(argc, argv);

	// ---------------------------------------------------------------------------------------------------- simulation
	opt_args[{"sim-type"}] =
			{"string",
			 "the type of simulation to run.",
			 "BFER, BFERI, EXIT, GEN"};
#ifdef MULTI_PREC
	opt_args[{"sim-prec", "p"}] =
		{"positive_int",
		 "the simulation precision in bit.",
		 "8, 16, 32, 64"};
#endif

	// ---------------------------------------------------------------------------------------------------------- code
	req_args[{"cde-type"}] =
		{"string",
		 "the type of codes you want to simulate.",
		 "POLAR, TURBO, LDPC, REPETITION, RA, RSC, UNCODED"};

	// --------------------------------------------------------------------------------------------------------- other
	opt_args[{"version", "v"}] =
		{"",
		 "print informations about the version of the code."};
	opt_args[{"help", "h"}] =
		{"",
		 "print this help."};

	auto display_help = true;
	auto parsing = ar.parse_arguments(req_args, opt_args);

	if (ar.exist_arg({"version", "v"}))
		print_version();

	if (parsing)
	{
		// required parameters
		code_type = ar.get_arg({"cde-type"});

		// facultative parameters
		if(ar.exist_arg({"sim-type"})) simu_type = ar.get_arg({"sim-type"});
#ifdef MULTI_PREC
		if(ar.exist_arg({"sim-prec", "p"})) prec = ar.get_arg_int({"sim-prec", "p"});
#endif

		display_help = false;
	}

	if (display_help)
	{
		std::vector<std::vector<std::string>> arg_grp;
		arg_grp.push_back({"sim", "Simulation parameter(s)"});
		arg_grp.push_back({"cde", "Code parameter(s)"      });
		ar.print_usage(arg_grp);
		std::exit(EXIT_FAILURE);
	}

	if (!ar.check_arguments())
		std::exit(EXIT_FAILURE);
}

template <typename B, typename R, typename Q, typename QD>
Launcher<B,R,Q>* create_exit_simu(const int argc, const char **argv, std::string code_type, std::string simu_type)
{
	return nullptr;
}

#if defined(MULTI_PREC) || defined(PREC_32_BIT)
template <>
Launcher<int,float,float>* create_exit_simu<int, float, float, float>(const int     argc,
                                                                      const char  **argv,
                                                                      std::string   code_type,
                                                                      std::string   simu_type)
{
	if (code_type == "POLAR")
		if (simu_type == "EXIT")
			return new Launcher_EXIT_polar<int,float,float>(argc, argv);

	if (code_type == "RSC")
		if (simu_type == "EXIT")
			return new Launcher_EXIT_RSC<int,float,float,float>(argc, argv);

	return nullptr;
}
#endif

#if defined(MULTI_PREC) || defined(PREC_64_BIT)
template <>
Launcher<long long,double,double>* create_exit_simu<long long, double, double, double>(const int     argc,
                                                                                const char  **argv,
                                                                                std::string   code_type,
                                                                                std::string   simu_type)
{
	if (code_type == "POLAR")
		if (simu_type == "EXIT")
			return new Launcher_EXIT_polar<long long,double,double>(argc, argv);

	if (code_type == "RSC")
		if (simu_type == "EXIT")
			return new Launcher_EXIT_RSC<long long,double,double,double>(argc, argv);

	return nullptr;
}
#endif

template <typename B, typename R, typename Q, typename QD>
void start_simu(const int argc, const char **argv, std::string code_type, std::string simu_type)
{
	Launcher<B,R,Q> *launcher = nullptr;

	if (code_type == "POLAR")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_polar<B,R,Q>(argc, argv);
		else if (simu_type == "GEN")
			launcher = new Launcher_GEN_polar<B,R,Q>(argc, argv);
	}

	if (code_type == "RSC")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_RSC<B,R,Q,QD>(argc, argv);
		else if (simu_type == "BFERI")
			launcher = new Launcher_BFERI_RSC<B,R,Q,QD>(argc, argv);
	}

	if (code_type == "TURBO")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_turbo<B,R,Q,QD>(argc, argv);
	}

	if (code_type == "REPETITION")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_repetition<B,R,Q>(argc, argv);
	}

	if (code_type == "RA")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_RA<B,R,Q>(argc, argv);
	}

	if (code_type == "LDPC")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_LDPC<B,R,Q>(argc, argv);
		else if (simu_type == "BFERI")
			launcher = new Launcher_BFERI_LDPC<B,R,Q>(argc, argv);
	}

	if (code_type == "UNCODED")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_uncoded<B,R,Q>(argc, argv);
		else if (simu_type == "BFERI")
			launcher = new Launcher_BFERI_uncoded<B,R,Q>(argc, argv);
	}

	if (launcher == nullptr)
	{
		launcher = create_exit_simu<B,R,Q,QD>(argc, argv, code_type, simu_type);

		if (launcher == nullptr)
		{
			std::cerr << bold_red("(EE) Unsupported type of codes/simulation.") << std::endl;
			exit(EXIT_FAILURE);
		}
	}

	launcher->launch();
	delete launcher;
}

#ifndef SYSTEMC
int main(int argc, char **argv)
#else
int sc_main(int argc, char **argv)
#endif
{
	std::string code_type, simu_type = "BFER";

#ifdef MULTI_PREC
	int prec = 32;
	read_arguments(argc, (const char**)argv, code_type, simu_type, prec);

	switch (prec)
	{
		case 8:
			start_simu<B_8, R_8, Q_8, QD_8 >(argc, (const char**)argv, code_type, simu_type); break;
		case 16:
			start_simu<B_16,R_16,Q_16,QD_16>(argc, (const char**)argv, code_type, simu_type); break;
		case 32:
			start_simu<B_32,R_32,Q_32,QD_32>(argc, (const char**)argv, code_type, simu_type); break;
#if defined(__x86_64) || defined(__x86_64__) || defined(_WIN64) || defined(__aarch64__)
		case 64:
			start_simu<B_64,R_64,Q_64,QD_64>(argc, (const char**)argv, code_type, simu_type); break;
#endif
		default:
			std::cerr << bold_red("(EE) Unsupported number of bits.") << std::endl;
			exit(EXIT_FAILURE);
			break;
	}
#else
	read_arguments(argc, (const char**)argv, code_type, simu_type);
	start_simu<B,R,Q,QD>(argc, (const char**)argv, code_type, simu_type);
#endif

	return EXIT_SUCCESS;
}
<commit_msg>Increment the version number.<commit_after>#include <cstdlib>
#include <iostream>
#include <map>

#include "Tools/types.h"
#include "Tools/params.h"
#include "Tools/Arguments_reader.hpp"
#include "Tools/Display/bash_tools.h"
#include "Tools/Perf/MIPP/mipp.h"

#include "Launcher/Launcher.hpp"

#include "Launcher/BFER/Polar/Launcher_BFER_polar.hpp"
#include "Launcher/BFER/Turbo/Launcher_BFER_turbo.hpp"
#include "Launcher/BFER/LDPC/Launcher_BFER_LDPC.hpp"
#include "Launcher/BFER/RSC/Launcher_BFER_RSC.hpp"
#include "Launcher/BFER/RA/Launcher_BFER_RA.hpp"
#include "Launcher/BFER/Repetition/Launcher_BFER_repetition.hpp"
#include "Launcher/BFER/Uncoded/Launcher_BFER_uncoded.hpp"

#include "Launcher/BFERI/RSC/Launcher_BFERI_RSC.hpp"
#include "Launcher/BFERI/LDPC/Launcher_BFERI_LDPC.hpp"
#include "Launcher/BFERI/Uncoded/Launcher_BFERI_uncoded.hpp"

#include "Launcher/EXIT/Polar/Launcher_EXIT_polar.hpp"
#include "Launcher/EXIT/RSC/Launcher_EXIT_RSC.hpp"

#include "Launcher/GEN/Polar/Launcher_GEN_polar.hpp"

#include "main.h"

void print_version()
{
#if defined(_WIN64) || defined(_WIN32) || defined(WIN32) || defined(__MINGW32__)
	std::string os = "Windows";
#elif defined(__linux__) || defined(__linux)
	std::string os = "Linux";
#elif defined(__APPLE__)
	std::string os = "Mac OS X";
#else
	std::string os = "Unknown OS";
#endif

#if defined(__x86_64) || defined(__x86_64__) || defined(_WIN64) || defined(__aarch64__)
	std::string prec = " 64-bit";
#elif defined(__i386) || defined(__i386__) || defined(i386) || defined(_WIN32) || defined(__ARM_ARCH_7__)
	std::string prec = " 32-bit";
#else
	std::string prec = "";
#endif

#if defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC)
	std::string compiler = "icpc";
#if defined(__INTEL_COMPILER)
	std::string compiler_version = std::to_string(__INTEL_COMPILER);
#elif defined(__ICL)
	std::string compiler_version = std::to_string(__ICL);
#else
	std::string compiler_version = std::to_string(__ICC);
#endif
	compiler_version = compiler_version.substr(0,2) + "." + compiler_version.substr(2,compiler_version.size());
#elif defined(__clang__) || defined(__llvm__)
	std::string compiler = "clang++";
	std::string compiler_version = std::to_string(__clang_major__);
	compiler_version += "." + std::to_string(__clang_minor__);
#elif defined(__GNUG__) || (defined(__GNUC__) && defined(__cplusplus))
	std::string compiler = "g++";
	std::string compiler_version = std::to_string(__GNUC__);
	compiler_version += "." + std::to_string(__GNUC_MINOR__);
#elif defined(_MSC_VER)
	std::string compiler = "MSVC++";
	std::string compiler_version = std::to_string(_MSC_VER);
#else
	std::string compiler = "Unknown compiler";
	std::string compiler_version = "";
#endif
	std::string affect_version = "1.1.0";

	std::cout << "aff3ct (" << os << prec << ", " << compiler << " " << compiler_version << ", "
	          << mipp::IntructionsType << ") " << affect_version << std::endl;
	std::cout << "Copyright (c) 2016 - MIT license."                                           << std::endl;
	std::cout << "This is free software; see the source for copying conditions.  There is NO"  << std::endl;
	std::cout << "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." << std::endl;
	exit(EXIT_SUCCESS);
}

#ifdef MULTI_PREC
void read_arguments(const int argc, const char** argv, std::string &code_type, std::string &simu_type, int &prec)
#else
void read_arguments(const int argc, const char** argv, std::string &code_type, std::string &simu_type)
#endif
{
	using namespace std::chrono;

	std::map<std::vector<std::string>, std::vector<std::string>> req_args, opt_args;
	Arguments_reader ar(argc, argv);

	// ---------------------------------------------------------------------------------------------------- simulation
	opt_args[{"sim-type"}] =
			{"string",
			 "the type of simulation to run.",
			 "BFER, BFERI, EXIT, GEN"};
#ifdef MULTI_PREC
	opt_args[{"sim-prec", "p"}] =
		{"positive_int",
		 "the simulation precision in bit.",
		 "8, 16, 32, 64"};
#endif

	// ---------------------------------------------------------------------------------------------------------- code
	req_args[{"cde-type"}] =
		{"string",
		 "the type of codes you want to simulate.",
		 "POLAR, TURBO, LDPC, REPETITION, RA, RSC, UNCODED"};

	// --------------------------------------------------------------------------------------------------------- other
	opt_args[{"version", "v"}] =
		{"",
		 "print informations about the version of the code."};
	opt_args[{"help", "h"}] =
		{"",
		 "print this help."};

	auto display_help = true;
	auto parsing = ar.parse_arguments(req_args, opt_args);

	if (ar.exist_arg({"version", "v"}))
		print_version();

	if (parsing)
	{
		// required parameters
		code_type = ar.get_arg({"cde-type"});

		// facultative parameters
		if(ar.exist_arg({"sim-type"})) simu_type = ar.get_arg({"sim-type"});
#ifdef MULTI_PREC
		if(ar.exist_arg({"sim-prec", "p"})) prec = ar.get_arg_int({"sim-prec", "p"});
#endif

		display_help = false;
	}

	if (display_help)
	{
		std::vector<std::vector<std::string>> arg_grp;
		arg_grp.push_back({"sim", "Simulation parameter(s)"});
		arg_grp.push_back({"cde", "Code parameter(s)"      });
		ar.print_usage(arg_grp);
		std::exit(EXIT_FAILURE);
	}

	if (!ar.check_arguments())
		std::exit(EXIT_FAILURE);
}

template <typename B, typename R, typename Q, typename QD>
Launcher<B,R,Q>* create_exit_simu(const int argc, const char **argv, std::string code_type, std::string simu_type)
{
	return nullptr;
}

#if defined(MULTI_PREC) || defined(PREC_32_BIT)
template <>
Launcher<int,float,float>* create_exit_simu<int, float, float, float>(const int     argc,
                                                                      const char  **argv,
                                                                      std::string   code_type,
                                                                      std::string   simu_type)
{
	if (code_type == "POLAR")
		if (simu_type == "EXIT")
			return new Launcher_EXIT_polar<int,float,float>(argc, argv);

	if (code_type == "RSC")
		if (simu_type == "EXIT")
			return new Launcher_EXIT_RSC<int,float,float,float>(argc, argv);

	return nullptr;
}
#endif

#if defined(MULTI_PREC) || defined(PREC_64_BIT)
template <>
Launcher<long long,double,double>* create_exit_simu<long long, double, double, double>(const int     argc,
                                                                                const char  **argv,
                                                                                std::string   code_type,
                                                                                std::string   simu_type)
{
	if (code_type == "POLAR")
		if (simu_type == "EXIT")
			return new Launcher_EXIT_polar<long long,double,double>(argc, argv);

	if (code_type == "RSC")
		if (simu_type == "EXIT")
			return new Launcher_EXIT_RSC<long long,double,double,double>(argc, argv);

	return nullptr;
}
#endif

template <typename B, typename R, typename Q, typename QD>
void start_simu(const int argc, const char **argv, std::string code_type, std::string simu_type)
{
	Launcher<B,R,Q> *launcher = nullptr;

	if (code_type == "POLAR")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_polar<B,R,Q>(argc, argv);
		else if (simu_type == "GEN")
			launcher = new Launcher_GEN_polar<B,R,Q>(argc, argv);
	}

	if (code_type == "RSC")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_RSC<B,R,Q,QD>(argc, argv);
		else if (simu_type == "BFERI")
			launcher = new Launcher_BFERI_RSC<B,R,Q,QD>(argc, argv);
	}

	if (code_type == "TURBO")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_turbo<B,R,Q,QD>(argc, argv);
	}

	if (code_type == "REPETITION")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_repetition<B,R,Q>(argc, argv);
	}

	if (code_type == "RA")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_RA<B,R,Q>(argc, argv);
	}

	if (code_type == "LDPC")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_LDPC<B,R,Q>(argc, argv);
		else if (simu_type == "BFERI")
			launcher = new Launcher_BFERI_LDPC<B,R,Q>(argc, argv);
	}

	if (code_type == "UNCODED")
	{
		if (simu_type == "BFER")
			launcher = new Launcher_BFER_uncoded<B,R,Q>(argc, argv);
		else if (simu_type == "BFERI")
			launcher = new Launcher_BFERI_uncoded<B,R,Q>(argc, argv);
	}

	if (launcher == nullptr)
	{
		launcher = create_exit_simu<B,R,Q,QD>(argc, argv, code_type, simu_type);

		if (launcher == nullptr)
		{
			std::cerr << bold_red("(EE) Unsupported type of codes/simulation.") << std::endl;
			exit(EXIT_FAILURE);
		}
	}

	launcher->launch();
	delete launcher;
}

#ifndef SYSTEMC
int main(int argc, char **argv)
#else
int sc_main(int argc, char **argv)
#endif
{
	std::string code_type, simu_type = "BFER";

#ifdef MULTI_PREC
	int prec = 32;
	read_arguments(argc, (const char**)argv, code_type, simu_type, prec);

	switch (prec)
	{
		case 8:
			start_simu<B_8, R_8, Q_8, QD_8 >(argc, (const char**)argv, code_type, simu_type); break;
		case 16:
			start_simu<B_16,R_16,Q_16,QD_16>(argc, (const char**)argv, code_type, simu_type); break;
		case 32:
			start_simu<B_32,R_32,Q_32,QD_32>(argc, (const char**)argv, code_type, simu_type); break;
#if defined(__x86_64) || defined(__x86_64__) || defined(_WIN64) || defined(__aarch64__)
		case 64:
			start_simu<B_64,R_64,Q_64,QD_64>(argc, (const char**)argv, code_type, simu_type); break;
#endif
		default:
			std::cerr << bold_red("(EE) Unsupported number of bits.") << std::endl;
			exit(EXIT_FAILURE);
			break;
	}
#else
	read_arguments(argc, (const char**)argv, code_type, simu_type);
	start_simu<B,R,Q,QD>(argc, (const char**)argv, code_type, simu_type);
#endif

	return EXIT_SUCCESS;
}
<|endoftext|>