<commit_before>/*************************************************************************
 *
 *  $RCSfile: options.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: jsc $ $Date: 2001-03-15 12:30:43 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#include <stdio.h>

#ifndef _IDLC_OPTIONS_HXX_
#include <idlc/options.hxx>
#endif

using namespace rtl;

Options::Options()
{
}

Options::~Options()
{

}

sal_Bool Options::initOptions(int ac, char* av[], sal_Bool bCmdFile)
    throw( IllegalArgument )
{
    sal_Bool    ret = sal_True;
    sal_uInt16  i=0;

    if (!bCmdFile)
    {
        bCmdFile = sal_True;

        m_program = av[0];

        if (ac < 2)
        {
            fprintf(stderr, "%s", prepareHelp().getStr());
            ret = sal_False;
        }

        i = 1;
    } else
    {
        i = 0;
    }

    char    *s=NULL;
    for (i; i < ac; i++)
    {
        if (av[i][0] == '-')
        {
            switch (av[i][1])
            {
                case 'O':
                    if (av[i][2] == '\0')
                    {
                        if (i < ac - 1 && av[i+1][0] != '-')
                        {
                            i++;
                            s = av[i];
                        } else
                        {
                            OString tmp("'-O', please check");
                            if (i <= ac - 1)
                            {
                                tmp += " your input '" + OString(av[i+1]) + "'";
                            }

                            throw IllegalArgument(tmp);
                        }
                    } else
                    {
                        s = av[i] + 2;
                    }

                    m_options["-O"] = OString(s);
                    break;
                case 'I':
                {
                    if (av[i][2] == '\0')
                    {
                        if (i < ac - 1 && av[i+1][0] != '-')
                        {
                            i++;
                            s = av[i];
                        } else
                        {
                            OString tmp("'-I', please check");
                            if (i <= ac - 1)
                            {
                                tmp += " your input '" + OString(av[i+1]) + "'";
                            }

                            throw IllegalArgument(tmp);
                        }
                    } else
                    {
                        s = av[i] + 2;
                    }

                    OString inc(s);
                    if ( inc.indexOf(';') > 0 )
                    {
                        OString tmp(s);
                        sal_Int32 count = tmp.getTokenCount(';');
                        inc = OString();
                        for (sal_Int32 i=0; i < count; i++)
                            inc = inc + " -I" + tmp.getToken(i, ';');
                    } else
                        inc = OString("-I") + s;

                    if (m_options.count("-I") > 0)
                    {
                        OString tmp(m_options["-I"]);
                        tmp = tmp + " " + inc;
                        m_options["-I"] = tmp;
                    } else
                    {
                        m_options["-I"] = inc;
                    }
                }
                    break;
                case 'D':
                    if (av[i][2] == '\0')
                    {
                        if (i < ac - 1 && av[i+1][0] != '-')
                        {
                            i++;
                            s = av[i];
                        } else
                        {
                            OString tmp("'-D', please check");
                            if (i <= ac - 1)
                            {
                                tmp += " your input '" + OString(av[i+1]) + "'";
                            }

                            throw IllegalArgument(tmp);
                        }
                    } else
                    {
                        s = av[i];
                    }

                    if (m_options.count("-D") > 0)
                    {
                        OString tmp(m_options["-D"]);
                        tmp = tmp + " " + s;
                        m_options["-D"] = tmp;
                    } else
                    {
                        m_options["-D"] = OString(s);
                    }
                    break;
                case 'C':
                    if (av[i][2] != '\0')
                    {
                        throw IllegalArgument(OString(av[i]) + ", please check your input");
                    }
                    if (m_options.count("-C") == 0)
                    {
                        m_options["-C"] = OString(s);
                    }
                    break;
                case 'h':
                case '?':
                    if (av[i][2] != '\0')
                    {
                        throw IllegalArgument(OString(av[i]) + ", please check your input");
                    } else
                    {
                        fprintf(stdout, "%s", prepareHelp().getStr());
                        exit(0);
                    }
                    break;
                default:
                    throw IllegalArgument("the option is unknown" + OString(av[i]));
                    break;
            }
        } else
        {
            if (av[i][0] == '@')
            {
                FILE* cmdFile = fopen(av[i]+1, "r");
                  if( cmdFile == NULL )
                  {
                    fprintf(stderr, "%s", prepareHelp().getStr());
                    ret = sal_False;
                } else
                {
                    int rargc=0;
                    char* rargv[512];
                    char  buffer[512];

                    while ( fscanf(cmdFile, "%s", buffer) != EOF )
                    {
                        rargv[rargc]= strdup(buffer);
                        rargc++;
                    }
                    fclose(cmdFile);

                    ret = initOptions(rargc, rargv, bCmdFile);

                    for (long i=0; i < rargc; i++)
                    {
                        free(rargv[i]);
                    }
                }
            } else
            {
                OString name(av[i]);
                name = name.toLowerCase();
                if ( name.lastIndexOf(".idl") != (name.getLength() - 4) )
                {
                    throw IllegalArgument("'" + OString(av[i]) +
                        "' is not a valid input file, only '*.idl' files will be accepted");
                }
                m_inputFiles.push_back(av[i]);
            }
        }
    }

    return ret;
}

OString Options::prepareHelp()
{
    OString help("\nusing: ");
    help += m_program + " [-options] file_1 ... file_n | @<filename>\n";
    help += "    file_n      = file_n specifies one or more idl files.\n";
    help += "                  Only files with the extension '.idl' are valid.\n";
    help += "    @<filename> = filename specifies the name of a command file.\n";
    help += "  Options:\n";
    help += "    -O<path>   = path describes the output directory.\n";
    help += "                 The generated output is a registry file with\n";
    help += "                 the same name as the idl input file.\n";
    help += "    -I<path>   = path specifies a directory where are include\n";
    help += "                 files will be searched by the preprcessor.\n";
    help += "                 Multible directories could be combined with ';'.\n";
    help += "    -D<name>   = name defines a macro for the preprocessor.\n";
    help += "    -C         = generate complete type information, including\n";
    help += "                 additional service information and documentation.\n";
    help += "    -h|-?      = print this help message and exit.\n";
    help += prepareVersion();

    return help;
}

OString Options::prepareVersion()
{
    OString version("\nSun Microsystems (R) ");
    version += m_program + " Version 1.0\n\n";
    return version;
}

const OString& Options::getProgramName() const
{
    return m_program;
}

sal_uInt16 Options::getNumberOfOptions() const
{
    return m_options.size();
}

sal_Bool Options::isValid(const OString& option)
{
    return (m_options.count(option) > 0);
}

const OString Options::getOption(const OString& option)
    throw( IllegalArgument )
{
    const OString ret;

    if (m_options.count(option) > 0)
    {
        return m_options[option];
    } else
    {
        throw IllegalArgument("Option is not valid or currently not set.");
    }

    return ret;
}

const OptionMap& Options::getOptions()
{
    return m_options;
}

sal_uInt16 Options::getNumberOfInputFiles() const
{
    return m_inputFiles.size();
}

const OString Options::getInputFile(sal_uInt16 index)
    throw( IllegalArgument )
{
    const OString ret;

    if (index < m_inputFiles.size())
    {
        return m_inputFiles[index];
    } else
    {
        throw IllegalArgument("index is out of bound.");
    }

    return ret;
}

const StringVector& Options::getInputFiles()
{
    return m_inputFiles;
}

<commit_msg>change option description<commit_after>/*************************************************************************
 *
 *  $RCSfile: options.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: jsc $ $Date: 2001-03-19 09:31:13 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#include <stdio.h>

#ifndef _IDLC_OPTIONS_HXX_
#include <idlc/options.hxx>
#endif

using namespace rtl;

Options::Options()
{
}

Options::~Options()
{

}

sal_Bool Options::initOptions(int ac, char* av[], sal_Bool bCmdFile)
    throw( IllegalArgument )
{
    sal_Bool    ret = sal_True;
    sal_uInt16  i=0;

    if (!bCmdFile)
    {
        bCmdFile = sal_True;

        m_program = av[0];

        if (ac < 2)
        {
            fprintf(stderr, "%s", prepareHelp().getStr());
            ret = sal_False;
        }

        i = 1;
    } else
    {
        i = 0;
    }

    char    *s=NULL;
    for (i; i < ac; i++)
    {
        if (av[i][0] == '-')
        {
            switch (av[i][1])
            {
                case 'O':
                    if (av[i][2] == '\0')
                    {
                        if (i < ac - 1 && av[i+1][0] != '-')
                        {
                            i++;
                            s = av[i];
                        } else
                        {
                            OString tmp("'-O', please check");
                            if (i <= ac - 1)
                            {
                                tmp += " your input '" + OString(av[i+1]) + "'";
                            }

                            throw IllegalArgument(tmp);
                        }
                    } else
                    {
                        s = av[i] + 2;
                    }

                    m_options["-O"] = OString(s);
                    break;
                case 'I':
                {
                    if (av[i][2] == '\0')
                    {
                        if (i < ac - 1 && av[i+1][0] != '-')
                        {
                            i++;
                            s = av[i];
                        } else
                        {
                            OString tmp("'-I', please check");
                            if (i <= ac - 1)
                            {
                                tmp += " your input '" + OString(av[i+1]) + "'";
                            }

                            throw IllegalArgument(tmp);
                        }
                    } else
                    {
                        s = av[i] + 2;
                    }

                    OString inc(s);
                    if ( inc.indexOf(';') > 0 )
                    {
                        OString tmp(s);
                        sal_Int32 count = tmp.getTokenCount(';');
                        inc = OString();
                        for (sal_Int32 i=0; i < count; i++)
                            inc = inc + " -I" + tmp.getToken(i, ';');
                    } else
                        inc = OString("-I") + s;

                    if (m_options.count("-I") > 0)
                    {
                        OString tmp(m_options["-I"]);
                        tmp = tmp + " " + inc;
                        m_options["-I"] = tmp;
                    } else
                    {
                        m_options["-I"] = inc;
                    }
                }
                    break;
                case 'D':
                    if (av[i][2] == '\0')
                    {
                        if (i < ac - 1 && av[i+1][0] != '-')
                        {
                            i++;
                            s = av[i];
                        } else
                        {
                            OString tmp("'-D', please check");
                            if (i <= ac - 1)
                            {
                                tmp += " your input '" + OString(av[i+1]) + "'";
                            }

                            throw IllegalArgument(tmp);
                        }
                    } else
                    {
                        s = av[i];
                    }

                    if (m_options.count("-D") > 0)
                    {
                        OString tmp(m_options["-D"]);
                        tmp = tmp + " " + s;
                        m_options["-D"] = tmp;
                    } else
                    {
                        m_options["-D"] = OString(s);
                    }
                    break;
                case 'C':
                    if (av[i][2] != '\0')
                    {
                        throw IllegalArgument(OString(av[i]) + ", please check your input");
                    }
                    if (m_options.count("-C") == 0)
                    {
                        m_options["-C"] = OString(s);
                    }
                    break;
                case 'h':
                case '?':
                    if (av[i][2] != '\0')
                    {
                        throw IllegalArgument(OString(av[i]) + ", please check your input");
                    } else
                    {
                        fprintf(stdout, "%s", prepareHelp().getStr());
                        exit(0);
                    }
                    break;
                default:
                    throw IllegalArgument("the option is unknown" + OString(av[i]));
                    break;
            }
        } else
        {
            if (av[i][0] == '@')
            {
                FILE* cmdFile = fopen(av[i]+1, "r");
                  if( cmdFile == NULL )
                  {
                    fprintf(stderr, "%s", prepareHelp().getStr());
                    ret = sal_False;
                } else
                {
                    int rargc=0;
                    char* rargv[512];
                    char  buffer[512];

                    while ( fscanf(cmdFile, "%s", buffer) != EOF )
                    {
                        rargv[rargc]= strdup(buffer);
                        rargc++;
                    }
                    fclose(cmdFile);

                    ret = initOptions(rargc, rargv, bCmdFile);

                    for (long i=0; i < rargc; i++)
                    {
                        free(rargv[i]);
                    }
                }
            } else
            {
                OString name(av[i]);
                name = name.toLowerCase();
                if ( name.lastIndexOf(".idl") != (name.getLength() - 4) )
                {
                    throw IllegalArgument("'" + OString(av[i]) +
                        "' is not a valid input file, only '*.idl' files will be accepted");
                }
                m_inputFiles.push_back(av[i]);
            }
        }
    }

    return ret;
}

OString Options::prepareHelp()
{
    OString help("\nusing: ");
    help += m_program + " [-options] file_1 ... file_n | @<filename>\n";
    help += "    file_n      = file_n specifies one or more idl files.\n";
    help += "                  Only files with the extension '.idl' are valid.\n";
    help += "    @<filename> = filename specifies the name of a command file.\n";
    help += "  Options:\n";
    help += "    -O<path>   = path describes the output directory.\n";
    help += "                 The generated output is a registry file with\n";
    help += "                 the same name as the idl input file.\n";
    help += "    -I<path>   = path specifies a directory where are include\n";
    help += "                 files will be searched by the preprocessor.\n";
    help += "                 Multible directories could be combined with ';'.\n";
    help += "    -D<name>   = name defines a macro for the preprocessor.\n";
    help += "    -C         = generate complete type information, including\n";
    help += "                 additional service information and documentation.\n";
    help += "    -h|-?      = print this help message and exit.\n";
    help += prepareVersion();

    return help;
}

OString Options::prepareVersion()
{
    OString version("\nSun Microsystems (R) ");
    version += m_program + " Version 1.0\n\n";
    return version;
}

const OString& Options::getProgramName() const
{
    return m_program;
}

sal_uInt16 Options::getNumberOfOptions() const
{
    return m_options.size();
}

sal_Bool Options::isValid(const OString& option)
{
    return (m_options.count(option) > 0);
}

const OString Options::getOption(const OString& option)
    throw( IllegalArgument )
{
    const OString ret;

    if (m_options.count(option) > 0)
    {
        return m_options[option];
    } else
    {
        throw IllegalArgument("Option is not valid or currently not set.");
    }

    return ret;
}

const OptionMap& Options::getOptions()
{
    return m_options;
}

sal_uInt16 Options::getNumberOfInputFiles() const
{
    return m_inputFiles.size();
}

const OString Options::getInputFile(sal_uInt16 index)
    throw( IllegalArgument )
{
    const OString ret;

    if (index < m_inputFiles.size())
    {
        return m_inputFiles[index];
    } else
    {
        throw IllegalArgument("index is out of bound.");
    }

    return ret;
}

const StringVector& Options::getInputFiles()
{
    return m_inputFiles;
}

<|endoftext|>


<commit_before>//
// Created by Miguel Rentes on 11/03/17.
//

#include "strings.h"

int main(void) {
    unsigned int n, q;
    string temp;
    vector<string> hrml;
    vector<string> queries;
    cin >> n >> q;
    cin.ignore();

    for(int i = 0; i < n; i++) {
        getline(cin, temp);
        hrml.push_back(temp);
    }

    for(int i = 0; i < q; i++) {
        getline(cin, temp);
        queries.push_back(temp);
    }

    map<string, string> m;
    vector<string> tag;

    for(int i = 0; i < n; i++) {
        temp = hrml[i];
        temp.erase(remove(temp.begin(), temp.end(), '\"'), temp.end());
        temp.erase(remove(temp.begin(), temp.end(), '>'), temp.end());

        if(temp.substr(0, 2) == "</") {
            tag.pop_back();
        }
        else {
            stringstream ss;
            ss.str("");
            ss << temp;
            string t1, p1, v1;
            char ch;
            ss >> ch >> t1 >> p1 >> ch >> v1;
            string temp1 = "";
            if(tag.size() > 0) {
                temp1 =* tag.rbegin();
                temp1 = temp1 + "." + t1;
            }
            else
                temp1 = t1;
            tag.push_back(temp1);
            m[*tag.rbegin() + "~" + p1] = v1;
            while(ss) {
                ss >> p1 >> ch >> v1;
                m[*tag.rbegin() + "~" + p1] = v1;
            }
        }
    }

    for(int i = 0; i < q; i++) {
        if (m.find(queries[i]) == m.end())
            cout << "Not Found!" << endl;
        else
            cout << m[queries[i]] << endl;
    }

    return EXIT_SUCCESS;
}
<commit_msg>Refactors solution for the Attribute Parser challenge.<commit_after>//
// Created by Miguel Rentes on 11/03/17.
//

#include "strings.h"

int main(void) {
    unsigned int n, q;
    string temp;
    vector<string> hrml;
    vector<string> queries;
    map<string, string> m;
    vector<string> tag;
    cin >> n >> q;
    cin.ignore();

    // inserts HRML input into hrml vector
    for(int i = 0; i < n; i++) {
        getline(cin, temp);
        hrml.push_back(temp);
    }

    // inserts queries input into queries vector
    for(int i = 0; i < q; i++) {
        getline(cin, temp);
        queries.push_back(temp);
    }

    for(int i = 0; i < n; i++) {
        temp = hrml[i];
        temp.erase(remove(temp.begin(), temp.end(), '\"'), temp.end());
        temp.erase(remove(temp.begin(), temp.end(), '>'), temp.end());

        if(temp.substr(0, 2) == "</") {
            tag.pop_back();
        }
        else {
            stringstream ss;
            ss.str("");
            ss << temp;
            string t1, p1, v1;
            char ch;
            ss >> ch >> t1 >> p1 >> ch >> v1;
            string temp1 = "";
            if(tag.size() > 0) {
                temp1 =* tag.rbegin();
                temp1 = temp1 + "." + t1;
            }
            else
                temp1 = t1;
            tag.push_back(temp1);
            m[*tag.rbegin() + "~" + p1] = v1;
            while(ss) {
                ss >> p1 >> ch >> v1;
                m[*tag.rbegin() + "~" + p1] = v1;
            }
        }
    }

    for(int i = 0; i < q; i++) {
        if (m.find(queries[i]) == m.end())
            cout << "Not Found!" << endl;
        else
            cout << m[queries[i]] << endl;
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <sys/types.h>
#include <signal.h>
#include <cstring>
#include <unistd.h>
#include <sys/time.h>

#include <vespa/defaults.h>
#include <vespa/log/log.h>
LOG_SETUP("config-sentinel");

#include <vespa/config-sentinel.h>

#include "config-handler.h"

using namespace config;

constexpr uint64_t CONFIG_TIMEOUT_MS = 3 * 60 * 1000;

static int sigPermanent(int sig, void(*handler)(int));

static void gracefulShutdown(int sig);
static void sigchldHandler(int sig);

sig_atomic_t stop = 0;
static sig_atomic_t pendingWait = 0;

int
main(int argc, char **argv)
{
    int c = getopt(argc, argv, "c:");
    if (c != 'c') {
        LOG(error, "Usage: %s -c <config-id>", argv[0]);
        EV_STOPPING("config-sentinel", "Bad arguments on command line");
        exit(EXIT_FAILURE);
    }

    const char *configId = strdup(optarg);

    const char *rootDir = getenv("ROOT");
    if (!rootDir) {
        rootDir = vespa::Defaults::vespaHome();
        LOG(warning, "ROOT is not set, using %s", rootDir);
        setenv("ROOT", rootDir, 1);
    }

    if (chdir(rootDir) == -1) {
        LOG(error, "Fatal: Cannot cd to $ROOT (%s)", rootDir);
        EV_STOPPING("config-sentinel", "Cannot cd to $ROOT");
        exit(EXIT_FAILURE);
    }

    EV_STARTED("config-sentinel");

    sigPermanent(SIGPIPE, SIG_IGN);
    sigPermanent(SIGTERM, gracefulShutdown);
    sigPermanent(SIGINT, gracefulShutdown);
    sigPermanent(SIGCHLD, sigchldHandler);
    if (setenv("LC_ALL", "C", 1) != 0) {
        LOG(error, "Unable to set locale");
        exit(EXIT_FAILURE);
    }
    setlocale(LC_ALL, "C");

    sentinel::ConfigHandler handler;

    LOG(debug, "Reading configuration");
    try {
        handler.subscribe(configId, CONFIG_TIMEOUT_MS);
    } catch (ConfigTimeoutException & ex) {
        LOG(info, "Timout getting config, please check your setup. Will exit and restart: %s", ex.getMessage().c_str());
        EV_STOPPING("config-sentinel", ex.what());
        exit(EXIT_FAILURE);
    } catch (InvalidConfigException& ex) {
        LOG(error, "Fatal: Invalid configuration, please check your setup: %s", ex.getMessage().c_str());
        EV_STOPPING("config-sentinel", ex.what());
        exit(EXIT_FAILURE);
    } catch (ConfigRuntimeException& ex) {
        LOG(error, "Fatal: Could not get config, please check your setup: %s", ex.getMessage().c_str());
        EV_STOPPING("config-sentinel", ex.what());
        exit(EXIT_FAILURE);
    }

    struct timeval lastTv;
    gettimeofday(&lastTv, nullptr);
    while (!stop) {
        try {
            pendingWait = 0;
            handler.doWork();       // Check for child procs & commands
        } catch (InvalidConfigException& ex) {
            LOG(warning, "Configuration problem: (ignoring): %s",
                ex.what());
        }
        if (!pendingWait) {
            int maxNum = 0;
            fd_set fds;
            FD_ZERO(&fds);
            handler.updateActiveFdset(&fds, &maxNum);

            struct timeval tv;
            tv.tv_sec = 1;
            tv.tv_usec = 0;

            if (!pendingWait) {
                select(maxNum, &fds, nullptr, nullptr, &tv);
            }
        }

        struct timeval tv;
        gettimeofday(&tv, nullptr);
        double delta = tv.tv_sec - lastTv.tv_sec
                       + 1e-6 * tv.tv_usec - lastTv.tv_usec;
        if (delta < 0.01) {
            usleep(12500); // Avoid busy looping;
        }
        lastTv = tv;
    }

    int rv = handler.terminate();

    EV_STOPPING("config-sentinel", "normal exit");
    return rv;
}

static void
gracefulShutdown(int sig)
{
    (void)sig;
    stop = 1;
}

static void
sigchldHandler(int sig)
{
    (void)sig;
    pendingWait = 1;
}

static int
sigPermanent(int sig, void(*handler)(int))
{
    struct sigaction sa;

    memset(&sa, 0, sizeof(sa));
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0; // no SA_RESTART!
    sa.sa_handler = handler;
    return sigaction(sig, &sa, nullptr);
}
<commit_msg>Awarning it is.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <sys/types.h>
#include <signal.h>
#include <cstring>
#include <unistd.h>
#include <sys/time.h>

#include <vespa/defaults.h>
#include <vespa/log/log.h>
LOG_SETUP("config-sentinel");

#include <vespa/config-sentinel.h>

#include "config-handler.h"

using namespace config;

constexpr uint64_t CONFIG_TIMEOUT_MS = 3 * 60 * 1000;

static int sigPermanent(int sig, void(*handler)(int));

static void gracefulShutdown(int sig);
static void sigchldHandler(int sig);

sig_atomic_t stop = 0;
static sig_atomic_t pendingWait = 0;

int
main(int argc, char **argv)
{
    int c = getopt(argc, argv, "c:");
    if (c != 'c') {
        LOG(error, "Usage: %s -c <config-id>", argv[0]);
        EV_STOPPING("config-sentinel", "Bad arguments on command line");
        exit(EXIT_FAILURE);
    }

    const char *configId = strdup(optarg);

    const char *rootDir = getenv("ROOT");
    if (!rootDir) {
        rootDir = vespa::Defaults::vespaHome();
        LOG(warning, "ROOT is not set, using %s", rootDir);
        setenv("ROOT", rootDir, 1);
    }

    if (chdir(rootDir) == -1) {
        LOG(error, "Fatal: Cannot cd to $ROOT (%s)", rootDir);
        EV_STOPPING("config-sentinel", "Cannot cd to $ROOT");
        exit(EXIT_FAILURE);
    }

    EV_STARTED("config-sentinel");

    sigPermanent(SIGPIPE, SIG_IGN);
    sigPermanent(SIGTERM, gracefulShutdown);
    sigPermanent(SIGINT, gracefulShutdown);
    sigPermanent(SIGCHLD, sigchldHandler);
    if (setenv("LC_ALL", "C", 1) != 0) {
        LOG(error, "Unable to set locale");
        exit(EXIT_FAILURE);
    }
    setlocale(LC_ALL, "C");

    sentinel::ConfigHandler handler;

    LOG(debug, "Reading configuration");
    try {
        handler.subscribe(configId, CONFIG_TIMEOUT_MS);
    } catch (ConfigTimeoutException & ex) {
        LOG(warning, "Timout getting config, please check your setup. Will exit and restart: %s", ex.getMessage().c_str());
        EV_STOPPING("config-sentinel", ex.what());
        exit(EXIT_FAILURE);
    } catch (InvalidConfigException& ex) {
        LOG(error, "Fatal: Invalid configuration, please check your setup: %s", ex.getMessage().c_str());
        EV_STOPPING("config-sentinel", ex.what());
        exit(EXIT_FAILURE);
    } catch (ConfigRuntimeException& ex) {
        LOG(error, "Fatal: Could not get config, please check your setup: %s", ex.getMessage().c_str());
        EV_STOPPING("config-sentinel", ex.what());
        exit(EXIT_FAILURE);
    }

    struct timeval lastTv;
    gettimeofday(&lastTv, nullptr);
    while (!stop) {
        try {
            pendingWait = 0;
            handler.doWork();       // Check for child procs & commands
        } catch (InvalidConfigException& ex) {
            LOG(warning, "Configuration problem: (ignoring): %s",
                ex.what());
        }
        if (!pendingWait) {
            int maxNum = 0;
            fd_set fds;
            FD_ZERO(&fds);
            handler.updateActiveFdset(&fds, &maxNum);

            struct timeval tv;
            tv.tv_sec = 1;
            tv.tv_usec = 0;

            if (!pendingWait) {
                select(maxNum, &fds, nullptr, nullptr, &tv);
            }
        }

        struct timeval tv;
        gettimeofday(&tv, nullptr);
        double delta = tv.tv_sec - lastTv.tv_sec
                       + 1e-6 * tv.tv_usec - lastTv.tv_usec;
        if (delta < 0.01) {
            usleep(12500); // Avoid busy looping;
        }
        lastTv = tv;
    }

    int rv = handler.terminate();

    EV_STOPPING("config-sentinel", "normal exit");
    return rv;
}

static void
gracefulShutdown(int sig)
{
    (void)sig;
    stop = 1;
}

static void
sigchldHandler(int sig)
{
    (void)sig;
    pendingWait = 1;
}

static int
sigPermanent(int sig, void(*handler)(int))
{
    struct sigaction sa;

    memset(&sa, 0, sizeof(sa));
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0; // no SA_RESTART!
    sa.sa_handler = handler;
    return sigaction(sig, &sa, nullptr);
}
<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2005-2007 Matthias Kretz <kretz@kde.org>

    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) version 3, or any
    later version accepted by the membership of KDE e.V. (or its
    successor approved by the membership of KDE e.V.), Nokia Corporation
    (or its successors, if any) and the KDE Free Qt Foundation, which shall
    act as a proxy defined in Section 6 of version 3 of the license.

    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, see <http://www.gnu.org/licenses/>.

*/

#include "videowidget.h"
#include "videowidget_p.h"
#include "videowidgetinterface.h"
#include "factory_p.h"
#include "phonondefs_p.h"
#include "phononnamespace_p.h"

#include <QtGui/QAction>
#define IFACES2 VideoWidgetInterface44
#define IFACES1 IFACES2
#define IFACES0 VideoWidgetInterface43, IFACES1
#define PHONON_INTERFACENAME IFACES0

QT_BEGIN_NAMESPACE

#ifndef QT_NO_PHONON_VIDEO

namespace Phonon
{

VideoWidget::VideoWidget(QWidget *parent)
    : QWidget(parent)
    , Phonon::AbstractVideoOutput(*new VideoWidgetPrivate(this))
{
    K_D(VideoWidget);
    d->init();
    d->createBackendObject();
    setMouseTracking(true);
}

VideoWidget::VideoWidget(VideoWidgetPrivate &dd, QWidget *parent)
    : QWidget(parent),
    Phonon::AbstractVideoOutput(dd)
{
    K_D(VideoWidget);
    d->init();
}

void VideoWidgetPrivate::init()
{
    Q_Q(VideoWidget);
    changeFlags = q->windowFlags() & (Qt::SubWindow | Qt::Window);
}

void VideoWidget::mouseMoveEvent(QMouseEvent *e)
{
    QWidget::mouseMoveEvent(e);
}

void VideoWidgetPrivate::createBackendObject()
{
    if (m_backendObject)
        return;
    Q_Q(VideoWidget);
    m_backendObject = Factory::createVideoWidget(q);
    if (m_backendObject) {
        setupBackendObject();
    }
}

#define PHONON_CLASSNAME VideoWidget

PHONON_INTERFACE_GETTER(Phonon::VideoWidget::AspectRatio, aspectRatio, d->aspectRatio)
PHONON_INTERFACE_SETTER(setAspectRatio, aspectRatio, Phonon::VideoWidget::AspectRatio)

PHONON_INTERFACE_GETTER(Phonon::VideoWidget::ScaleMode, scaleMode, d->scaleMode)
PHONON_INTERFACE_SETTER(setScaleMode, scaleMode, Phonon::VideoWidget::ScaleMode)

PHONON_INTERFACE_GETTER(qreal, brightness, d->brightness)
PHONON_INTERFACE_SETTER(setBrightness, brightness, qreal)

PHONON_INTERFACE_GETTER(qreal, contrast, d->contrast)
PHONON_INTERFACE_SETTER(setContrast, contrast, qreal)

PHONON_INTERFACE_GETTER(qreal, hue, d->hue)
PHONON_INTERFACE_SETTER(setHue, hue, qreal)

PHONON_INTERFACE_GETTER(qreal, saturation, d->saturation)
PHONON_INTERFACE_SETTER(setSaturation, saturation, qreal)

QImage VideoWidget::snapshot() const {
    Iface<VideoWidgetInterface44> iface((VideoWidgetPrivate*) (k_ptr));
    if(iface) return iface->snapshot();
    return QImage(); // TODO not implemented in VideoInterface
}

void VideoWidget::setFullScreen(bool newFullScreen)
{
    pDebug() << Q_FUNC_INFO << newFullScreen;
    K_D(VideoWidget);
    // TODO: disable screensaver? or should we leave that responsibility to the
    // application?
    Qt::WindowFlags flags = windowFlags();
    if (newFullScreen) {
        if (!isFullScreen()) {
            //we only update that value if it is not already fullscreen
            d->changeFlags = flags & (Qt::Window | Qt::SubWindow);
            flags |= Qt::Window;
            flags ^= Qt::SubWindow;
            setWindowFlags(flags);
#ifdef Q_WS_X11
            // This works around a bug with Compiz
            // as the window must be visible before we can set the state
            show();
            raise();
            setWindowState( windowState() | Qt::WindowFullScreen ); // set
#else
            setWindowState( windowState() | Qt::WindowFullScreen ); // set
            show();
#endif
        }
    } else if (isFullScreen()) {
        flags ^= (Qt::Window | Qt::SubWindow); //clear the flags...
        flags |= d->changeFlags; //then we reset the flags (window and subwindow)
        setWindowFlags(flags);
        setWindowState( windowState()  ^ Qt::WindowFullScreen ); // reset
        show();
    }
}

void VideoWidget::exitFullScreen()
{
    setFullScreen(false);
}

void VideoWidget::enterFullScreen()
{
    setFullScreen(true);
}

bool VideoWidgetPrivate::aboutToDeleteBackendObject()
{
    aspectRatio = pINTERFACE_CALL(aspectRatio());
    scaleMode = pINTERFACE_CALL(scaleMode());
    return AbstractVideoOutputPrivate::aboutToDeleteBackendObject();
}

void VideoWidgetPrivate::setupBackendObject()
{
    Q_Q(VideoWidget);
    Q_ASSERT(m_backendObject);
    //AbstractVideoOutputPrivate::setupBackendObject();
    pDebug() << "calling setAspectRatio on the backend " << aspectRatio;
    pINTERFACE_CALL(setAspectRatio(aspectRatio));
    pINTERFACE_CALL(setScaleMode(scaleMode));

    QWidget *w = pINTERFACE_CALL(widget());
    if (w) {
        layout.addWidget(w);
        q->setSizePolicy(w->sizePolicy());
        w->setMouseTracking(true);
    }
}

bool VideoWidget::event(QEvent *e)
{
    return QWidget::event(e);
}

} //namespace Phonon

#endif //QT_NO_PHONON_VIDEO

QT_END_NAMESPACE

#include "moc_videowidget.cpp"

#undef PHONON_CLASSNAME
// vim: sw=4 ts=4 tw=80
<commit_msg>Some other fixes<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2005-2007 Matthias Kretz <kretz@kde.org>

    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) version 3, or any
    later version accepted by the membership of KDE e.V. (or its
    successor approved by the membership of KDE e.V.), Nokia Corporation
    (or its successors, if any) and the KDE Free Qt Foundation, which shall
    act as a proxy defined in Section 6 of version 3 of the license.

    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, see <http://www.gnu.org/licenses/>.

*/

#include "videowidget.h"
#include "videowidget_p.h"
#include "videowidgetinterface.h"
#include "factory_p.h"
#include "phonondefs_p.h"
#include "phononnamespace_p.h"

#include <QtGui/QAction>
#define IFACES4 VideoWidgetInterface44
#define IFACES0 VideoWidgetInterface43, IFACES4
#define PHONON_INTERFACENAME IFACES0

QT_BEGIN_NAMESPACE

#ifndef QT_NO_PHONON_VIDEO

namespace Phonon
{

VideoWidget::VideoWidget(QWidget *parent)
    : QWidget(parent)
    , Phonon::AbstractVideoOutput(*new VideoWidgetPrivate(this))
{
    K_D(VideoWidget);
    d->init();
    d->createBackendObject();
    setMouseTracking(true);
}

VideoWidget::VideoWidget(VideoWidgetPrivate &dd, QWidget *parent)
    : QWidget(parent),
    Phonon::AbstractVideoOutput(dd)
{
    K_D(VideoWidget);
    d->init();
}

void VideoWidgetPrivate::init()
{
    Q_Q(VideoWidget);
    changeFlags = q->windowFlags() & (Qt::SubWindow | Qt::Window);
}

void VideoWidget::mouseMoveEvent(QMouseEvent *e)
{
    QWidget::mouseMoveEvent(e);
}

void VideoWidgetPrivate::createBackendObject()
{
    if (m_backendObject)
        return;
    Q_Q(VideoWidget);
    m_backendObject = Factory::createVideoWidget(q);
    if (m_backendObject) {
        setupBackendObject();
    }
}

#define PHONON_CLASSNAME VideoWidget

PHONON_INTERFACE_GETTER(Phonon::VideoWidget::AspectRatio, aspectRatio, d->aspectRatio)
PHONON_INTERFACE_SETTER(setAspectRatio, aspectRatio, Phonon::VideoWidget::AspectRatio)

PHONON_INTERFACE_GETTER(Phonon::VideoWidget::ScaleMode, scaleMode, d->scaleMode)
PHONON_INTERFACE_SETTER(setScaleMode, scaleMode, Phonon::VideoWidget::ScaleMode)

PHONON_INTERFACE_GETTER(qreal, brightness, d->brightness)
PHONON_INTERFACE_SETTER(setBrightness, brightness, qreal)

PHONON_INTERFACE_GETTER(qreal, contrast, d->contrast)
PHONON_INTERFACE_SETTER(setContrast, contrast, qreal)

PHONON_INTERFACE_GETTER(qreal, hue, d->hue)
PHONON_INTERFACE_SETTER(setHue, hue, qreal)

PHONON_INTERFACE_GETTER(qreal, saturation, d->saturation)
PHONON_INTERFACE_SETTER(setSaturation, saturation, qreal)

QImage VideoWidget::snapshot() const {
    K_D(const VideoWidget);
    ConstIface<IFACES4> iface(d);
    if(iface) return iface->snapshot();
    return QImage(); // TODO not implemented in VideoInterface
}

void VideoWidget::setFullScreen(bool newFullScreen)
{
    pDebug() << Q_FUNC_INFO << newFullScreen;
    K_D(VideoWidget);
    // TODO: disable screensaver? or should we leave that responsibility to the
    // application?
    Qt::WindowFlags flags = windowFlags();
    if (newFullScreen) {
        if (!isFullScreen()) {
            //we only update that value if it is not already fullscreen
            d->changeFlags = flags & (Qt::Window | Qt::SubWindow);
            flags |= Qt::Window;
            flags ^= Qt::SubWindow;
            setWindowFlags(flags);
#ifdef Q_WS_X11
            // This works around a bug with Compiz
            // as the window must be visible before we can set the state
            show();
            raise();
            setWindowState( windowState() | Qt::WindowFullScreen ); // set
#else
            setWindowState( windowState() | Qt::WindowFullScreen ); // set
            show();
#endif
        }
    } else if (isFullScreen()) {
        flags ^= (Qt::Window | Qt::SubWindow); //clear the flags...
        flags |= d->changeFlags; //then we reset the flags (window and subwindow)
        setWindowFlags(flags);
        setWindowState( windowState()  ^ Qt::WindowFullScreen ); // reset
        show();
    }
}

void VideoWidget::exitFullScreen()
{
    setFullScreen(false);
}

void VideoWidget::enterFullScreen()
{
    setFullScreen(true);
}

bool VideoWidgetPrivate::aboutToDeleteBackendObject()
{
    aspectRatio = pINTERFACE_CALL(aspectRatio());
    scaleMode = pINTERFACE_CALL(scaleMode());
    return AbstractVideoOutputPrivate::aboutToDeleteBackendObject();
}

void VideoWidgetPrivate::setupBackendObject()
{
    Q_Q(VideoWidget);
    Q_ASSERT(m_backendObject);
    //AbstractVideoOutputPrivate::setupBackendObject();
    pDebug() << "calling setAspectRatio on the backend " << aspectRatio;
    pINTERFACE_CALL(setAspectRatio(aspectRatio));
    pINTERFACE_CALL(setScaleMode(scaleMode));

    QWidget *w = pINTERFACE_CALL(widget());
    if (w) {
        layout.addWidget(w);
        q->setSizePolicy(w->sizePolicy());
        w->setMouseTracking(true);
    }
}

bool VideoWidget::event(QEvent *e)
{
    return QWidget::event(e);
}

} //namespace Phonon

#endif //QT_NO_PHONON_VIDEO

QT_END_NAMESPACE

#include "moc_videowidget.cpp"

#undef PHONON_CLASSNAME
// vim: sw=4 ts=4 tw=80
<|endoftext|>


<commit_before>#include "mpi_common.h"
#include "dynamical.h"
#include "kpoint.h"
#include "fcs_phonon.h"
#include "system.h"
#include "memory.h"
#include "error.h"
#include "phonons.h"
#include "../alm_c++/constants.h"
#include <string>
#include <iomanip>
#include <fstream>
#include <algorithm>

#ifdef _USE_BOOST
#include <boost/lexical_cast.hpp>
#endif

using namespace PHON_NS;

Fcs_phonon::Fcs_phonon(PHON *phon): Pointers(phon) {
    maxorder = 2;
}

Fcs_phonon::~Fcs_phonon(){}

void Fcs_phonon::setup(std::string mode)
{
    unsigned int nat = system->nat;
    unsigned int natmin = system->natmin;
    memory->allocate(fc2, natmin, nat, 3, 3);

    unsigned int i, j, icrd, jcrd;
    for (i = 0; i < natmin; ++i){
        for (j = 0; j < nat; ++j){
            for (icrd = 0; icrd < 3; ++icrd){
                for (jcrd = 0; jcrd < 3; ++jcrd){
                    fc2[i][j][icrd][jcrd] = 0.0;
                }
            }
        }
    }

    if (mympi->my_rank == 0) load_fc2();
    // This is not necessary
    MPI_Bcast(&fc2[0][0][0][0], 9*natmin*nat, MPI_DOUBLE, 0, MPI_COMM_WORLD);

    if (mode == "boltzmann" || mode == "gruneisen"){
        memory->allocate(force_constant, 2);

        if (mympi->my_rank == 0) load_fcs();

        MPI_Bcast_fc_class(2);

        if (mympi->my_rank == 0) {
            for (i = 0; i < maxorder; ++i){
                std::cout << "Number of non-zero IFCs for " << i + 2 << " order: ";
                std::cout << force_constant[i].size() << std::endl;
            }
        }
    }
}

void Fcs_phonon::load_fc2()
{
    unsigned int i, icrd, jcrd;
    unsigned int iat, jat;
    unsigned int inatmin;

    unsigned int len1, len2;

    std::string str_tmp, str1, str2;
    std::ifstream ifs_fcs;
    unsigned int nfc2;
    double fc2_tmp;

    ifs_fcs.open(file_fcs.c_str(), std::ios::in);

    while(!ifs_fcs.eof())
    {
        std::getline(ifs_fcs, str_tmp);
        if(str_tmp == "#FCS_HARMONIC"){
            ifs_fcs >> nfc2;
            ifs_fcs.ignore();
            std::getline(ifs_fcs, str_tmp);

            for (i = 0; i < nfc2; ++i){

                ifs_fcs >> fc2_tmp;

                ifs_fcs >> str1 >> str2;
                len1 = str1.size();
                len2 = str2.size();

                iat = atoi(str1.substr(0, len1 - 1).c_str()) - 1;
                jat = atoi(str2.substr(0, len2 - 1).c_str()) - 1;
                icrd = coordinate_index(str1[len1 - 1]);
                jcrd = coordinate_index(str2[len2 - 1]);

                inatmin = system->map_s2p[iat].atom_num;
                fc2[inatmin][jat][icrd][jcrd] = fc2_tmp;
            }
        }
    }
    ifs_fcs.close();
}

void Fcs_phonon::load_fcs()
{
    unsigned int i, iorder;
    unsigned int ifcs, nfcs;

    double val;

    unsigned int atmn, xyz;
    std::string str_int;
    unsigned int len;
    unsigned int *ind;

    Triplet tri_tmp;
    std::vector<unsigned int> ivec;
    std::vector<Triplet> tri_vec;

    bool flag_found;
    std::ifstream ifs_fcs;
    std::string str_tmp;
    std::string *flag_str;

    std::cout << "Reading harmonic and anharmonic force constants from the info file..." << std::endl;

    memory->allocate(flag_str, maxorder);
    ifs_fcs.open(file_fcs.c_str(), std::ios::in);

    memory->allocate(ind, maxorder + 1);

    for (iorder = 0; iorder < maxorder; ++iorder){

        ifs_fcs.clear();
        ifs_fcs.seekg(0, std::ios_base::beg);

        if (iorder == 0) {
            flag_str[iorder] = "#FCS_HARMONIC";
        } else {
#ifdef _USE_BOOST
            flag_str[iorder] = "#FCS_ANHARM" + boost::lexical_cast<std::string>(iorder + 2);
#else
			flag_str[iorder] = "#FCS_ANHARM" + std::to_string(iorder + 2);
#endif
        }

        flag_found = false;

        while(!ifs_fcs.eof() && !flag_found)
        {
            std::getline(ifs_fcs, str_tmp);
            if (str_tmp == flag_str[iorder]) {

                flag_found = true;
                ifs_fcs >> nfcs;
                ifs_fcs.ignore();
                std::getline(ifs_fcs,str_tmp);

                for (ifcs = 0; ifcs < nfcs; ++ifcs){

                    ifs_fcs >> val;
                    ivec.clear();

                    for (i = 0; i < iorder + 2; ++i){
                        ifs_fcs >> str_int;
                        len = str_int.size();
                        atmn = atoi(str_int.substr(0, len - 1).c_str()) - 1;
                        xyz = coordinate_index(str_int[len - 1]);
                        ivec.push_back(3 * atmn + xyz);
                    }

                    if (std::abs(val) > eps) {
                        do {
                            tri_vec.clear();

                            for (i = 0; i < iorder + 2; ++i){
                                tri_tmp.atom = system->map_s2p[ivec[i] / 3].atom_num;
                                tri_tmp.cell = system->map_s2p[ivec[i] / 3].tran_num;
                                tri_tmp.xyz  = ivec[i] % 3;

                                tri_vec.push_back(tri_tmp);
                            }

                            force_constant[iorder].push_back(FcsClass(val, tri_vec));

                        } while (std::next_permutation(ivec.begin() + 1, ivec.end()));
                    }
                }
            }
        }

        if (!flag_found){
            str_tmp = flag_str[iorder] + " flag not found in the info file";
            error->exit("load_fcs", str_tmp.c_str());
        }
    }

    ifs_fcs.close();

    memory->deallocate(ind);
    std::cout << "Done !" << std::endl;

}

unsigned int Fcs_phonon::coordinate_index(const char char_coord)
{
    unsigned int m;
    if(char_coord == 'x'){
        m = 0;
    } else if (char_coord == 'y'){
        m = 1;
    } else if (char_coord == 'z'){
        m = 2;
    } else {
        error->exit("coordinate_index", "invalid char_coord", char_coord);
    }
    return m;
}

void Fcs_phonon::MPI_Bcast_fc_class(const unsigned int N)
{
    unsigned int i;
    int j, k;
    int nelem;
    double *fcs_tmp;
    unsigned int ***ind;

    Triplet tri_tmp;
    std::vector<Triplet> tri_vec;

    for (i = 0; i < N; ++i){
        int len = force_constant[i].size();
        nelem = i + 2;

        MPI_Bcast(&len, 1, MPI_INT, 0, MPI_COMM_WORLD);

        memory->allocate(fcs_tmp, len);
        memory->allocate(ind, len, nelem, 3);

        if (mympi->my_rank == 0) {
            for (j = 0; j < len; ++j){
                fcs_tmp[j] = force_constant[i][j].fcs_val;
                for (k = 0; k < nelem; ++k){
                    ind[j][k][0] = force_constant[i][j].elems[k].atom;
                    ind[j][k][1] = force_constant[i][j].elems[k].cell;
                    ind[j][k][2] = force_constant[i][j].elems[k].xyz;
                }
            }
        }

        MPI_Bcast(&fcs_tmp[0], len, MPI_DOUBLE, 0, MPI_COMM_WORLD);
        MPI_Bcast(&ind[0][0][0], 3*nelem*len, MPI_UNSIGNED, 0, MPI_COMM_WORLD);

        if (mympi->my_rank > 0) {
            force_constant[i].clear();

            for (j = 0; j < len; ++j){

                tri_vec.clear();

                for (k = 0; k < nelem; ++k){
                    tri_tmp.atom = ind[j][k][0];
                    tri_tmp.cell = ind[j][k][1];
                    tri_tmp.xyz  = ind[j][k][2];

                    tri_vec.push_back(tri_tmp);
                }
                force_constant[i].push_back(FcsClass(fcs_tmp[j], tri_vec));
            }
        }

        memory->deallocate(fcs_tmp);
        memory->deallocate(ind);
    }
}
<commit_msg>to_string method was replaced by a stringstream method.<commit_after>#include "mpi_common.h"
#include "dynamical.h"
#include "kpoint.h"
#include "fcs_phonon.h"
#include "system.h"
#include "memory.h"
#include "error.h"
#include "phonons.h"
#include "../alm_c++/constants.h"
#include <string>
#include <iomanip>
#include <fstream>
#include <algorithm>

#ifdef _USE_BOOST
#include <boost/lexical_cast.hpp>
#endif

using namespace PHON_NS;

Fcs_phonon::Fcs_phonon(PHON *phon): Pointers(phon) {
    maxorder = 2;
}

Fcs_phonon::~Fcs_phonon(){}

void Fcs_phonon::setup(std::string mode)
{
    unsigned int nat = system->nat;
    unsigned int natmin = system->natmin;
    memory->allocate(fc2, natmin, nat, 3, 3);

    unsigned int i, j, icrd, jcrd;
    for (i = 0; i < natmin; ++i){
        for (j = 0; j < nat; ++j){
            for (icrd = 0; icrd < 3; ++icrd){
                for (jcrd = 0; jcrd < 3; ++jcrd){
                    fc2[i][j][icrd][jcrd] = 0.0;
                }
            }
        }
    }

    if (mympi->my_rank == 0) load_fc2();
    // This is not necessary
    MPI_Bcast(&fc2[0][0][0][0], 9*natmin*nat, MPI_DOUBLE, 0, MPI_COMM_WORLD);

    if (mode == "boltzmann" || mode == "gruneisen"){
        memory->allocate(force_constant, 2);

        if (mympi->my_rank == 0) load_fcs();

        MPI_Bcast_fc_class(2);

        if (mympi->my_rank == 0) {
            for (i = 0; i < maxorder; ++i){
                std::cout << "Number of non-zero IFCs for " << i + 2 << " order: ";
                std::cout << force_constant[i].size() << std::endl;
            }
        }
    }
}

void Fcs_phonon::load_fc2()
{
    unsigned int i, icrd, jcrd;
    unsigned int iat, jat;
    unsigned int inatmin;

    unsigned int len1, len2;

    std::string str_tmp, str1, str2;
    std::ifstream ifs_fcs;
    unsigned int nfc2;
    double fc2_tmp;

    ifs_fcs.open(file_fcs.c_str(), std::ios::in);

    while(!ifs_fcs.eof())
    {
        std::getline(ifs_fcs, str_tmp);
        if(str_tmp == "#FCS_HARMONIC"){
            ifs_fcs >> nfc2;
            ifs_fcs.ignore();
            std::getline(ifs_fcs, str_tmp);

            for (i = 0; i < nfc2; ++i){

                ifs_fcs >> fc2_tmp;

                ifs_fcs >> str1 >> str2;
                len1 = str1.size();
                len2 = str2.size();

                iat = atoi(str1.substr(0, len1 - 1).c_str()) - 1;
                jat = atoi(str2.substr(0, len2 - 1).c_str()) - 1;
                icrd = coordinate_index(str1[len1 - 1]);
                jcrd = coordinate_index(str2[len2 - 1]);

                inatmin = system->map_s2p[iat].atom_num;
                fc2[inatmin][jat][icrd][jcrd] = fc2_tmp;
            }
        }
    }
    ifs_fcs.close();
}

void Fcs_phonon::load_fcs()
{
    unsigned int i, iorder;
    unsigned int ifcs, nfcs;

    double val;

    unsigned int atmn, xyz;
    std::string str_int;
    unsigned int len;
    unsigned int *ind;

    Triplet tri_tmp;
    std::vector<unsigned int> ivec;
    std::vector<Triplet> tri_vec;

    bool flag_found;
    std::ifstream ifs_fcs;
    std::string str_tmp;
    std::string *flag_str;

    std::cout << "Reading harmonic and anharmonic force constants from the info file..." << std::endl;

    memory->allocate(flag_str, maxorder);
    ifs_fcs.open(file_fcs.c_str(), std::ios::in);

    memory->allocate(ind, maxorder + 1);

    for (iorder = 0; iorder < maxorder; ++iorder){

        ifs_fcs.clear();
        ifs_fcs.seekg(0, std::ios_base::beg);

        if (iorder == 0) {
            flag_str[iorder] = "#FCS_HARMONIC";
        } else {
#ifdef _USE_BOOST
            flag_str[iorder] = "#FCS_ANHARM" + boost::lexical_cast<std::string>(iorder + 2);
#else
			std::stringstream ss_tmp;
			ss_tmp << iorder + 2;
			flag_str[iorder] = "#FCS_ANHARM" + ss_tmp.str();
#endif
        }

        flag_found = false;

        while(!ifs_fcs.eof() && !flag_found)
        {
            std::getline(ifs_fcs, str_tmp);
            if (str_tmp == flag_str[iorder]) {

                flag_found = true;
                ifs_fcs >> nfcs;
                ifs_fcs.ignore();
                std::getline(ifs_fcs,str_tmp);

                for (ifcs = 0; ifcs < nfcs; ++ifcs){

                    ifs_fcs >> val;
                    ivec.clear();

                    for (i = 0; i < iorder + 2; ++i){
                        ifs_fcs >> str_int;
                        len = str_int.size();
                        atmn = atoi(str_int.substr(0, len - 1).c_str()) - 1;
                        xyz = coordinate_index(str_int[len - 1]);
                        ivec.push_back(3 * atmn + xyz);
                    }

                    if (std::abs(val) > eps) {
                        do {
                            tri_vec.clear();

                            for (i = 0; i < iorder + 2; ++i){
                                tri_tmp.atom = system->map_s2p[ivec[i] / 3].atom_num;
                                tri_tmp.cell = system->map_s2p[ivec[i] / 3].tran_num;
                                tri_tmp.xyz  = ivec[i] % 3;

                                tri_vec.push_back(tri_tmp);
                            }

                            force_constant[iorder].push_back(FcsClass(val, tri_vec));

                        } while (std::next_permutation(ivec.begin() + 1, ivec.end()));
                    }
                }
            }
        }

        if (!flag_found){
            str_tmp = flag_str[iorder] + " flag not found in the info file";
            error->exit("load_fcs", str_tmp.c_str());
        }
    }

    ifs_fcs.close();

    memory->deallocate(ind);
    std::cout << "Done !" << std::endl;

}

unsigned int Fcs_phonon::coordinate_index(const char char_coord)
{
    unsigned int m;
    if(char_coord == 'x'){
        m = 0;
    } else if (char_coord == 'y'){
        m = 1;
    } else if (char_coord == 'z'){
        m = 2;
    } else {
        error->exit("coordinate_index", "invalid char_coord", char_coord);
    }
    return m;
}

void Fcs_phonon::MPI_Bcast_fc_class(const unsigned int N)
{
    unsigned int i;
    int j, k;
    int nelem;
    double *fcs_tmp;
    unsigned int ***ind;

    Triplet tri_tmp;
    std::vector<Triplet> tri_vec;

    for (i = 0; i < N; ++i){
        int len = force_constant[i].size();
        nelem = i + 2;

        MPI_Bcast(&len, 1, MPI_INT, 0, MPI_COMM_WORLD);

        memory->allocate(fcs_tmp, len);
        memory->allocate(ind, len, nelem, 3);

        if (mympi->my_rank == 0) {
            for (j = 0; j < len; ++j){
                fcs_tmp[j] = force_constant[i][j].fcs_val;
                for (k = 0; k < nelem; ++k){
                    ind[j][k][0] = force_constant[i][j].elems[k].atom;
                    ind[j][k][1] = force_constant[i][j].elems[k].cell;
                    ind[j][k][2] = force_constant[i][j].elems[k].xyz;
                }
            }
        }

        MPI_Bcast(&fcs_tmp[0], len, MPI_DOUBLE, 0, MPI_COMM_WORLD);
        MPI_Bcast(&ind[0][0][0], 3*nelem*len, MPI_UNSIGNED, 0, MPI_COMM_WORLD);

        if (mympi->my_rank > 0) {
            force_constant[i].clear();

            for (j = 0; j < len; ++j){

                tri_vec.clear();

                for (k = 0; k < nelem; ++k){
                    tri_tmp.atom = ind[j][k][0];
                    tri_tmp.cell = ind[j][k][1];
                    tri_tmp.xyz  = ind[j][k][2];

                    tri_vec.push_back(tri_tmp);
                }
                force_constant[i].push_back(FcsClass(fcs_tmp[j], tri_vec));
            }
        }

        memory->deallocate(fcs_tmp);
        memory->deallocate(ind);
    }
}
<|endoftext|>


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

#include <sampgdk/a_players.h>
#include <sampgdk/a_samp.h>
#include <sampgdk/core.h>
#include <sampgdk/sdk.h>

using sampgdk::logprintf;

void SAMPGDK_CALL PrintTickCountTimer(int timerid, void *params) {
  logprintf("Tick count: %d", GetTickCount());
}

PLUGIN_EXPORT bool PLUGIN_CALL OnGameModeInit() {
  SetGameModeText("Hello, World!");
  AddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f, 0, 0, 0, 0, 0, 0);
  SetTimer(1000, true, PrintTickCountTimer, 0);
  return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) {
  SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the HelloWorld server!");
  return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestClass(int playerid, int classid) {
  SetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
  SetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
  SetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f, CAMERA_CUT);
  return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerCommandText(int playerid, const char *cmdtext) {
  if (strcmp(cmdtext, "/hello") == 0) {
    char name[MAX_PLAYER_NAME];
    GetPlayerName(playerid, name, sizeof(name));
    char message[MAX_CLIENT_MESSAGE];
    sprintf(message, "Hello, %s!", name);
    SendClientMessage(playerid, 0x00FF00FF, message);
    return true;
  }
  return false;
}

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
  return sampgdk::Supports() | SUPPORTS_PROCESS_TICK;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
  return sampgdk::Load(ppData);
}

PLUGIN_EXPORT void PLUGIN_CALL Unload() {
  sampgdk::Unload();
}

PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() {
  sampgdk::ProcessTick();
}
<commit_msg>Limit code to 80 columns in helloworld<commit_after>#include <stdio.h>
#include <string.h>

#include <sampgdk/a_players.h>
#include <sampgdk/a_samp.h>
#include <sampgdk/core.h>
#include <sampgdk/sdk.h>

using sampgdk::logprintf;

void SAMPGDK_CALL PrintTickCountTimer(int timerid, void *params) {
  logprintf("Tick count: %d", GetTickCount());
}

PLUGIN_EXPORT bool PLUGIN_CALL OnGameModeInit() {
  SetGameModeText("Hello, World!");
  AddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f,
                 0, 0, 0, 0, 0, 0);
  SetTimer(1000, true, PrintTickCountTimer, 0);
  return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) {
  SendClientMessage(playerid, 0xFFFFFFFF, "Welcome to the HelloWorld server!");
  return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestClass(int playerid,
                                                    int classid) {
  SetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
  SetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);
  SetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f,
                        CAMERA_CUT);
  return true;
}

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerCommandText(int playerid,
                                                   const char *cmdtext) {
  if (strcmp(cmdtext, "/hello") == 0) {
    char name[MAX_PLAYER_NAME];
    GetPlayerName(playerid, name, sizeof(name));
    char message[MAX_CLIENT_MESSAGE];
    sprintf(message, "Hello, %s!", name);
    SendClientMessage(playerid, 0x00FF00FF, message);
    return true;
  }
  return false;
}

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
  return sampgdk::Supports() | SUPPORTS_PROCESS_TICK;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
  return sampgdk::Load(ppData);
}

PLUGIN_EXPORT void PLUGIN_CALL Unload() {
  sampgdk::Unload();
}

PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() {
  sampgdk::ProcessTick();
}
<|endoftext|>


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

#ifndef _CONNECTIVITY_ADO_INDEX_HXX_
#define _CONNECTIVITY_ADO_INDEX_HXX_

#ifndef _CONNECTIVITY_SDBCX_INDEX_HXX_
#include "connectivity/sdbcx/VIndex.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _CONNECTIVITY_ADO_AWRAPADOX_HXX_
#include "ado/Awrapadox.hxx"
#endif

namespace connectivity
{
    namespace ado
    {
        typedef sdbcx::OIndex OIndex_ADO;

        class OConnection;
        class OAdoIndex :    public OIndex_ADO
        {
            WpADOIndex      m_aIndex;
            OConnection*    m_pConnection;
        protected:
            void fillPropertyValues();
            virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const ::com::sun::star::uno::Any& rValue)throw (::com::sun::star::uno::Exception);
        public:
            virtual void refreshColumns();
        public:
            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();
            OAdoIndex(sal_Bool _bCase,  OConnection* _pConnection,ADOIndex* _pIndex);
            OAdoIndex(sal_Bool _bCase,  OConnection* _pConnection);
            // com::sun::star::lang::XUnoTunnel
            virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();

            WpADOIndex      getImpl() const { return m_aIndex;}
        };
    }
}
#endif // _CONNECTIVITY_ADO_INDEX_HXX_

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

#ifndef _CONNECTIVITY_ADO_INDEX_HXX_
#define _CONNECTIVITY_ADO_INDEX_HXX_

#include "connectivity/sdbcx/VIndex.hxx"
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#include "ado/Awrapadox.hxx"

namespace connectivity
{
    namespace ado
    {
        typedef sdbcx::OIndex OIndex_ADO;

        class OConnection;
        class OAdoIndex :    public OIndex_ADO
        {
            WpADOIndex      m_aIndex;
            OConnection*    m_pConnection;
        protected:
            void fillPropertyValues();
            virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const ::com::sun::star::uno::Any& rValue)throw (::com::sun::star::uno::Exception);
        public:
            virtual void refreshColumns();
        public:
            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();
            OAdoIndex(sal_Bool _bCase,  OConnection* _pConnection,ADOIndex* _pIndex);
            OAdoIndex(sal_Bool _bCase,  OConnection* _pConnection);
            // com::sun::star::lang::XUnoTunnel
            virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();

            WpADOIndex      getImpl() const { return m_aIndex;}
        };
    }
}
#endif // _CONNECTIVITY_ADO_INDEX_HXX_

<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/tracer.hpp"
#include <new>

#include "sqlite3.h"

using namespace flusspferd;

// Put everything in an anon-namespace so typeid wont clash ever.
namespace {

void raise_sqlite_error(sqlite3* db);

///////////////////////////
// Classes
///////////////////////////

class sqlite3 : public native_object_base {
public:
  struct class_info : public flusspferd::class_info {
    static char const *full_name() { return "SQLite3"; }
    typedef boost::mpl::bool_<true> constructible;
    static char const *constructor_name() { return "SQLite3"; }
    static void augment_constructor(object &ctor);
    static object create_prototype();
  };

  sqlite3(object const &obj, call_context &x);
  ~sqlite3();

protected:
  //void trace(tracer &);

private: // JS methods
  ::sqlite3 *db;

  void close();
  void cursor(call_context &x);
};

class sqlite3_cursor : public native_object_base {
public:
  struct class_info : public flusspferd::class_info {
    typedef boost::mpl::bool_<false> constructible;
    static char const *full_name() { return "SQLite3.Cursor"; }
    static char const* constructor_name() { return "Cursor"; }
    static object create_prototype();
  };

  sqlite3_cursor(object const &obj, sqlite3_stmt *sth);
  ~sqlite3_cursor();

private:
  sqlite3_stmt *sth;

  // Methods that help wiht binding
  void bind_array(array &a, size_t num_binds);
  void bind_dict(object &o, size_t num_binds);
  void do_bind_param(int n, value v);

private: // JS methods
  void finish();
  void reset();
  object next();
  void bind(call_context &x);
};

///////////////////////////
// import hook
extern "C" value flusspferd_load(object container)
{
  return load_class<sqlite3>(container);
}

///////////////////////////
// Set version properties on constructor object
void sqlite3::class_info::augment_constructor(object &ctor)
{
  // Set static properties on the constructor
  ctor.define_property("version", SQLITE_VERSION_NUMBER,
      object::read_only_property | object::permanent_property);
  ctor.define_property("versionStr", string(SQLITE_VERSION),
      object::read_only_property | object::permanent_property);

  load_class<sqlite3_cursor>(ctor);
}

///////////////////////////
object sqlite3::class_info::create_prototype()
{
  object proto = create_object();

  create_native_method(proto, "cursor", 1);
  create_native_method(proto, "close", 0);
  return proto;
}

///////////////////////////
sqlite3::sqlite3(object const &obj, call_context &x)
  : native_object_base(obj),
    db(NULL)
{
  if (x.arg.size() == 0)
    throw exception ("SQLite3 requires more than 0 arguments");

  string dsn = x.arg[0];

  // TODO: pull arguments from 2nd/options argument
  if (sqlite3_open(dsn.c_str(), &db) != SQLITE_OK) {
    if (db)
      raise_sqlite_error(db);
    else
      throw std::bad_alloc(); // out of memory. better way to signal this?
  }

  register_native_method("cursor", &sqlite3::cursor);
  register_native_method("close", &sqlite3::close);
}
///////////////////////////
sqlite3::~sqlite3()
{
  close();
}

///////////////////////////
void sqlite3::close()
{
  if (db) {
    sqlite3_close(db);
    db = NULL;
  }
}

///////////////////////////
void sqlite3::cursor(call_context &x) {
  local_root_scope scope;
  if (!db)
    throw exception("SQLite3.cursor called on closed dbh");

  if (x.arg.size() < 1)
    throw exception ("cursor requires more than 0 arguments");

  string sql = x.arg[0].to_string();
  size_t n_bytes = sql.length() * 2;
  sqlite3_stmt *sth;
  char16_t *tail; // uncompiled part of the sql (when multiple stmts)
  if (sqlite3_prepare16_v2(db, sql.data(), n_bytes, &sth, (const void**)&tail) != SQLITE_OK)
  {
    raise_sqlite_error(db);
  }
  object cursor = create_native_object<sqlite3_cursor>(object(), sth);

  // TODO: remove tail and set it seperately
  cursor.define_property("sql", sql);

  x.result = cursor;
}

///////////////////////////
object sqlite3_cursor::class_info::create_prototype() {
  object proto = create_object();

  create_native_method(proto, "finish", 0);
  create_native_method(proto, "reset", 0);
  create_native_method(proto, "next", 0);
  create_native_method(proto, "bind", 0);

  return proto;
}

///////////////////////////
// 'Private' constructor that is called from sqlite3::cursor
sqlite3_cursor::sqlite3_cursor(object const &obj, sqlite3_stmt *_sth)
  : native_object_base(obj),
    sth(_sth)
{
  register_native_method("finish", &sqlite3_cursor::finish);
  register_native_method("reset", &sqlite3_cursor::reset);
  register_native_method("next", &sqlite3_cursor::next);
  register_native_method("bind", &sqlite3_cursor::bind);
}

///////////////////////////
sqlite3_cursor::~sqlite3_cursor()
{
  finish();
}

///////////////////////////
void sqlite3_cursor::finish() {
  if (sth) {
    sqlite3_finalize(sth);
    sth = NULL;
  }
}

///////////////////////////
void sqlite3_cursor::reset() {
}

///////////////////////////
object sqlite3_cursor::next() {
  return object();
}

///////////////////////////
// JS method
void sqlite3_cursor::bind(call_context &x) {
  local_root_scope scope;

  size_t num_binds = sqlite3_bind_parameter_count(sth);

  if (!num_binds)
    return;

  if (x.arg[0].is_object()) {
    object o = x.arg[0].get_object();

    if (o.is_array()) {
      array a = o;
      bind_array(a, num_binds);
    }
    else
      bind_dict(o, num_binds);
  } else if (num_binds == 1) {
    // Dont document that we accept a single param
    do_bind_param(1, x.arg[0]);

  } else {
    throw exception("SQLite3.Cursor.bind requires an array or an object as its only argument");
  }
}

///////////////////////////
// bind numbered params
void sqlite3_cursor::bind_array(array &a, size_t num_binds) {

  // Pull bind param 1 (the first) from array index 0 (also the first)
  for (size_t n = 1; n <= num_binds; n++) {
    value bind = a.get_element(n-1);

    if (!bind.is_void())
      do_bind_param(n, bind);

  }
}

///////////////////////////
// bind named or numbered params
void sqlite3_cursor::bind_dict(object &o, size_t num_binds) {

  for (size_t n = 1; n <= num_binds; n++) {
    const char* name = sqlite3_bind_parameter_name(sth, n);

    value bind;

    if (!name) {
      // Possibly a '?' unnnamed param
      // TODO: This will break when n is > 2^31.
      bind = o.get_property( value( int(n) ) );
    } else {
      // Named param
      bind = o.get_property(name);
    }

    if (!bind.is_void())
      do_bind_param(n, bind);

  }

}

#include <stdio.h>
///////////////////////////
// Bind the actual para
void sqlite3_cursor::do_bind_param(int n, value v) {
  int ok;
  printf("Binding %d to value %s\n", n, v.to_string().c_str());
  if (v.is_int()) {
      ok = sqlite3_bind_int(sth, n, v.get_int());
  } else if (v.is_double()) {
    ok = sqlite3_bind_double(sth, n, v.get_double());
  } else if (v.is_null()) {
    ok = sqlite3_bind_null(sth, n);
  } else {
    // Default, stringify the object
    string bind = v.to_string();
    ok = sqlite3_bind_text16(sth, n, bind.data(), bind.length()*2, SQLITE_TRANSIENT);
  }

  if (ok != SQLITE_OK)
    raise_sqlite_error( sqlite3_db_handle(sth) );
}

///////////////////////////
// Helper function
void raise_sqlite_error(::sqlite3* db)
{
  std::string s = "SQLite3 Error: ";
  s += sqlite3_errmsg(db);
  throw exception(s);
}

}

<commit_msg>Plugins/sqlite3: Remove debug prints<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/tracer.hpp"
#include <new>

#include "sqlite3.h"

using namespace flusspferd;

// Put everything in an anon-namespace so typeid wont clash ever.
namespace {

void raise_sqlite_error(sqlite3* db);

///////////////////////////
// Classes
///////////////////////////

class sqlite3 : public native_object_base {
public:
  struct class_info : public flusspferd::class_info {
    static char const *full_name() { return "SQLite3"; }
    typedef boost::mpl::bool_<true> constructible;
    static char const *constructor_name() { return "SQLite3"; }
    static void augment_constructor(object &ctor);
    static object create_prototype();
  };

  sqlite3(object const &obj, call_context &x);
  ~sqlite3();

protected:
  //void trace(tracer &);

private: // JS methods
  ::sqlite3 *db;

  void close();
  void cursor(call_context &x);
};

class sqlite3_cursor : public native_object_base {
public:
  struct class_info : public flusspferd::class_info {
    typedef boost::mpl::bool_<false> constructible;
    static char const *full_name() { return "SQLite3.Cursor"; }
    static char const* constructor_name() { return "Cursor"; }
    static object create_prototype();
  };

  sqlite3_cursor(object const &obj, sqlite3_stmt *sth);
  ~sqlite3_cursor();

private:
  sqlite3_stmt *sth;

  // Methods that help wiht binding
  void bind_array(array &a, size_t num_binds);
  void bind_dict(object &o, size_t num_binds);
  void do_bind_param(int n, value v);

private: // JS methods
  void finish();
  void reset();
  object next();
  void bind(call_context &x);
};

///////////////////////////
// import hook
extern "C" value flusspferd_load(object container)
{
  return load_class<sqlite3>(container);
}

///////////////////////////
// Set version properties on constructor object
void sqlite3::class_info::augment_constructor(object &ctor)
{
  // Set static properties on the constructor
  ctor.define_property("version", SQLITE_VERSION_NUMBER,
      object::read_only_property | object::permanent_property);
  ctor.define_property("versionStr", string(SQLITE_VERSION),
      object::read_only_property | object::permanent_property);

  load_class<sqlite3_cursor>(ctor);
}

///////////////////////////
object sqlite3::class_info::create_prototype()
{
  object proto = create_object();

  create_native_method(proto, "cursor", 1);
  create_native_method(proto, "close", 0);
  return proto;
}

///////////////////////////
sqlite3::sqlite3(object const &obj, call_context &x)
  : native_object_base(obj),
    db(NULL)
{
  if (x.arg.size() == 0)
    throw exception ("SQLite3 requires more than 0 arguments");

  string dsn = x.arg[0];

  // TODO: pull arguments from 2nd/options argument
  if (sqlite3_open(dsn.c_str(), &db) != SQLITE_OK) {
    if (db)
      raise_sqlite_error(db);
    else
      throw std::bad_alloc(); // out of memory. better way to signal this?
  }

  register_native_method("cursor", &sqlite3::cursor);
  register_native_method("close", &sqlite3::close);
}
///////////////////////////
sqlite3::~sqlite3()
{
  close();
}

///////////////////////////
void sqlite3::close()
{
  if (db) {
    sqlite3_close(db);
    db = NULL;
  }
}

///////////////////////////
void sqlite3::cursor(call_context &x) {
  local_root_scope scope;
  if (!db)
    throw exception("SQLite3.cursor called on closed dbh");

  if (x.arg.size() < 1)
    throw exception ("cursor requires more than 0 arguments");

  string sql = x.arg[0].to_string();
  size_t n_bytes = sql.length() * 2;
  sqlite3_stmt *sth;
  char16_t *tail; // uncompiled part of the sql (when multiple stmts)
  if (sqlite3_prepare16_v2(db, sql.data(), n_bytes, &sth, (const void**)&tail) != SQLITE_OK)
  {
    raise_sqlite_error(db);
  }
  object cursor = create_native_object<sqlite3_cursor>(object(), sth);

  // TODO: remove tail and set it seperately
  cursor.define_property("sql", sql);

  x.result = cursor;
}

///////////////////////////
object sqlite3_cursor::class_info::create_prototype() {
  object proto = create_object();

  create_native_method(proto, "finish", 0);
  create_native_method(proto, "reset", 0);
  create_native_method(proto, "next", 0);
  create_native_method(proto, "bind", 0);

  return proto;
}

///////////////////////////
// 'Private' constructor that is called from sqlite3::cursor
sqlite3_cursor::sqlite3_cursor(object const &obj, sqlite3_stmt *_sth)
  : native_object_base(obj),
    sth(_sth)
{
  register_native_method("finish", &sqlite3_cursor::finish);
  register_native_method("reset", &sqlite3_cursor::reset);
  register_native_method("next", &sqlite3_cursor::next);
  register_native_method("bind", &sqlite3_cursor::bind);
}

///////////////////////////
sqlite3_cursor::~sqlite3_cursor()
{
  finish();
}

///////////////////////////
void sqlite3_cursor::finish() {
  if (sth) {
    sqlite3_finalize(sth);
    sth = NULL;
  }
}

///////////////////////////
void sqlite3_cursor::reset() {
}

///////////////////////////
object sqlite3_cursor::next() {
  return object();
}

///////////////////////////
// JS method
void sqlite3_cursor::bind(call_context &x) {
  local_root_scope scope;

  size_t num_binds = sqlite3_bind_parameter_count(sth);

  if (!num_binds)
    return;

  if (x.arg[0].is_object()) {
    object o = x.arg[0].get_object();

    if (o.is_array()) {
      array a = o;
      bind_array(a, num_binds);
    }
    else
      bind_dict(o, num_binds);
  } else if (num_binds == 1) {
    // Dont document that we accept a single param
    do_bind_param(1, x.arg[0]);

  } else {
    throw exception("SQLite3.Cursor.bind requires an array or an object as its only argument");
  }
}

///////////////////////////
// bind numbered params
void sqlite3_cursor::bind_array(array &a, size_t num_binds) {

  // Pull bind param 1 (the first) from array index 0 (also the first)
  for (size_t n = 1; n <= num_binds; n++) {
    value bind = a.get_element(n-1);

    if (!bind.is_void())
      do_bind_param(n, bind);

  }
}

///////////////////////////
// bind named or numbered params
void sqlite3_cursor::bind_dict(object &o, size_t num_binds) {

  for (size_t n = 1; n <= num_binds; n++) {
    const char* name = sqlite3_bind_parameter_name(sth, n);

    value bind;

    if (!name) {
      // Possibly a '?' unnnamed param
      // TODO: This will break when n is > 2^31.
      bind = o.get_property( value( int(n) ) );
    } else {
      // Named param
      bind = o.get_property(name);
    }

    if (!bind.is_void())
      do_bind_param(n, bind);

  }

}

///////////////////////////
// Bind the actual para
void sqlite3_cursor::do_bind_param(int n, value v) {
  int ok;
  if (v.is_int()) {
      ok = sqlite3_bind_int(sth, n, v.get_int());
  } else if (v.is_double()) {
    ok = sqlite3_bind_double(sth, n, v.get_double());
  } else if (v.is_null()) {
    ok = sqlite3_bind_null(sth, n);
  } else {
    // Default, stringify the object
    string bind = v.to_string();
    ok = sqlite3_bind_text16(sth, n, bind.data(), bind.length()*2, SQLITE_TRANSIENT);
  }

  if (ok != SQLITE_OK)
    raise_sqlite_error( sqlite3_db_handle(sth) );
}

///////////////////////////
// Helper function
void raise_sqlite_error(::sqlite3* db)
{
  std::string s = "SQLite3 Error: ";
  s += sqlite3_errmsg(db);
  throw exception(s);
}

}

<|endoftext|>