<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "product.h"

void test_product_large()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( product(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
    CALL_SUBTEST_2( product(MatrixXd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
    CALL_SUBTEST_3( product(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
    CALL_SUBTEST_4( product(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2), internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2))) );
    CALL_SUBTEST_5( product(Matrix<float,Dynamic,Dynamic,RowMajor>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
  }

#if defined EIGEN_TEST_PART_6
  {
    // test a specific issue in DiagonalProduct
    int N = 1000000;
    VectorXf v = VectorXf::Ones(N);
    MatrixXf m = MatrixXf::Ones(N,3);
    m = (v+v).asDiagonal() * m;
    VERIFY_IS_APPROX(m, MatrixXf::Constant(N,3,2));
  }

  {
    // test deferred resizing in Matrix::operator=
    MatrixXf a = MatrixXf::Random(10,4), b = MatrixXf::Random(4,10), c = a;
    VERIFY_IS_APPROX((a = a * b), (c * b).eval());
  }

  {
    // check the functions to setup blocking sizes compile and do not segfault
    // FIXME check they do what they are supposed to do !!
    std::ptrdiff_t l1 = internal::random<int>(10000,20000);
    std::ptrdiff_t l2 = internal::random<int>(1000000,2000000);
    setCpuCacheSizes(l1,l2);
    VERIFY(l1==l1CacheSize());
    VERIFY(l2==l2CacheSize());
    std::ptrdiff_t k1 = internal::random<int>(10,100)*16;
    std::ptrdiff_t m1 = internal::random<int>(10,100)*16;
    std::ptrdiff_t n1 = internal::random<int>(10,100)*16;
    // only makes sure it compiles fine
    internal::computeProductBlockingSizes<float,float>(k1,m1,n1);
  }

  {
    // test regression in row-vector by matrix (bad Map type)
    MatrixXf mat1(10,32); mat1.setRandom();
    MatrixXf mat2(32,32); mat2.setRandom();
    MatrixXf r1 = mat1.row(2)*mat2.transpose();
    VERIFY_IS_APPROX(r1, (mat1.row(2)*mat2.transpose()).eval());

    MatrixXf r2 = mat1.row(2)*mat2;
    VERIFY_IS_APPROX(r2, (mat1.row(2)*mat2).eval());
  }
#endif
}
<commit_msg>Regression test for bug 714. Note that the bug only occurs on some compilers and is not fixed yet<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "product.h"

void test_product_large()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( product(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
    CALL_SUBTEST_2( product(MatrixXd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
    CALL_SUBTEST_3( product(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
    CALL_SUBTEST_4( product(MatrixXcf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2), internal::random<int>(1,EIGEN_TEST_MAX_SIZE/2))) );
    CALL_SUBTEST_5( product(Matrix<float,Dynamic,Dynamic,RowMajor>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
  }

#if defined EIGEN_TEST_PART_6
  {
    // test a specific issue in DiagonalProduct
    int N = 1000000;
    VectorXf v = VectorXf::Ones(N);
    MatrixXf m = MatrixXf::Ones(N,3);
    m = (v+v).asDiagonal() * m;
    VERIFY_IS_APPROX(m, MatrixXf::Constant(N,3,2));
  }

  {
    // test deferred resizing in Matrix::operator=
    MatrixXf a = MatrixXf::Random(10,4), b = MatrixXf::Random(4,10), c = a;
    VERIFY_IS_APPROX((a = a * b), (c * b).eval());
  }

  {
    // check the functions to setup blocking sizes compile and do not segfault
    // FIXME check they do what they are supposed to do !!
    std::ptrdiff_t l1 = internal::random<int>(10000,20000);
    std::ptrdiff_t l2 = internal::random<int>(1000000,2000000);
    setCpuCacheSizes(l1,l2);
    VERIFY(l1==l1CacheSize());
    VERIFY(l2==l2CacheSize());
    std::ptrdiff_t k1 = internal::random<int>(10,100)*16;
    std::ptrdiff_t m1 = internal::random<int>(10,100)*16;
    std::ptrdiff_t n1 = internal::random<int>(10,100)*16;
    // only makes sure it compiles fine
    internal::computeProductBlockingSizes<float,float>(k1,m1,n1);
  }

  {
    // test regression in row-vector by matrix (bad Map type)
    MatrixXf mat1(10,32); mat1.setRandom();
    MatrixXf mat2(32,32); mat2.setRandom();
    MatrixXf r1 = mat1.row(2)*mat2.transpose();
    VERIFY_IS_APPROX(r1, (mat1.row(2)*mat2.transpose()).eval());

    MatrixXf r2 = mat1.row(2)*mat2;
    VERIFY_IS_APPROX(r2, (mat1.row(2)*mat2).eval());
  }
#endif

  // Regression test for bug 714:
#ifdef EIGEN_HAS_OPENMP
  std::cout << "Testing omp_set_dynamic(1)\n";
  omp_set_dynamic(1);
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_6( product(Matrix<float,Dynamic,Dynamic>(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );
  }
#endif
}
<|endoftext|>


<commit_before>/**
 * Copyright © 2017 INFN Torino - INDIGO-DataCloud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "PriorityManager.h"

#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <pwd.h>
#include <pthread.h>
#include <errno.h>
// booh #include <time.h>
#include <stdexcept>
#include <cmath>
#include <iomanip>
#include <ctime>
#include <climits>
#include <list>
#include "Fass.h"
#include "FassLog.h"
#include "VMPool.h"
#include "VirtualMachine.h"
// #include "InitShares.h"
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

list<PriorityManager::user*> PriorityManager::user_list;

// unary operator
PriorityManager::user*
PriorityManager::make_user(
          const std::string& user_group_share, const int& sum) {
  vector< string > tokens;
  boost::split(tokens, user_group_share, boost::is_any_of(":"));

  if ( 4 != tokens.size() ) {
     throw;
  }

  PriorityManager::user *us = new PriorityManager::user(
                      boost::lexical_cast<int16_t>(tokens[1]),
                      boost::lexical_cast<int16_t>(tokens[2]),
                      boost::lexical_cast<float_t>(tokens[3])/sum);

  return us;
}

PriorityManager::PriorityManager(
          const string _one_xmlrpc,
          const string _one_secret,
          int _message_size,
          int _timeout,
          unsigned int _max_vm,
          vector<string> _shares,
          int _manager_timer):
                one_xmlrpc(_one_xmlrpc),
                one_secret(_one_secret),
                message_size(_message_size),
                timeout(_timeout),
                max_vm(_max_vm),
                shares(_shares),
                manager_timer(_manager_timer),
                stop_manager(false) {
    // initialize XML-RPC Client
    ostringstream oss;
    int rc;

    try {
    XMLRPCClient::initialize(one_secret, one_xmlrpc, message_size, timeout);

    client = XMLRPCClient::client();

    oss << "XML-RPC client using "
        << (XMLRPCClient::client())->get_message_size()
    << " bytes for response buffer." << endl;

    FassLog::log("PM", Log::INFO, oss);
    }
    catch(runtime_error &) {
        throw;
    }

    // create list of user objects with initial shares
    rc = calculate_initial_shares();

    if (!rc) {
        FassLog::log("PM", Log::ERROR, "Could not evaluate initial shares.");
    }
}

extern "C" void * pm_loop(void *arg) {
    PriorityManager * pm;

    if ( arg == 0 ) {
        return 0;
    }

    FassLog::log("PM", Log::INFO, "Priority Manager started.");

    pm = static_cast<PriorityManager *>(arg);

    // set thread cancel state
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);

    // here the actual loop happens
    int rc;
    struct timespec timeout;

    ostringstream oss;
    // oss << "Manager timer is: " << pm->manager_timer;
    // FassLog::log("SARA", Log::INFO, oss);

    // actual loop
    while (!pm->stop_manager) {
        bool wait = true;
        timeout.tv_sec  = time(NULL) + pm->manager_timer;
        timeout.tv_nsec = 0;

        // FassLog::log("SARA", Log::INFO, "Pippo!");

        pm->lock();
        while (wait && !pm->stop_manager) {  // block for manager_timer seconds
                rc = pthread_cond_timedwait(&pm->cond, &pm->mutex, &timeout);
                // ostringstream oss;
                // oss << "Timedwait return value: " << rc;
                // FassLog::log("SARA",Log::INFO, oss);

                if ( rc == ETIMEDOUT ) wait = false;
        }

        // FassLog::log("SARA", Log::INFO, "Pluto!");
        pm->unlock();

        pm->loop();
    }

    FassLog::log("PM", Log::INFO, "Priority Manager stopped.");

    return 0;
}

void PriorityManager::loop() {
    FassLog::log("SARA", Log::INFO, "PRIORITY MANAGER LOOP");

    int rc;
    // let's get the list of pending VMs from ONE
    rc = get_pending();

    if ( rc != 0 ) {
        FassLog::log("PM", Log::ERROR, "Cannot get the VM pool!");
    }

    // return an xml string with reordered VMs
    rc = set_queue();

    if ( !rc ) {
        FassLog::log("PM", Log::ERROR, "Cannot set the VM pool!");
    }

    // do_prioritize();
}

bool PriorityManager::set_queue() {
    queue = "pippo";

    return true;
}

int PriorityManager::start() {
    pthread_attr_t  pattr;
    ostringstream oss;
    // int rc;

    FassLog::log("PM", Log::INFO, "Starting Priority Manager...");

    pthread_attr_init(&pattr);
    pthread_attr_setdetachstate(&pattr, PTHREAD_CREATE_JOINABLE);

    pthread_create(&pm_thread, &pattr, pm_loop, reinterpret_cast<void *>(this));

    return true;
}

int PriorityManager::get_pending() {
    FassLog::log("PM", Log::DEBUG, "Executing get_pending...");
    int rc;
    // VM pool
    // TODO(valzacc or svallero): is it needed?
    bool live_resched = true;
    vmpool = new VMPool(client, max_vm, live_resched);

    // cleans the cache and gets the VM pool
    rc = vmpool->set_up();
    // TODO(svallero): real return code
    return rc;
}

/*
void PriorityManager::do_prioritize() {
    FassLog::log("PM", Log::INFO, "Executing do_prioritize...");
    int rc;
    ostringstream oss;

    VirtualMachine * vm;

    int oid;
    int uid;
    int gid;
    int vm_memory;
    int vm_cpu;
//    list<user> user_list;

    const map<int, VirtualMachine*> pending_vms = vmpool->get_objects();

    time_t time_start = time(0);
    time_t time_end   = time(0);

    tm tmp_tm = *localtime(&time_start);

    int start_month = 1;   // January
    int start_year = 2016; // TODO Make this number settable in the config file

    float vm_prio = 1.0; // value from 0 to 1

    tmp_tm.tm_sec  = 0;
    tmp_tm.tm_min  = 0;
    tmp_tm.tm_hour = 0;
    tmp_tm.tm_mday = 1;
    tmp_tm.tm_mon  = start_month - 1;
    tmp_tm.tm_year = start_year - 1900;
    tmp_tm.tm_isdst = -1; // Unknown daylight saving time

    time_start = mktime(&tmp_tm);

    // first param is the filter flag:
    // -3: Connected user resources
    // -2: All resources
    // -1: Connected user and his group resources
    // 0: UID User Resources

    //client->call("one.vmpool.accounting", "iii", &result, 0, time_start, time_end); // how to use this info?  TODO with Sara

    map<int, VirtualMachine*>::const_iterator  vm_it;

    oss << "Scheduling Results:" << endl;

    for (vm_it=pending_vms.begin(); vm_it != pending_vms.end(); vm_it++) {

         vm = static_cast<VirtualMachine*>(vm_it->second);

         vm->get_requirements(vm_cpu, vm_memory);
         oid = vm->get_oid();
         vm->get_uid();
         vm->get_gid();
//         vm->get_state();
// // I think that this is not relevant
// //         vm->get_rank();

        //oss << *vm;
        oss << oid << " ";
        //FassLog::log("PM", Log::INFO, oss);
    }
    FassLog::log("PM", Log::INFO, oss);

//  oss    << "\tNumber of VMs:            "
//         << pending_vms.size() << endl;

// FassLog::log("PM", Log::INFO, oss);

// //shares retrieved in Fass class and passed into pm

// PluginBasic::update_prio(oid, uid, gid, vm_cpu, vm_memory, list_of_users, &vm_prio); // TODO we miss historical usage U

  return;
}
*/

bool PriorityManager::calculate_initial_shares() {
    FassLog::log("PM", Log::INFO, "Evaluating initial shares...");

    // TODO(svallero or valzacc):
    // for the time being only user shares are considered
    vector<string> norm_shares;
    int sum = 0;
    for (vector<string>::const_iterator i= shares.begin();
                                      i != shares.end(); i++) {
        vector<string> tokens;
        boost::split(tokens, *i, boost::is_any_of(":"));
        sum += boost::lexical_cast<int16_t>(tokens[3]);
    }

    for (vector<string>::const_iterator i= shares.begin();
                                      i != shares.end(); i++) {
       user_list.push_back(make_user(*i , sum));
    }

    ostringstream oss;
    oss << "" << endl;
    for (list<user*>::const_iterator i = user_list.begin();
                                    i != user_list.end(); ++i) {
        oss << (*i)->userID << " "
        << (*i)->groupID << " "
        << (*i)->share << endl;
    }

    FassLog::log("SARA", Log::INFO, oss);

    return true;
}

<commit_msg>Codestyle<commit_after>/**
 * Copyright © 2017 INFN Torino - INDIGO-DataCloud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "PriorityManager.h"

#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <pwd.h>
#include <pthread.h>
#include <errno.h>
// booh #include <time.h>
#include <stdexcept>
#include <cmath>
#include <iomanip>
#include <ctime>
#include <climits>
#include <list>
#include "Fass.h"
#include "FassLog.h"
#include "VMPool.h"
#include "VirtualMachine.h"
// #include "InitShares.h"
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

list<PriorityManager::user*> PriorityManager::user_list;

// unary operator
PriorityManager::user*
PriorityManager::make_user(
          const std::string& user_group_share, const int& sum) {
  vector< string > tokens;
  boost::split(tokens, user_group_share, boost::is_any_of(":"));

  if ( 4 != tokens.size() ) {
     throw;
  }

  PriorityManager::user *us = new PriorityManager::user(
                      boost::lexical_cast<int16_t>(tokens[1]),
                      boost::lexical_cast<int16_t>(tokens[2]),
                      boost::lexical_cast<float_t>(tokens[3])/sum);

  return us;
}

PriorityManager::PriorityManager(
          const string _one_xmlrpc,
          const string _one_secret,
          int _message_size,
          int _timeout,
          unsigned int _max_vm,
          vector<string> _shares,
          int _manager_timer):
                one_xmlrpc(_one_xmlrpc),
                one_secret(_one_secret),
                message_size(_message_size),
                timeout(_timeout),
                max_vm(_max_vm),
                shares(_shares),
                manager_timer(_manager_timer),
                stop_manager(false) {
    // initialize XML-RPC Client
    ostringstream oss;
    int rc;

    try {
    XMLRPCClient::initialize(one_secret, one_xmlrpc, message_size, timeout);

    client = XMLRPCClient::client();

    oss << "XML-RPC client using "
        << (XMLRPCClient::client())->get_message_size()
    << " bytes for response buffer." << endl;

    FassLog::log("PM", Log::INFO, oss);
    }
    catch(runtime_error &) {
        throw;
    }

    // create list of user objects with initial shares
    rc = calculate_initial_shares();

    if (!rc) {
        FassLog::log("PM", Log::ERROR, "Could not evaluate initial shares.");
    }
}

extern "C" void * pm_loop(void *arg) {
    PriorityManager * pm;

    if ( arg == 0 ) {
        return 0;
    }

    FassLog::log("PM", Log::INFO, "Priority Manager started.");

    pm = static_cast<PriorityManager *>(arg);

    // set thread cancel state
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);

    // here the actual loop happens
    int rc;
    struct timespec timeout;

    ostringstream oss;
    // oss << "Manager timer is: " << pm->manager_timer;
    // FassLog::log("SARA", Log::INFO, oss);

    // actual loop
    while (!pm->stop_manager) {
        bool wait = true;
        timeout.tv_sec  = time(NULL) + pm->manager_timer;
        timeout.tv_nsec = 0;

        // FassLog::log("SARA", Log::INFO, "Pippo!");

        pm->lock();
        while (wait && !pm->stop_manager) {  // block for manager_timer seconds
                rc = pthread_cond_timedwait(&pm->cond, &pm->mutex, &timeout);
                // ostringstream oss;
                // oss << "Timedwait return value: " << rc;
                // FassLog::log("SARA",Log::INFO, oss);

                if ( rc == ETIMEDOUT ) wait = false;
        }

        // FassLog::log("SARA", Log::INFO, "Pluto!");
        pm->unlock();

        pm->loop();
    }

    FassLog::log("PM", Log::INFO, "Priority Manager stopped.");

    return 0;
}

void PriorityManager::loop() {
    FassLog::log("SARA", Log::INFO, "PRIORITY MANAGER LOOP");

    int rc;
    // let's get the list of pending VMs from ONE
    rc = get_pending();

    if ( rc != 0 ) {
        FassLog::log("PM", Log::ERROR, "Cannot get the VM pool!");
    }

    // return an xml string with reordered VMs
    rc = set_queue();

    if ( !rc ) {
        FassLog::log("PM", Log::ERROR, "Cannot set the VM pool!");
    }

    // do_prioritize();
}

bool PriorityManager::set_queue() {
    queue = "pippo";

    return true;
}

int PriorityManager::start() {
    pthread_attr_t  pattr;
    ostringstream oss;
    // int rc;

    FassLog::log("PM", Log::INFO, "Starting Priority Manager...");

    pthread_attr_init(&pattr);
    pthread_attr_setdetachstate(&pattr, PTHREAD_CREATE_JOINABLE);

    pthread_create(&pm_thread, &pattr, pm_loop, reinterpret_cast<void *>(this));

    return true;
}

int PriorityManager::get_pending() {
    FassLog::log("PM", Log::DEBUG, "Executing get_pending...");
    int rc;
    // VM pool
    // TODO(valzacc or svallero): is it needed?
    bool live_resched = true;
    vmpool = new VMPool(client, max_vm, live_resched);

    // cleans the cache and gets the VM pool
    rc = vmpool->set_up();
    // TODO(svallero): real return code
    return rc;
}

/*
void PriorityManager::do_prioritize() {
    FassLog::log("PM", Log::INFO, "Executing do_prioritize...");
    int rc;
    ostringstream oss;

    VirtualMachine * vm;

    int oid;
    int uid;
    int gid;
    int vm_memory;
    int vm_cpu;
//    list<user> user_list;

    const map<int, VirtualMachine*> pending_vms = vmpool->get_objects();

    time_t time_start = time(0);
    time_t time_end   = time(0);

    tm tmp_tm = *localtime(&time_start);

    int start_month = 1;   // January
    int start_year = 2016; // TODO Make this number settable in the config file

    float vm_prio = 1.0; // value from 0 to 1

    tmp_tm.tm_sec  = 0;
    tmp_tm.tm_min  = 0;
    tmp_tm.tm_hour = 0;
    tmp_tm.tm_mday = 1;
    tmp_tm.tm_mon  = start_month - 1;
    tmp_tm.tm_year = start_year - 1900;
    tmp_tm.tm_isdst = -1; // Unknown daylight saving time

    time_start = mktime(&tmp_tm);

    // first param is the filter flag:
    // -3: Connected user resources
    // -2: All resources
    // -1: Connected user and his group resources
    // 0: UID User Resources

    //client->call("one.vmpool.accounting", "iii", &result, 0, time_start, time_end); // how to use this info?  TODO with Sara

    map<int, VirtualMachine*>::const_iterator  vm_it;

    oss << "Scheduling Results:" << endl;

    for (vm_it=pending_vms.begin(); vm_it != pending_vms.end(); vm_it++) {

         vm = static_cast<VirtualMachine*>(vm_it->second);

         vm->get_requirements(vm_cpu, vm_memory);
         oid = vm->get_oid();
         vm->get_uid();
         vm->get_gid();
//         vm->get_state();
// // I think that this is not relevant
// //         vm->get_rank();

        //oss << *vm;
        oss << oid << " ";
        //FassLog::log("PM", Log::INFO, oss);
    }
    FassLog::log("PM", Log::INFO, oss);

//  oss    << "\tNumber of VMs:            "
//         << pending_vms.size() << endl;

// FassLog::log("PM", Log::INFO, oss);

// //shares retrieved in Fass class and passed into pm

// PluginBasic::update_prio(oid, uid, gid, vm_cpu, vm_memory, list_of_users, &vm_prio); // TODO we miss historical usage U

  return;
}
*/

bool PriorityManager::calculate_initial_shares() {
    FassLog::log("PM", Log::INFO, "Evaluating initial shares...");

    // TODO(svallero or valzacc):
    // for the time being only user shares are considered
    vector<string> norm_shares;
    int sum = 0;
    for (vector<string>::const_iterator i= shares.begin();
                                      i != shares.end(); i++) {
        vector<string> tokens;
        boost::split(tokens, *i, boost::is_any_of(":"));
        sum += boost::lexical_cast<int16_t>(tokens[3]);
    }

    for (vector<string>::const_iterator i= shares.begin();
                                      i != shares.end(); i++) {
       user_list.push_back(make_user(*i , sum));
    }

    ostringstream oss;
    oss << "" << endl;
    for (list<user*>::const_iterator i = user_list.begin();
                                    i != user_list.end(); ++i) {
        oss << (*i)->userID << " "
        << (*i)->groupID << " "
        << (*i)->share << endl;
    }

    FassLog::log("SARA", Log::INFO, oss);

    return true;
}

<|endoftext|>


<commit_before>/*
*****************************************************************************
*                      ___       _   _    _ _
*                     / _ \ __ _| |_| |__(_) |_ ___
*                    | (_) / _` | / / '_ \ |  _(_-<
*                     \___/\__,_|_\_\_.__/_|\__/__/
*                          Copyright (c) 2011
*
* 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.
*****************************************************************************/
/**
* @author   R. Picard
* @date     2011/12/19
*
*****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "String.h"

/**
* @date     2011/12/19
*
*  Constructor.
*
******************************************************************************/
String::String(void):
   InitStatus(0), Area(NULL), AreaSize(0)
{
}

/**
* @date     2011/12/21
*
*  Copy Constructor.
*
******************************************************************************/
String::String(const String &BaseString):
   InitStatus(-1), Area(NULL), AreaSize(0)
{
   InitStatus = SetTo(BaseString);
}

/**
* @date     2012/01/11
*
*  Constructor.
*
******************************************************************************/
String::String(const char *BaseString, uint32_t i_Length):
   InitStatus(-1), Area(NULL), AreaSize(0)
{
   InitStatus = SetTo(BaseString, i_Length);
}

/**
* @date     2011/12/19
*
*  Destructor.
*
******************************************************************************/
String::~String(void)
{
   DelArea();
}

/**
* @date     2012/01/08
*
*  Equality operator.
*
******************************************************************************/
bool String::operator==(const String &Rhs) const
{
   if(strcmp(GetString(), Rhs.GetString()) == 0)
      return(true);
   return(false);
}

/**
* @date     2012/01/08
*
*  Equality operator.
*
******************************************************************************/
bool String::operator!=(const String &Rhs) const
{
   return(!operator==(Rhs));
}

/**
* @date     2012/02/14
*
*  Append operator.
*
******************************************************************************/
String& String::operator<<(int Rhs)
{
   char Num[32];
   int32_t i_Length = snprintf(Num, sizeof(Num), "%d", Rhs);

   AppendString(Num, i_Length);
   return(*this);
}

/**
* @date     2012/02/14
*
*  Append operator.
*
******************************************************************************/
String& String::operator<<(const char* Rhs)
{
   AppendString(Rhs, strlen(Rhs));
   return(*this);
}

/**
* @date     2012/02/14
*
*  Append operator.
*
******************************************************************************/
String& String::operator<<(const String &Rhs)
{
   AppendString(Rhs.GetString(), Rhs.GetSize());
   return(*this);
}

/**
* @date     2012/01/08
*
*  Sets the value of the string.
*
******************************************************************************/
int32_t String::SetTo(const String &Value)
{
   return(SetTo(Value.GetString(), 0));
}

/**
* @date     2011/12/19
*
*  Sets the value of the string.
*
******************************************************************************/
int32_t String::SetTo(const char *Value, uint32_t i_Length)
{
   if(Value == NULL)
      return(-1);

   DelArea();
   uint32_t ValueLength;
   if(i_Length == 0)
      ValueLength = strlen(Value);
   else
      ValueLength = i_Length;
   Area = static_cast<char*>(malloc(ValueLength+1));
   if(Area == NULL)
      return(-1);
   AreaSize = ValueLength+1;
   memcpy(Area, Value, strlen(Value));
   Area[ValueLength] = '\0';
   return(0);
}

/**
* @date     2011/12/21
*
*  Search SearchString inside the string object.
*
*  @param   SearchString (in): String to search for.
*  @return  SearchString offset is success.
*  @return  -1 otherwise.
******************************************************************************/
int32_t String::FindFirst(const String &SearchString) const
{
   const char *SearchCString = SearchString.GetString();
   char  *Result;

   if(SearchCString != NULL)
   {
      Result = strstr(Area, SearchCString);
      if(Result != NULL)
      {
         return(Result-Area);
      }
   }
   return(-1);
}

/**
* @date     2011/12/19
*
*  Frees the Area storage space.
*
******************************************************************************/
void String::DelArea(void)
{
   if(Area != NULL)
   {
      free(Area);
      Area = NULL;
      AreaSize = 0;
   }
}

/**
* @date     2012/02/14
*
*  Appends a string.
* ///@todo : prealloc space to avoid multiple reallocs
*
******************************************************************************/
int32_t String::AppendString(const char* sz_String, uint32_t i_Length)
{
   if( (sz_String == NULL) || (i_Length == 0) )
      return(-1);

   bool     b_Duplicate = sz_String == Area ? true : false;
   uint32_t i_Offset = 0;
   if(Area != NULL)
      i_Offset = strlen(Area);

   uint32_t i_NewSize = i_Length+1;
   if(Area != NULL)
      i_NewSize += strlen(Area);

   if(i_NewSize > AreaSize)
   {
      Area = static_cast<char*>(realloc(Area, i_NewSize));
      if(Area != NULL)
         AreaSize = i_NewSize;
   }
   if(Area == NULL)
      return(-1);
   if(b_Duplicate == true)
      memcpy(Area+i_Offset, Area, i_Length);
   else
      memcpy(Area+i_Offset, sz_String, i_Length);
   Area[i_Offset+i_Length] = '\0';
   return(0);
}
<commit_msg>Fix overflows in String<commit_after>/*
*****************************************************************************
*                      ___       _   _    _ _
*                     / _ \ __ _| |_| |__(_) |_ ___
*                    | (_) / _` | / / '_ \ |  _(_-<
*                     \___/\__,_|_\_\_.__/_|\__/__/
*                          Copyright (c) 2011
*
* 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.
*****************************************************************************/
/**
* @author   R. Picard
* @date     2011/12/19
*
*****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "String.h"

/**
* @date     2011/12/19
*
*  Constructor.
*
******************************************************************************/
String::String(void):
   InitStatus(0), Area(NULL), AreaSize(0)
{
}

/**
* @date     2011/12/21
*
*  Copy Constructor.
*
******************************************************************************/
String::String(const String &BaseString):
   InitStatus(-1), Area(NULL), AreaSize(0)
{
   InitStatus = SetTo(BaseString);
}

/**
* @date     2012/01/11
*
*  Constructor.
*
******************************************************************************/
String::String(const char *BaseString, uint32_t i_Length):
   InitStatus(-1), Area(NULL), AreaSize(0)
{
   InitStatus = SetTo(BaseString, i_Length);
}

/**
* @date     2011/12/19
*
*  Destructor.
*
******************************************************************************/
String::~String(void)
{
   DelArea();
}

/**
* @date     2012/01/08
*
*  Equality operator.
*
******************************************************************************/
bool String::operator==(const String &Rhs) const
{
   if(strcmp(GetString(), Rhs.GetString()) == 0)
      return(true);
   return(false);
}

/**
* @date     2012/01/08
*
*  Equality operator.
*
******************************************************************************/
bool String::operator!=(const String &Rhs) const
{
   return(!operator==(Rhs));
}

/**
* @date     2012/02/14
*
*  Append operator.
*
******************************************************************************/
String& String::operator<<(int Rhs)
{
   char Num[32];
   int32_t i_Length = snprintf(Num, sizeof(Num), "%d", Rhs);

   Num[sizeof(Num) -1] = '\0';
   AppendString(Num, i_Length);
   return(*this);
}

/**
* @date     2012/02/14
*
*  Append operator.
*
******************************************************************************/
String& String::operator<<(const char* Rhs)
{
   AppendString(Rhs, strlen(Rhs));
   return(*this);
}

/**
* @date     2012/02/14
*
*  Append operator.
*
******************************************************************************/
String& String::operator<<(const String &Rhs)
{
   AppendString(Rhs.GetString(), Rhs.GetSize());
   return(*this);
}

/**
* @date     2012/01/08
*
*  Sets the value of the string.
*
******************************************************************************/
int32_t String::SetTo(const String &Value)
{
   return(SetTo(Value.GetString(), 0));
}

/**
* @date     2011/12/19
*
*  Sets the value of the string.
*
******************************************************************************/
int32_t String::SetTo(const char *Value, uint32_t i_Length)
{
   if(Value == NULL)
      return(-1);

   DelArea();
   uint32_t ValueLength;
   if(i_Length == 0)
      ValueLength = strlen(Value);
   else
      ValueLength = i_Length;
   Area = static_cast<char*>(malloc(ValueLength+1));
   if(Area == NULL)
      return(-1);
   AreaSize = ValueLength+1;
   memcpy(Area, Value, ValueLength);
   Area[ValueLength] = '\0';
   return(0);
}

/**
* @date     2011/12/21
*
*  Search SearchString inside the string object.
*
*  @param   SearchString (in): String to search for.
*  @return  SearchString offset is success.
*  @return  -1 otherwise.
******************************************************************************/
int32_t String::FindFirst(const String &SearchString) const
{
   const char *SearchCString = SearchString.GetString();
   char  *Result;

   if(SearchCString != NULL)
   {
      Result = strstr(Area, SearchCString);
      if(Result != NULL)
      {
         return(Result-Area);
      }
   }
   return(-1);
}

/**
* @date     2011/12/19
*
*  Frees the Area storage space.
*
******************************************************************************/
void String::DelArea(void)
{
   if(Area != NULL)
   {
      free(Area);
      Area = NULL;
      AreaSize = 0;
   }
}

/**
* @date     2012/02/14
*
*  Appends a string.
* ///@todo : prealloc space to avoid multiple reallocs
*
******************************************************************************/
int32_t String::AppendString(const char* sz_String, uint32_t i_Length)
{
   if( (sz_String == NULL) || (i_Length == 0) )
      return(-1);

   bool     b_Duplicate = sz_String == Area ? true : false;
   uint32_t i_Offset = 0;
   if(Area != NULL)
      i_Offset = strlen(Area);

   uint32_t i_NewSize = i_Length+1;
   if(Area != NULL)
      i_NewSize += strlen(Area);

   if(i_NewSize > AreaSize)
   {
      Area = static_cast<char*>(realloc(Area, i_NewSize));
      if(Area != NULL)
         AreaSize = i_NewSize;
   }
   if(Area == NULL)
      return(-1);
   if(b_Duplicate == true)
      memcpy(Area+i_Offset, Area, i_Length);
   else
      memcpy(Area+i_Offset, sz_String, i_Length);
   Area[i_Offset+i_Length] = '\0';
   return(0);
}
<|endoftext|>


<commit_before>/*
 * This file is part of the Topologic/GL project.
*/

/*
 * Copyright (c) 2012-2013, ef.gy Project Members
 *
 * 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.
*/

#ifdef __APPLE__
#include <OpenGL/gl3.h>
#include <GLUT/glut.h>          /* Open GL Util APPLE */
#else
#include <GL/glew.h>
#include <GL/glut.h>            /* FreeGLUT (hopefully) */
#endif

#include <topologic/gl.h>

#if !defined(MAXDEPTH)
#define MAXDEPTH 7
#endif

GLfloat mouseX, mouseY;
GLfloat lastMouseX, lastMouseY;

bool mouseLeft, mouseRight;

topologic::state<topologic::GLFP,MAXDEPTH> topologicState;

void displayCall(void)
{
    if (topologicState.model)
    {
        topologicState.model->render(true);
    }

    glutSwapBuffers();
    glutPostRedisplay();
}

void reshape(GLint width, GLint height)
{
    glViewport(0, 0, width, height);
    glClearDepth(1.0f);

    glEnable (GL_BLEND);

    glEnable(GL_CULL_FACE);

    topologicState.width  = width;
    topologicState.height = height;
}

void idle(void)
{
    if (mouseLeft || mouseRight)
    {
        glutPostRedisplay();
    }
}

bool shiftActive;

void processMouse(int x, int y)
{
    mouseX = x;
    mouseY = y;

    if (mouseLeft || mouseRight)
    {
        double xd = (mouseX - lastMouseX);
        double yd = (mouseY - lastMouseY);

        if (shiftActive)
        {
            topologicState.interpretDrag(0,0,xd+-yd);
        }
        else
        {
            topologicState.interpretDrag(xd,yd,0);
        }

        lastMouseX = mouseX;
        lastMouseY = mouseY;
    }
}

void processMouseButton(int button, int state, int x, int y)
{
    shiftActive = (glutGetModifiers() & GLUT_ACTIVE_SHIFT);

    processMouse(x,y);

    switch (button)
    {
        case 0:
            mouseLeft = (state == 0);
            break;
        case 2:
            mouseRight = (state == 0);
            break;
        case 3:
            if (state == 0)
            {
                topologicState.interpretDrag(0,0,30);
            }
            break;
        case 4:
            if (state == 0)
            {
                topologicState.interpretDrag(0,0,-30);
            }
            break;
    }

    if (mouseLeft || mouseRight)
    {
        lastMouseX = mouseX;
        lastMouseY = mouseY;
    }
}

void processKeyboard(unsigned char key, int x, int y)
{
    switch (key)
    {
        case '1': topologicState.setActive ( 3); break;
        case '2': topologicState.setActive ( 4); break;
        case '3': topologicState.setActive ( 5); break;
        case '4': topologicState.setActive ( 6); break;
        case '5': topologicState.setActive ( 7); break;
        case '6': topologicState.setActive ( 8); break;
        case '7': topologicState.setActive ( 9); break;
        case '8': topologicState.setActive (10); break;
        case '9': topologicState.setActive (11); break;
        case '0': topologicState.setActive (12); break;
        case 'r':
            topologicState.realign();
            glutPostRedisplay();
            break;
    }
}

int main (int argc, char* argv[])
{
    try
    {
        if (!topologic::parseArguments (topologicState, argc, argv, topologic::outGL))
        {
            return 1;
        }

        if (!topologicState.model)
        {
            std::cerr << "error: no model to render\n";
        }
        else
        {
            glutInit(&argc, argv);
            glutInitWindowSize(1280, 720);

#ifdef __APPLE__
	        glutInitDisplayMode(GLUT_3_2_CORE_PROFILE | GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
#else
#if defined(GLUT_CORE_PROFILE)
	        glutInitContextVersion(3, 2);
	        glutInitContextProfile(GLUT_CORE_PROFILE);
#endif
	        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
#endif
            glutCreateWindow("Topologic/GLUT");
#ifndef __APPLE__
            glewInit();
#endif

            glutDisplayFunc (displayCall);
            glutIdleFunc(idle);
            glutReshapeFunc (reshape);
            glutMouseFunc(processMouseButton);
            glutMotionFunc(processMouse);
            glutPassiveMotionFunc(processMouse);
            glutKeyboardFunc(processKeyboard);
            glutFullScreen();

            glutMainLoop();
        }
    }
    catch (std::exception &e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
        return 1;
    }
    catch (...)
    {
        std::cerr << "Unknown Exception\n";
        return 1;
    }

    return 0;
}
<commit_msg>ditch the quite unnecessary idle function; seems to help a lot with the generated webgl code and it decreases the CPU load when there's nothing to update<commit_after>/*
 * This file is part of the Topologic/GL project.
*/

/*
 * Copyright (c) 2012-2013, ef.gy Project Members
 *
 * 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.
*/

#ifdef __APPLE__
#include <OpenGL/gl3.h>
#include <GLUT/glut.h>          /* Open GL Util APPLE */
#else
#include <GL/glew.h>
#include <GL/glut.h>            /* FreeGLUT (hopefully) */
#endif

#include <topologic/gl.h>

#if !defined(MAXDEPTH)
#define MAXDEPTH 7
#endif

GLfloat mouseX, mouseY;
GLfloat lastMouseX, lastMouseY;

bool mouseLeft, mouseRight;

topologic::state<topologic::GLFP,MAXDEPTH> topologicState;

void displayCall(void)
{
    if (topologicState.model)
    {
        topologicState.model->render(true);
    }

    glutSwapBuffers();
    glutPostRedisplay();
}

void reshape(GLint width, GLint height)
{
    glViewport(0, 0, width, height);
    glClearDepth(1.0f);

    glEnable (GL_BLEND);

    glEnable(GL_CULL_FACE);

    topologicState.width  = width;
    topologicState.height = height;
}

bool shiftActive;

void processMouse(int x, int y)
{
    mouseX = x;
    mouseY = y;

    if (mouseLeft || mouseRight)
    {
        double xd = (mouseX - lastMouseX);
        double yd = (mouseY - lastMouseY);

        if (shiftActive)
        {
            topologicState.interpretDrag(0,0,xd+-yd);
        }
        else
        {
            topologicState.interpretDrag(xd,yd,0);
        }

        lastMouseX = mouseX;
        lastMouseY = mouseY;

        glutPostRedisplay();
    }
}

void processMouseButton(int button, int state, int x, int y)
{
    shiftActive = (glutGetModifiers() & GLUT_ACTIVE_SHIFT);

    processMouse(x,y);

    switch (button)
    {
        case 0:
            mouseLeft = (state == 0);
            break;
        case 2:
            mouseRight = (state == 0);
            break;
        case 3:
            if (state == 0)
            {
                topologicState.interpretDrag(0,0,30);
            }
            break;
        case 4:
            if (state == 0)
            {
                topologicState.interpretDrag(0,0,-30);
            }
            break;
    }

    if (mouseLeft || mouseRight)
    {
        lastMouseX = mouseX;
        lastMouseY = mouseY;

        glutPostRedisplay();
    }
}

void processKeyboard(unsigned char key, int x, int y)
{
    switch (key)
    {
        case '1': topologicState.setActive ( 3); break;
        case '2': topologicState.setActive ( 4); break;
        case '3': topologicState.setActive ( 5); break;
        case '4': topologicState.setActive ( 6); break;
        case '5': topologicState.setActive ( 7); break;
        case '6': topologicState.setActive ( 8); break;
        case '7': topologicState.setActive ( 9); break;
        case '8': topologicState.setActive (10); break;
        case '9': topologicState.setActive (11); break;
        case '0': topologicState.setActive (12); break;
        case 'r':
            topologicState.realign();
            glutPostRedisplay();
            break;
    }

    glutPostRedisplay();
}

int main (int argc, char* argv[])
{
    try
    {
        if (!topologic::parseArguments (topologicState, argc, argv, topologic::outGL))
        {
            return 1;
        }

        if (!topologicState.model)
        {
            std::cerr << "error: no model to render\n";
        }
        else
        {
            glutInit(&argc, argv);
            glutInitWindowSize(1280, 720);

#ifdef __APPLE__
	        glutInitDisplayMode(GLUT_3_2_CORE_PROFILE | GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
#else
#if defined(GLUT_CORE_PROFILE)
	        glutInitContextVersion(3, 2);
	        glutInitContextProfile(GLUT_CORE_PROFILE);
#endif
	        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
#endif
            glutCreateWindow("Topologic/GLUT");
#ifndef __APPLE__
            glewInit();
#endif

            glutDisplayFunc (displayCall);
            glutReshapeFunc (reshape);
            glutMouseFunc(processMouseButton);
            glutMotionFunc(processMouse);
            glutPassiveMotionFunc(processMouse);
            glutKeyboardFunc(processKeyboard);
            glutFullScreen();

            glutMainLoop();
        }
    }
    catch (std::exception &e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
        return 1;
    }
    catch (...)
    {
        std::cerr << "Unknown Exception\n";
        return 1;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "Application.hpp"
#include "log.hpp"
#include "lua/State.hpp"
#include "Build.hpp"
#include "bind.hpp"
#include "quote.hpp"

#include "generators/Shell.hpp"
#include "generators/Makefile.hpp"
#include "generators/NMakefile.hpp"

#include <boost/algorithm/string.hpp>
#include <algorithm>
#include <iostream>
#include <map>

namespace fs = boost::filesystem;

namespace configure {

	namespace {

		std::vector<std::string> args_to_vector(int ac, char ** av)
		{
			std::vector<std::string> res;
			for (int i = 0; i < ac; ++i)
				res.push_back(av[i]);
			return res;
		}

		bool is_project_directory(fs::path const& dir)
		{
			for (auto&& p: Build::possible_configure_files())
				if (fs::is_regular_file(dir / p))
					return true;
			return false;
		}

		bool is_build_directory(fs::path const& dir)
		{
			return fs::is_regular_file(dir / ".configure.env");
		}

	}

	struct Application::Impl
	{
		std::string                        program_name;
		std::vector<std::string>           args;
		path_t                             current_directory;
		std::vector<path_t>                build_directories;
		path_t                             project_directory;
		std::map<std::string, std::string> build_variables;
		bool                               dump_graph_mode;
		std::string                        generator;
		bool                               build_mode;
		std::string                        build_target;
		Impl(std::vector<std::string> args)
			: program_name(args.at(0))
			, args(std::move(args))
			, current_directory(fs::current_path())
			, build_directories()
			, project_directory()
			, build_variables()
			, dump_graph_mode(false)
			, generator()
			, build_mode(false)
			, build_target()
		{ this->args.erase(this->args.begin()); }
	};

	Application::Application(int ac, char** av)
		: Application(args_to_vector(ac, av))
	{}

	Application::Application(std::vector<std::string> args)
		: _this(new Impl(std::move(args)))
	{ _parse_args(); }

	Application::~Application() {}

	void Application::run()
	{
		log::debug("Current directory:", _this->current_directory);
		log::debug("Program name:", _this->program_name);
		if (_this->build_directories.empty())
			throw std::runtime_error("No build directory specified");
		fs::path project_file = Build::find_project_file(_this->project_directory);
		fs::path package;
		char const* lib = ::getenv("CONFIGURE_LIBRARY_DIR");
		if (lib != nullptr)
			package = lib;
		else
			package = fs::canonical(
				fs::absolute(_this->program_name).parent_path().parent_path()
				/ "share" / "configure" / "lib"
			);
		package /= "?.lua";
		lua::State lua;
		bind(lua);
		lua.global("configure_library_dir", package.string());
		lua.load(
			"require 'package'\n"
			"package.path = configure_library_dir\n"
		);
		for (auto const& directory: _this->build_directories)
		{
			Build build(lua, directory, _this->build_variables);
			build.configure(_this->project_directory);
			if (_this->dump_graph_mode)
				build.dump_graphviz(std::cout);
			log::debug("Generating the build files in", build.directory());
			auto& generator = this->_generator(build);
			generator.generate(build);
			log::status("Build files generated successfully in",
						build.directory(), "(", generator.name(), ")");
			if (_this->build_mode)
			{
				log::status("Starting build in", build.directory());
				auto cmd = generator.build_command(build, _this->build_target);
				int res = ::system(
#ifdef _WIN32
				    quote<CommandParser::windows_shell>(cmd).c_str()
#else
				    quote<CommandParser::unix_shell>(cmd).c_str()
#endif
				);
				if (res != 0)
					CONFIGURE_THROW(
						error::BuildError("Build failed with exit code " + std::to_string(res))
						<< error::path(build.directory())
						<< error::command(cmd)
					);
			}
		}

	}

	std::string const& Application::program_name() const
	{ return _this->program_name; }

	fs::path const& Application::project_directory() const
	{ return _this->project_directory; }

	std::vector<fs::path> const& Application::build_directories() const
	{ return _this->build_directories; }

	Generator const& Application::_generator(Build& build) const
	{
		static std::vector<std::unique_ptr<Generator>> generators;
		if (generators.empty())
		{
#define ADD_GENERATOR(T) \
			{ \
				std::unique_ptr<Generator> g(new T()); \
				log::debug( \
					"Generator", g->name(), "is", \
					(g->is_available(build) ? "available" : "not available")); \
				generators.push_back(std::move(g));\
			} \
/**/
			ADD_GENERATOR(generators::Makefile);
			ADD_GENERATOR(generators::NMakefile);
			ADD_GENERATOR(generators::Shell);
#undef ADD_GENERATOR
		}

		std::string generator_name = _this->generator;
		if (generator_name.empty())
		{
			log::debug("No generator specified on command line, searching for one that is available as default");
			for (auto& gen: generators)
				if (gen->is_available(build))
				{
					generator_name = gen->name();
					log::debug("Found generator", generator_name, "as default");
					break;
				}
			if (generator_name.empty())
				CONFIGURE_THROW(
					error::InvalidGenerator(
						"No generator available for your platform"
					)
				);
		}

		generator_name = build.option<std::string>(
			"GENERATOR",
			"Generator to use",
			generator_name
		);
		log::debug("Choosen generator is", generator_name);

		boost::algorithm::to_lower(generator_name);
		for (auto& gen: generators)
			if (boost::algorithm::to_lower_copy(gen->name()) == generator_name)
			{
				if (!gen->is_available(build))
					CONFIGURE_THROW(
						error::InvalidGenerator(
							"Generator '" + generator_name + "' is not available"
						)
					);
				return *gen;
			}
		CONFIGURE_THROW(
			error::InvalidGenerator("Unknown generator '" + generator_name + "'")
		);
	}
	void Application::print_help()
	{
		std::cout
			<< "Usage: " << _this->program_name
			<< "  [OPTION]... [BUILD_DIR]... [KEY=VALUE]...\n"
			<< "\n"
			<< "  Configure your project's builds in one or more directories.\n"
			<< "\n"
			<< "Positional arguments:\n"

			<< "  BUILD_DIR" << "             "
			<< "Build directory to configure\n"

			<< "  KEY=VALUE" << "             "
			<< "Set a variable for selected build directories\n"

			<< "\n"

			<< "Optional arguments:\n"

			<< "  -G, --generator NAME" << "  "
			<< "Specify the generator to use (alternative to variable GENERATOR)\n"

			<< "  -p, --project PATH" << "    "
			<< "Specify the project to configure instead of detecting it\n"

			<< "  --dump-graph" << "          "
			<< "Dump the build graph\n"

			<< "  -d, --debug" << "           "
			<< "Enable debug output\n"

			<< "  -v, --verbose" << "         "
			<< "Enable verbose output\n"

			<< "  --version" << "             "
			<< "Print version\n"

			<< "  -h, --help" << "            "
			<< "Show this help and exit\n"

			<< "  -b,--build[=target]" << "   "
			<< "Start a build in specified directories\n"

		;
	}

	void Application::exit()
	{
		::exit(0);
	}

	void Application::_parse_args()
	{
		// Searching help and version flags first (ignoring command line errors
		// if any).
		for (auto const& arg: _this->args)
		{
			if (arg == "-h" || arg == "--help")
			{
				this->print_help();
				this->exit();
			}
			if (arg == "--version")
			{
#ifndef CONFIGURE_VERSION_STRING
# define CONFIGURE_VERSION_STRING "unknown"
#endif
				log::print("configure version", CONFIGURE_VERSION_STRING);
				this->exit();
			}
		}

		bool has_project = false;
		enum class NextArg { project, generator, other };
		NextArg next_arg = NextArg::other;
		for (auto const& arg: _this->args)
		{
			if (next_arg == NextArg::project)
			{
				if (!is_project_directory(arg))
					throw std::runtime_error{"Invalid project directory"};
				if (!has_project)
				{
					_this->project_directory = fs::canonical(arg);
					has_project = true;
				}
				else if (_this->project_directory == fs::canonical(arg))
				{
					std::cerr << "Warning: Project directory specified more than once.\n";
				}
				else
				{
					throw std::runtime_error{"Cannot operate on multiple projects"};
				}
				next_arg = NextArg::other;
			}
			else if (next_arg == NextArg::generator)
			{
				_this->generator = arg;
				next_arg = NextArg::other;
			}
			else if (arg == "-p" || arg == "--project")
			{
				next_arg = NextArg::project;
			}
			else if (arg == "--dump-graph")
			{
				_this->dump_graph_mode = true;
			}
			else if (arg == "-G" || arg == "--generator")
			{
				next_arg = NextArg::generator;
			}
			else if (arg == "-d" || arg == "--debug")
			{
				log::level() = log::Level::debug;
			}
			else if (arg == "-v" || arg == "--verbose")
			{
				log::level() = log::Level::verbose;
			}
			else if (boost::starts_with(arg, "--build=") ||
			         boost::starts_with(arg, "-b="))
			{
				auto it = arg.find('=');
				_this->build_target = arg.substr(it + 1, std::string::npos);
				_this->build_mode = true;
			}
			else if (arg == "--build" || arg == "-b")
			{
				_this->build_mode = true;
			}
			else if (arg.find('=') != std::string::npos)
			{
				auto it = arg.find('=');
				if (it != std::string::npos)
				{
					_this->build_variables[arg.substr(0, it)] =
						arg.substr(it + 1, std::string::npos);
					continue;
				}
			}
			else if (is_build_directory(arg) ||
			         !fs::exists(arg) ||
			         (fs::is_directory(arg) && fs::is_empty(arg)))
			{
				_this->build_directories.push_back(fs::absolute(arg));
			}
			else
			{
				CONFIGURE_THROW(
					error::InvalidArgument("Unknown argument '" + arg + "'")
				);
			}
		}
		if (next_arg != NextArg::other)
		{
			CONFIGURE_THROW(
				error::InvalidArgument(
					"Missing argument for flag '" + _this->args.back() + "'"
				)
			);
		}
		if (!has_project)
		{
			if (is_project_directory(_this->current_directory))
				_this->project_directory = _this->current_directory;
			else
				throw std::runtime_error{"No project to configure"};
		}
	}

}
<commit_msg>Check for NMake first (make does not work on windows yet).<commit_after>#include "Application.hpp"
#include "log.hpp"
#include "lua/State.hpp"
#include "Build.hpp"
#include "bind.hpp"
#include "quote.hpp"

#include "generators/Shell.hpp"
#include "generators/Makefile.hpp"
#include "generators/NMakefile.hpp"

#include <boost/algorithm/string.hpp>
#include <algorithm>
#include <iostream>
#include <map>

namespace fs = boost::filesystem;

namespace configure {

	namespace {

		std::vector<std::string> args_to_vector(int ac, char ** av)
		{
			std::vector<std::string> res;
			for (int i = 0; i < ac; ++i)
				res.push_back(av[i]);
			return res;
		}

		bool is_project_directory(fs::path const& dir)
		{
			for (auto&& p: Build::possible_configure_files())
				if (fs::is_regular_file(dir / p))
					return true;
			return false;
		}

		bool is_build_directory(fs::path const& dir)
		{
			return fs::is_regular_file(dir / ".configure.env");
		}

	}

	struct Application::Impl
	{
		std::string                        program_name;
		std::vector<std::string>           args;
		path_t                             current_directory;
		std::vector<path_t>                build_directories;
		path_t                             project_directory;
		std::map<std::string, std::string> build_variables;
		bool                               dump_graph_mode;
		std::string                        generator;
		bool                               build_mode;
		std::string                        build_target;
		Impl(std::vector<std::string> args)
			: program_name(args.at(0))
			, args(std::move(args))
			, current_directory(fs::current_path())
			, build_directories()
			, project_directory()
			, build_variables()
			, dump_graph_mode(false)
			, generator()
			, build_mode(false)
			, build_target()
		{ this->args.erase(this->args.begin()); }
	};

	Application::Application(int ac, char** av)
		: Application(args_to_vector(ac, av))
	{}

	Application::Application(std::vector<std::string> args)
		: _this(new Impl(std::move(args)))
	{ _parse_args(); }

	Application::~Application() {}

	void Application::run()
	{
		log::debug("Current directory:", _this->current_directory);
		log::debug("Program name:", _this->program_name);
		if (_this->build_directories.empty())
			throw std::runtime_error("No build directory specified");
		fs::path project_file = Build::find_project_file(_this->project_directory);
		fs::path package;
		char const* lib = ::getenv("CONFIGURE_LIBRARY_DIR");
		if (lib != nullptr)
			package = lib;
		else
			package = fs::canonical(
				fs::absolute(_this->program_name).parent_path().parent_path()
				/ "share" / "configure" / "lib"
			);
		package /= "?.lua";
		lua::State lua;
		bind(lua);
		lua.global("configure_library_dir", package.string());
		lua.load(
			"require 'package'\n"
			"package.path = configure_library_dir\n"
		);
		for (auto const& directory: _this->build_directories)
		{
			Build build(lua, directory, _this->build_variables);
			build.configure(_this->project_directory);
			if (_this->dump_graph_mode)
				build.dump_graphviz(std::cout);
			log::debug("Generating the build files in", build.directory());
			auto& generator = this->_generator(build);
			generator.generate(build);
			log::status("Build files generated successfully in",
						build.directory(), "(", generator.name(), ")");
			if (_this->build_mode)
			{
				log::status("Starting build in", build.directory());
				auto cmd = generator.build_command(build, _this->build_target);
				int res = ::system(
#ifdef _WIN32
				    quote<CommandParser::windows_shell>(cmd).c_str()
#else
				    quote<CommandParser::unix_shell>(cmd).c_str()
#endif
				);
				if (res != 0)
					CONFIGURE_THROW(
						error::BuildError("Build failed with exit code " + std::to_string(res))
						<< error::path(build.directory())
						<< error::command(cmd)
					);
			}
		}

	}

	std::string const& Application::program_name() const
	{ return _this->program_name; }

	fs::path const& Application::project_directory() const
	{ return _this->project_directory; }

	std::vector<fs::path> const& Application::build_directories() const
	{ return _this->build_directories; }

	Generator const& Application::_generator(Build& build) const
	{
		static std::vector<std::unique_ptr<Generator>> generators;
		if (generators.empty())
		{
#define ADD_GENERATOR(T) \
			{ \
				std::unique_ptr<Generator> g(new T()); \
				log::debug( \
					"Generator", g->name(), "is", \
					(g->is_available(build) ? "available" : "not available")); \
				generators.push_back(std::move(g));\
			} \
/**/
			ADD_GENERATOR(generators::NMakefile);
			ADD_GENERATOR(generators::Makefile);
			ADD_GENERATOR(generators::Shell);
#undef ADD_GENERATOR
		}

		std::string generator_name = _this->generator;
		if (generator_name.empty())
		{
			log::debug("No generator specified on command line, searching for one that is available as default");
			for (auto& gen: generators)
				if (gen->is_available(build))
				{
					generator_name = gen->name();
					log::debug("Found generator", generator_name, "as default");
					break;
				}
			if (generator_name.empty())
				CONFIGURE_THROW(
					error::InvalidGenerator(
						"No generator available for your platform"
					)
				);
		}

		generator_name = build.option<std::string>(
			"GENERATOR",
			"Generator to use",
			generator_name
		);
		log::debug("Choosen generator is", generator_name);

		boost::algorithm::to_lower(generator_name);
		for (auto& gen: generators)
			if (boost::algorithm::to_lower_copy(gen->name()) == generator_name)
			{
				if (!gen->is_available(build))
					CONFIGURE_THROW(
						error::InvalidGenerator(
							"Generator '" + generator_name + "' is not available"
						)
					);
				return *gen;
			}
		CONFIGURE_THROW(
			error::InvalidGenerator("Unknown generator '" + generator_name + "'")
		);
	}
	void Application::print_help()
	{
		std::cout
			<< "Usage: " << _this->program_name
			<< "  [OPTION]... [BUILD_DIR]... [KEY=VALUE]...\n"
			<< "\n"
			<< "  Configure your project's builds in one or more directories.\n"
			<< "\n"
			<< "Positional arguments:\n"

			<< "  BUILD_DIR" << "             "
			<< "Build directory to configure\n"

			<< "  KEY=VALUE" << "             "
			<< "Set a variable for selected build directories\n"

			<< "\n"

			<< "Optional arguments:\n"

			<< "  -G, --generator NAME" << "  "
			<< "Specify the generator to use (alternative to variable GENERATOR)\n"

			<< "  -p, --project PATH" << "    "
			<< "Specify the project to configure instead of detecting it\n"

			<< "  --dump-graph" << "          "
			<< "Dump the build graph\n"

			<< "  -d, --debug" << "           "
			<< "Enable debug output\n"

			<< "  -v, --verbose" << "         "
			<< "Enable verbose output\n"

			<< "  --version" << "             "
			<< "Print version\n"

			<< "  -h, --help" << "            "
			<< "Show this help and exit\n"

			<< "  -b,--build[=target]" << "   "
			<< "Start a build in specified directories\n"

		;
	}

	void Application::exit()
	{
		::exit(0);
	}

	void Application::_parse_args()
	{
		// Searching help and version flags first (ignoring command line errors
		// if any).
		for (auto const& arg: _this->args)
		{
			if (arg == "-h" || arg == "--help")
			{
				this->print_help();
				this->exit();
			}
			if (arg == "--version")
			{
#ifndef CONFIGURE_VERSION_STRING
# define CONFIGURE_VERSION_STRING "unknown"
#endif
				log::print("configure version", CONFIGURE_VERSION_STRING);
				this->exit();
			}
		}

		bool has_project = false;
		enum class NextArg { project, generator, other };
		NextArg next_arg = NextArg::other;
		for (auto const& arg: _this->args)
		{
			if (next_arg == NextArg::project)
			{
				if (!is_project_directory(arg))
					throw std::runtime_error{"Invalid project directory"};
				if (!has_project)
				{
					_this->project_directory = fs::canonical(arg);
					has_project = true;
				}
				else if (_this->project_directory == fs::canonical(arg))
				{
					std::cerr << "Warning: Project directory specified more than once.\n";
				}
				else
				{
					throw std::runtime_error{"Cannot operate on multiple projects"};
				}
				next_arg = NextArg::other;
			}
			else if (next_arg == NextArg::generator)
			{
				_this->generator = arg;
				next_arg = NextArg::other;
			}
			else if (arg == "-p" || arg == "--project")
			{
				next_arg = NextArg::project;
			}
			else if (arg == "--dump-graph")
			{
				_this->dump_graph_mode = true;
			}
			else if (arg == "-G" || arg == "--generator")
			{
				next_arg = NextArg::generator;
			}
			else if (arg == "-d" || arg == "--debug")
			{
				log::level() = log::Level::debug;
			}
			else if (arg == "-v" || arg == "--verbose")
			{
				log::level() = log::Level::verbose;
			}
			else if (boost::starts_with(arg, "--build=") ||
			         boost::starts_with(arg, "-b="))
			{
				auto it = arg.find('=');
				_this->build_target = arg.substr(it + 1, std::string::npos);
				_this->build_mode = true;
			}
			else if (arg == "--build" || arg == "-b")
			{
				_this->build_mode = true;
			}
			else if (arg.find('=') != std::string::npos)
			{
				auto it = arg.find('=');
				if (it != std::string::npos)
				{
					_this->build_variables[arg.substr(0, it)] =
						arg.substr(it + 1, std::string::npos);
					continue;
				}
			}
			else if (is_build_directory(arg) ||
			         !fs::exists(arg) ||
			         (fs::is_directory(arg) && fs::is_empty(arg)))
			{
				_this->build_directories.push_back(fs::absolute(arg));
			}
			else
			{
				CONFIGURE_THROW(
					error::InvalidArgument("Unknown argument '" + arg + "'")
				);
			}
		}
		if (next_arg != NextArg::other)
		{
			CONFIGURE_THROW(
				error::InvalidArgument(
					"Missing argument for flag '" + _this->args.back() + "'"
				)
			);
		}
		if (!has_project)
		{
			if (is_project_directory(_this->current_directory))
				_this->project_directory = _this->current_directory;
			else
				throw std::runtime_error{"No project to configure"};
		}
	}

}
<|endoftext|>


<commit_before>// Copyright 2006-2009 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// 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.

#include "v8.h"

#include "bootstrapper.h"
#include "debug.h"
#include "serialize.h"
#include "simulator.h"
#include "stub-cache.h"
#include "oprofile-agent.h"
#include "log.h"

namespace v8 {
namespace internal {

bool V8::is_running_ = false;
bool V8::has_been_setup_ = false;
bool V8::has_been_disposed_ = false;
bool V8::has_fatal_error_ = false;

bool V8::Initialize(Deserializer* des) {
  bool create_heap_objects = des == NULL;
  if (has_been_disposed_ || has_fatal_error_) return false;
  if (IsRunning()) return true;

  is_running_ = true;
  has_been_setup_ = true;
  has_fatal_error_ = false;
  has_been_disposed_ = false;
#ifdef DEBUG
  // The initialization process does not handle memory exhaustion.
  DisallowAllocationFailure disallow_allocation_failure;
#endif

  // Enable logging before setting up the heap
  Logger::Setup();

  CpuProfiler::Setup();

  // Setup the platform OS support.
  OS::Setup();

  // Initialize other runtime facilities
#if !V8_HOST_ARCH_ARM && V8_TARGET_ARCH_ARM
  ::assembler::arm::Simulator::Initialize();
#endif

  { // NOLINT
    // Ensure that the thread has a valid stack guard.  The v8::Locker object
    // will ensure this too, but we don't have to use lockers if we are only
    // using one thread.
    ExecutionAccess lock;
    StackGuard::InitThread(lock);
  }

  // Setup the object heap
  ASSERT(!Heap::HasBeenSetup());
  if (!Heap::Setup(create_heap_objects)) {
    SetFatalError();
    return false;
  }

  Bootstrapper::Initialize(create_heap_objects);
  Builtins::Setup(create_heap_objects);
  Top::Initialize();

  if (FLAG_preemption) {
    v8::Locker locker;
    v8::Locker::StartPreemption(100);
  }

#ifdef ENABLE_DEBUGGER_SUPPORT
  Debug::Setup(create_heap_objects);
#endif
  StubCache::Initialize(create_heap_objects);

  // If we are deserializing, read the state into the now-empty heap.
  if (des != NULL) {
    des->Deserialize();
    StubCache::Clear();
  }

  // Deserializing may put strange things in the root array's copy of the
  // stack guard.
  Heap::SetStackLimits();

  // Setup the CPU support. Must be done after heap setup and after
  // any deserialization because we have to have the initial heap
  // objects in place for creating the code object used for probing.
  CPU::Setup();

  OProfileAgent::Initialize();

  // If we are deserializing, log non-function code objects and compiled
  // functions found in the snapshot.
  if (des != NULL && FLAG_log_code) {
    HandleScope scope;
    LOG(LogCodeObjects());
    LOG(LogCompiledFunctions());
  }

  return true;
}

void V8::SetFatalError() {
  is_running_ = false;
  has_fatal_error_ = true;
}

void V8::TearDown() {
  if (!has_been_setup_ || has_been_disposed_) return;

  OProfileAgent::TearDown();

  if (FLAG_preemption) {
    v8::Locker locker;
    v8::Locker::StopPreemption();
  }

  Builtins::TearDown();
  Bootstrapper::TearDown();

  Top::TearDown();

  Heap::TearDown();

  CpuProfiler::TearDown();

  Logger::TearDown();

  is_running_ = false;
  has_been_disposed_ = true;
}

static uint32_t random_seed() {
  if (FLAG_random_seed == 0) {
    return random();
  }
  return FLAG_random_seed;
}

uint32_t V8::Random() {
  // Random number generator using George Marsaglia's MWC algorithm.
  static uint32_t hi = 0;
  static uint32_t lo = 0;

  // Initialize seed using the system random(). If one of the seeds
  // should ever become zero again, or if random() returns zero, we
  // avoid getting stuck with zero bits in hi or lo by re-initializing
  // them on demand.
  if (hi == 0) hi = random_seed();
  if (lo == 0) lo = random_seed();

  // Mix the bits.
  hi = 36969 * (hi & 0xFFFF) + (hi >> 16);
  lo = 18273 * (lo & 0xFFFF) + (lo >> 16);
  return (hi << 16) + (lo & 0xFFFF);
}

bool V8::IdleNotification() {
  // Returning true tells the caller that there is no need to call
  // IdleNotification again.
  if (!FLAG_use_idle_notification) return true;

  // Tell the heap that it may want to adjust.
  return Heap::IdleNotification();
}

// Use a union type to avoid type-aliasing optimizations in GCC.
typedef union {
  double double_value;
  uint64_t uint64_t_value;
} double_int_union;

Object* V8::FillHeapNumberWithRandom(Object* heap_number) {
  uint64_t random_bits = Random();
  // Make a double* from address (heap_number + sizeof(double)).
  double_int_union* r = reinterpret_cast<double_int_union*>(
      reinterpret_cast<char*>(heap_number) +
      HeapNumber::kValueOffset - kHeapObjectTag);
  // Convert 32 random bits to 0.(32 random bits) in a double
  // by computing:
  // ( 1.(20 0s)(32 random bits) x 2^20 ) - (1.0 x 2^20)).
  const double binary_million = 1048576.0;
  r->double_value = binary_million;
  r->uint64_t_value |=  random_bits;
  r->double_value -= binary_million;

  return heap_number;
}

} }  // namespace v8::internal
<commit_msg>Fix teardown order.<commit_after>// Copyright 2006-2009 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// 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.

#include "v8.h"

#include "bootstrapper.h"
#include "debug.h"
#include "serialize.h"
#include "simulator.h"
#include "stub-cache.h"
#include "oprofile-agent.h"
#include "log.h"

namespace v8 {
namespace internal {

bool V8::is_running_ = false;
bool V8::has_been_setup_ = false;
bool V8::has_been_disposed_ = false;
bool V8::has_fatal_error_ = false;

bool V8::Initialize(Deserializer* des) {
  bool create_heap_objects = des == NULL;
  if (has_been_disposed_ || has_fatal_error_) return false;
  if (IsRunning()) return true;

  is_running_ = true;
  has_been_setup_ = true;
  has_fatal_error_ = false;
  has_been_disposed_ = false;
#ifdef DEBUG
  // The initialization process does not handle memory exhaustion.
  DisallowAllocationFailure disallow_allocation_failure;
#endif

  // Enable logging before setting up the heap
  Logger::Setup();

  CpuProfiler::Setup();

  // Setup the platform OS support.
  OS::Setup();

  // Initialize other runtime facilities
#if !V8_HOST_ARCH_ARM && V8_TARGET_ARCH_ARM
  ::assembler::arm::Simulator::Initialize();
#endif

  { // NOLINT
    // Ensure that the thread has a valid stack guard.  The v8::Locker object
    // will ensure this too, but we don't have to use lockers if we are only
    // using one thread.
    ExecutionAccess lock;
    StackGuard::InitThread(lock);
  }

  // Setup the object heap
  ASSERT(!Heap::HasBeenSetup());
  if (!Heap::Setup(create_heap_objects)) {
    SetFatalError();
    return false;
  }

  Bootstrapper::Initialize(create_heap_objects);
  Builtins::Setup(create_heap_objects);
  Top::Initialize();

  if (FLAG_preemption) {
    v8::Locker locker;
    v8::Locker::StartPreemption(100);
  }

#ifdef ENABLE_DEBUGGER_SUPPORT
  Debug::Setup(create_heap_objects);
#endif
  StubCache::Initialize(create_heap_objects);

  // If we are deserializing, read the state into the now-empty heap.
  if (des != NULL) {
    des->Deserialize();
    StubCache::Clear();
  }

  // Deserializing may put strange things in the root array's copy of the
  // stack guard.
  Heap::SetStackLimits();

  // Setup the CPU support. Must be done after heap setup and after
  // any deserialization because we have to have the initial heap
  // objects in place for creating the code object used for probing.
  CPU::Setup();

  OProfileAgent::Initialize();

  // If we are deserializing, log non-function code objects and compiled
  // functions found in the snapshot.
  if (des != NULL && FLAG_log_code) {
    HandleScope scope;
    LOG(LogCodeObjects());
    LOG(LogCompiledFunctions());
  }

  return true;
}

void V8::SetFatalError() {
  is_running_ = false;
  has_fatal_error_ = true;
}

void V8::TearDown() {
  if (!has_been_setup_ || has_been_disposed_) return;

  OProfileAgent::TearDown();

  if (FLAG_preemption) {
    v8::Locker locker;
    v8::Locker::StopPreemption();
  }

  Builtins::TearDown();
  Bootstrapper::TearDown();

  Top::TearDown();

  CpuProfiler::TearDown();

  Heap::TearDown();

  Logger::TearDown();

  is_running_ = false;
  has_been_disposed_ = true;
}

static uint32_t random_seed() {
  if (FLAG_random_seed == 0) {
    return random();
  }
  return FLAG_random_seed;
}

uint32_t V8::Random() {
  // Random number generator using George Marsaglia's MWC algorithm.
  static uint32_t hi = 0;
  static uint32_t lo = 0;

  // Initialize seed using the system random(). If one of the seeds
  // should ever become zero again, or if random() returns zero, we
  // avoid getting stuck with zero bits in hi or lo by re-initializing
  // them on demand.
  if (hi == 0) hi = random_seed();
  if (lo == 0) lo = random_seed();

  // Mix the bits.
  hi = 36969 * (hi & 0xFFFF) + (hi >> 16);
  lo = 18273 * (lo & 0xFFFF) + (lo >> 16);
  return (hi << 16) + (lo & 0xFFFF);
}

bool V8::IdleNotification() {
  // Returning true tells the caller that there is no need to call
  // IdleNotification again.
  if (!FLAG_use_idle_notification) return true;

  // Tell the heap that it may want to adjust.
  return Heap::IdleNotification();
}

// Use a union type to avoid type-aliasing optimizations in GCC.
typedef union {
  double double_value;
  uint64_t uint64_t_value;
} double_int_union;

Object* V8::FillHeapNumberWithRandom(Object* heap_number) {
  uint64_t random_bits = Random();
  // Make a double* from address (heap_number + sizeof(double)).
  double_int_union* r = reinterpret_cast<double_int_union*>(
      reinterpret_cast<char*>(heap_number) +
      HeapNumber::kValueOffset - kHeapObjectTag);
  // Convert 32 random bits to 0.(32 random bits) in a double
  // by computing:
  // ( 1.(20 0s)(32 random bits) x 2^20 ) - (1.0 x 2^20)).
  const double binary_million = 1048576.0;
  r->double_value = binary_million;
  r->uint64_t_value |=  random_bits;
  r->double_value -= binary_million;

  return heap_number;
}

} }  // namespace v8::internal
<|endoftext|>


<commit_before>// System Dependencies
#include <sys/time.h>

// Local Dependencies
#include "../include/datetime.h"
#include "../include/exception.h"

/** Divisors: The number of milliseconds per item. */
#define DAY_DIVISOR		86400000
#define HOUR_DIVISOR	3600000
#define MINUTE_DIVISOR	60000
#define SECOND_DIVISOR	1000

namespace native
{
	DateTime::DateTime()
	{
		throw NotImplementedException();
	}

	DateTime::DateTime(int year, int month, int day)
	{
		throw NotImplementedException();
	}

	DateTime::DateTime(const DateTime& other) : _value(other._value), _offset(other._offset)
	{
	}

	void DateTime::addDays(int days)
	{
		_value += int64_t(days) * DAY_DIVISOR;
	}

	void DateTime::addHours(int hours)
	{
		_value += int64_t(hours) * HOUR_DIVISOR;
	}

	void DateTime::addMinutes(int minutes)
	{
		_value += int64_t(minutes) * MINUTE_DIVISOR;
	}

	void DateTime::addSeconds(int seconds)
	{
		_value += int64_t(seconds) * SECOND_DIVISOR;
	}

	void DateTime::addMilliSeconds(int milliseconds)
	{
		_value += milliseconds;
	}

	short DateTime::getDay() const
	{
		throw NotImplementedException();
	}

	WeekDay DateTime::getWeekDay() const
	{
		throw NotImplementedException();
	}

	Month DateTime::getMonth() const
	{
		throw NotImplementedException();
	}

	int DateTime::getYear() const
	{
		throw NotImplementedException();
	}

	short DateTime::getHour() const
	{
		throw NotImplementedException();
	}

	short DateTime::getMinute() const
	{
		throw NotImplementedException();
	}

	short DateTime::getSecond() const
	{
		throw NotImplementedException();
	}

	short DateTime::getMilliSecond() const
	{
		throw NotImplementedException();
	}

	String DateTime::toString() const
	{
		const wchar_t* format;

		if (getTimeZoneOffset() == 0)
			format = L"{0:04}-{1:02}-{2:02}T{3:02}:{4:02}:{5:02}.{6:03}Z";
		else
			format = L"{0:04}-{1:02}-{2:02}T{3:02}:{4:02}:{5:02}.{6:03}+{7:02}:{8:02}";

		return String::format(format, getYear(), getMonth(), getDay(), getHour(), getMinute(),
			getSecond(), getMilliSecond(), getTimeZoneOffset() / 60, getTimeZoneOffset() % 60);
	}
}
<commit_msg>Get started on Android DateTime stuff.<commit_after>// System Dependencies
#include <sys/time.h>

// Local Dependencies
#include "../include/datetime.h"
#include "../include/exception.h"

/** Divisors: The number of milliseconds per item. */
#define DAY_DIVISOR		86400000
#define HOUR_DIVISOR	3600000
#define MINUTE_DIVISOR	60000
#define SECOND_DIVISOR	1000

namespace native
{
	DateTime::DateTime()
	{
		struct timeval tv;
		struct timezone tz;

		::gettimeofday(&tv, &tz);

		_value = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
		_offset = tz.tz_minuteswest;
	}

	DateTime::DateTime(int year, int month, int day)
	{
		throw NotImplementedException();
	}

	DateTime::DateTime(const DateTime& other) : _value(other._value), _offset(other._offset)
	{
	}

	void DateTime::addDays(int days)
	{
		_value += int64_t(days) * DAY_DIVISOR;
	}

	void DateTime::addHours(int hours)
	{
		_value += int64_t(hours) * HOUR_DIVISOR;
	}

	void DateTime::addMinutes(int minutes)
	{
		_value += int64_t(minutes) * MINUTE_DIVISOR;
	}

	void DateTime::addSeconds(int seconds)
	{
		_value += int64_t(seconds) * SECOND_DIVISOR;
	}

	void DateTime::addMilliSeconds(int milliseconds)
	{
		_value += milliseconds;
	}

	short DateTime::getDay() const
	{
		throw NotImplementedException();
	}

	WeekDay DateTime::getWeekDay() const
	{
		throw NotImplementedException();
	}

	Month DateTime::getMonth() const
	{
		throw NotImplementedException();
	}

	int DateTime::getYear() const
	{
		throw NotImplementedException();
	}

	short DateTime::getHour() const
	{
		throw NotImplementedException();
	}

	short DateTime::getMinute() const
	{
		throw NotImplementedException();
	}

	short DateTime::getSecond() const
	{
		throw NotImplementedException();
	}

	short DateTime::getMilliSecond() const
	{
		throw NotImplementedException();
	}

	String DateTime::toString() const
	{
		const wchar_t* format;

		if (getTimeZoneOffset() == 0)
			format = L"{0:04}-{1:02}-{2:02}T{3:02}:{4:02}:{5:02}.{6:03}Z";
		else
			format = L"{0:04}-{1:02}-{2:02}T{3:02}:{4:02}:{5:02}.{6:03}+{7:02}:{8:02}";

		return String::format(format, getYear(), getMonth(), getDay(), getHour(), getMinute(),
			getSecond(), getMilliSecond(), getTimeZoneOffset() / 60, getTimeZoneOffset() % 60);
	}
}
<|endoftext|>