<commit_before>/*-------------ConjGrad.cpp---------------------------------------------------//
*
*              Conjugate Gradient Method
*
* Purpose: This file intends to solve a simple linear algebra equation:
*              Ax = b
*              Where A is a square matrix of dimension N and x, b are vectors
*              of length N.
*
*   Notes: We can write this entire code without std:: vector. Think about it
*          Need to make sure we are indexing arrays appropriately.
*          Think about using LAPACK / BLAS
*
*-----------------------------------------------------------------------------*/

#include <iostream>
#include <vector>
#include <memory>
#include <cassert>

// Struct to hold 2d array
struct array2D{
    // initial pointers to array
    std::unique_ptr<double[]> data;
    size_t rows, columns;

    // defines our interface with array creation and creates struct memebers
    array2D(size_t n, size_t m) : data(new double[(n)*(m)]),
                                  rows(n),
                                  columns(m) {
        for(size_t i = 0; i < n*m; i++){ data[i] = 0; }
    }

    // These are interfaces for array calls. Basically setting the row length.
    double operator() (size_t row, size_t col) const {
        return data[row * columns + col];
    }

    double& operator() (size_t row, size_t col) {
        return data[row * columns + col];
    }
};

// Smaller function for Matrix multiply
array2D matmul(const array2D &A, const array2D &B);

// Function for Conj Gradient -- All the big stuff happens here
void conjgrad(const array2D &A, const array2D &b, array2D &x);

/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/

int main(){

    array2D a(2,2), b(2,1);

    array2D c = matmul(a, b);

    for (size_t i = 0; i < c.rows; i++){
        for (size_t j = 0; j < c.columns; j++){
            std::cout << c(i,j) << '\t';
        }
        std::cout << '\n';
    }
}

/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/

// Smaller function for Matrix multiply
array2D matmul(const array2D &A, const array2D &B){

    if (A.columns != B.rows){
        std::cout << "Incorrect inner dimensions for multiplication." << '\n';
        assert(A.columns == B.rows);
    }

    // Check to make sure we are creating C with an appropriate size
    array2D C(A.rows, B.columns);

    for (size_t i = 0; i < C.rows; i++){
        for (size_t j = 0; j < C.columns; j++){
            for (size_t k = 0; k < A.columns; k++){
                C(i, j) += A(i, k) * B(k, j);
            }
        }
    }

    return C;
}

// Function for Conj Gradient -- All the big stuff happens here
void conjgrad(const array2D &A, const array2D &b, array2D &x){
}

<commit_msg>added a few more beta functions. Will be tested next stream.<commit_after>/*-------------ConjGrad.cpp---------------------------------------------------//
*
*              Conjugate Gradient Method
*
* Purpose: This file intends to solve a simple linear algebra equation:
*              Ax = b
*              Where A is a square matrix of dimension N and x, b are vectors
*              of length N.
*
*   Notes: We can write this entire code without std:: vector. Think about it
*          Need to make sure we are indexing arrays appropriately.
*          Think about using LAPACK / BLAS
*          matmag is not for matrices yet. Fix that.
*          ConjGrad function not working or tested yet.
*
*-----------------------------------------------------------------------------*/

#include <iostream>
#include <vector>
#include <memory>
#include <cassert>
#include <cmath>

// Struct to hold 2d array
struct array2D{
    // initial pointers to array
    std::unique_ptr<double[]> data;
    size_t rows, columns;

    // defines our interface with array creation and creates struct memebers
    array2D(size_t n, size_t m) : data(new double[(n)*(m)]),
                                  rows(n),
                                  columns(m) {
        for(size_t i = 0; i < n*m; i++){ data[i] = 0; }
    }

    // These are interfaces for array calls. Basically setting the row length.
    double operator() (size_t row, size_t col) const {
        return data[row * columns + col];
    }

    double& operator() (size_t row, size_t col) {
        return data[row * columns + col];
    }
};

// Smaller function for Matrix multiply
array2D matmul(const array2D &A, const array2D &B);

// Function for addition
array2D matadd(const array2D &A, const array2D &B);
array2D matdiff(const array2D &A, const array2D &B);

// Function for scaling
array2D matscale(const array2D &A, double scale);

// Function for finding the magnitude of a vector... Note not array yet.
double matmag(const array2D &A);

// Function for Conj Gradient -- All the big stuff happens here
void conjgrad(const array2D &A, const array2D &b, array2D &x_0, double thresh);

/*----------------------------------------------------------------------------//
* MAIN
*-----------------------------------------------------------------------------*/

int main(){

    array2D a(2,2), b(2,1);

    a(0,0) = 4; a(1,0) = 1; a(0,1) = 1; a(1,1) = 3;
    b(0,0) = 2; b(0,1) = 1;

    array2D c = matmul(a, b);

    for (size_t i = 0; i < c.rows; i++){
        for (size_t j = 0; j < c.columns; j++){
            std::cout << c(i,j) << '\t';
        }
        std::cout << '\n';
    }
}

/*----------------------------------------------------------------------------//
* SUBROUTINES
*-----------------------------------------------------------------------------*/

// Smaller function for Matrix multiply
array2D matmul(const array2D &A, const array2D &B){

    if (A.columns != B.rows){
        std::cout << "Incorrect inner dimensions for multiplication." << '\n';
        assert(A.columns == B.rows);
    }

    // Check to make sure we are creating C with an appropriate size
    array2D C(A.rows, B.columns);

    for (size_t i = 0; i < C.rows; i++){
        for (size_t j = 0; j < C.columns; j++){
            for (size_t k = 0; k < A.columns; k++){
                C(i, j) += A(i, k) * B(k, j);
            }
        }
    }

    return C;
}

// Function for Conj Gradient -- All the big stuff happens here

void conjgrad(const array2D &A, const array2D &b, array2D &x_0, double thresh){

    // Not working. Messily break if someone tries to use it.
    std::cout << "Not working" << '\n';
    assert(thresh < 0);

    array2D r(x_0.rows, x_0.columns), p(x_0.rows,x_0.columns);
    double alpha, diff;

    // definingin first r
    array2D r_0 = matdiff(b, matmul(A,x_0));

    // setting x arbitrarily high to start
    array2D x = matscale(x_0, 4);

    // *grumble... gustorn... grumble*
    array2D p_0 = matscale(r_0,1);
/*
    while (diff > thresh){
    }
*/
}

// Function for scaling
array2D matadd(const array2D &A, const array2D &B){

    if (A.rows != B.rows || A.columns != B.columns){
        std::cout << "incorrect dimensions with addition" << '\n';
        assert(A.rows == B.rows || A.columns == B.columns);
    }

    array2D C(A.rows, B.columns);

    for (size_t i = 0; i < C.rows; i++){
        for (size_t j = 0; j < C.columns; j++){
            C(i, j) = A(i, j) + B(i, j);
        }
    }

    return C;
}

// Function for scaling
array2D matdiff(const array2D &A, const array2D &B){

    if (A.rows != B.rows || A.columns != B.columns){
        std::cout << "incorrect dimensions with addition" << '\n';
        assert(A.rows == B.rows || A.columns == B.columns);
    }

    array2D C(A.rows, B.columns);

    for (size_t i = 0; i < C.rows; i++){
        for (size_t j = 0; j < C.columns; j++){
            C(i, j) = A(i, j) - B(i, j);
        }
    }

    return C;
}

// Function for scaling
array2D matscale(const array2D &A, double scale){

    array2D C(A.rows, A.columns);

    for (size_t i = 0; i < C.rows; i++){
        for (size_t j = 0; j < C.columns; j++){
            C(i, j) = A(i, j) * scale;
        }
    }

    return C;
}

// Function for finding magnitude for a single columned array
// Note: We should probably set this function to work for all types of matrices
double matmag(const array2D &A){
    double mag = 0;

    if (A.columns > 1){
        std::cout << "Not implemented yet for larger than 1 column." << '\n';
        assert(A.columns < 1);
    }

    for (size_t i = 0; i < A.rows; i++){
        mag += A(i,0)*A(i,0);
    }

    mag = sqrt(mag);
    return mag;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_obus_scominit.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_io_obus_scominit.C
/// @brief Invoke OBUS initfile
///
//----------------------------------------------------------------------------
// *HWP HWP Owner       : Chris Steffen <cwsteffen@us.ibm.com>
// *HWP HWP Backup Owner: Gary Peterson <garyp@us.ibm.com>
// *HWP FW Owner        : Sumit Kumar <sumit_kumar@in.ibm.com>
// *HWP Team            : IO
// *HWP Level           : 2
// *HWP Consumed by     : FSP:HB
//----------------------------------------------------------------------------
//
// @verbatim
// High-level procedure flow:
//
//   Invoke OBUS scominit file.
//
// Procedure Prereq:
//   - System clocks are running.
// @endverbatim
//----------------------------------------------------------------------------

//------------------------------------------------------------------------------
//  Includes
//------------------------------------------------------------------------------
#include <p9_io_scom.H>
#include <p9_io_regs.H>
#include <p9_io_obus_scominit.H>

//------------------------------------------------------------------------------
//  Constant definitions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------

// HWP entry point, comments in header
fapi2::ReturnCode p9_io_obus_scominit(
    const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& i_target,
    const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& i_connected_target)
{
    // mark HWP entry
    FAPI_INF("p9_io_obus_scominit: Entering...");
    fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS;

    // get system target
    const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_system_target;

    // assert IO reset to power-up bus endpoint logic
    // read-modify-write, set single reset bit (HW auto-clears)
    // on writeback
    FAPI_TRY(io::rmw(OPT_IORESET_HARD_BUS0, i_target, 0, 0, 1));

    FAPI_INF("Invoke FAPI procedure core: input_target");
//TODO:
#if 0
    FAPI_EXEC_HWP(rc, p9_obus_scom, i_target, l_system_target);
#endif

    FAPI_INF("Invoke FAPI procedure core: connected_target");
//TODO:
#if 0
    FAPI_EXEC_HWP(rc, p9_obus_scom, i_connected_target, l_system_target);
#endif

    // mark HWP exit
    FAPI_INF("p9_io_obus_scominit: ...Exiting");

fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>Scominit Reset and Delay Update<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_obus_scominit.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_io_obus_scominit.C
/// @brief Invoke OBUS initfile
///
//----------------------------------------------------------------------------
// *HWP HWP Owner       : Chris Steffen <cwsteffen@us.ibm.com>
// *HWP HWP Backup Owner: Gary Peterson <garyp@us.ibm.com>
// *HWP FW Owner        : Sumit Kumar <sumit_kumar@in.ibm.com>
// *HWP Team            : IO
// *HWP Level           : 2
// *HWP Consumed by     : FSP:HB
//----------------------------------------------------------------------------
//
// @verbatim
// High-level procedure flow:
//
//   Invoke OBUS scominit file.
//
// Procedure Prereq:
//   - System clocks are running.
// @endverbatim
//----------------------------------------------------------------------------

//------------------------------------------------------------------------------
//  Includes
//------------------------------------------------------------------------------
#include <p9_io_scom.H>
#include <p9_io_regs.H>
#include <p9_io_obus_scominit.H>

//------------------------------------------------------------------------------
//  Constant definitions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------

// HWP entry point, comments in header
fapi2::ReturnCode p9_io_obus_scominit(
    const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& i_target,
    const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& i_connected_target)
{
    // mark HWP entry
    FAPI_INF("p9_io_obus_scominit: Entering...");
    const uint8_t GROUP_00 = 0;
    const uint8_t LANE_00  = 0;
    const uint8_t SET_RESET = 1;
    const uint8_t CLEAR_RESET = 0;
    fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS;

    // get system target
    const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_system_target;

    // assert IO reset to power-up bus endpoint logic
    FAPI_TRY( io::rmw( OPT_IORESET_HARD_BUS0, i_target, GROUP_00, LANE_00, SET_RESET ) );

    // Bus Reset is relatively fast, only needing < a hundred cycles to allow the signal to propogate.
    FAPI_TRY( fapi2::delay( 10, 1000 ) );

    FAPI_TRY( io::rmw( OPT_IORESET_HARD_BUS0, i_target, GROUP_00, LANE_00, CLEAR_RESET ) );

    FAPI_INF("Invoke FAPI procedure core: input_target");
//TODO:
#if 0
    FAPI_EXEC_HWP(rc, p9_obus_scom, i_target, l_system_target);
#endif

    FAPI_INF("Invoke FAPI procedure core: connected_target");
//TODO:
#if 0
    FAPI_EXEC_HWP(rc, p9_obus_scom, i_connected_target, l_system_target);
#endif

    // mark HWP exit
    FAPI_INF("p9_io_obus_scominit: ...Exiting");

fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h"

#include <string>

#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_ip_address.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_ip_address_family.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"

namespace quic {

QuicSocketAddress::QuicSocketAddress(QuicIpAddress address, uint16_t port)
    : host_(address), port_(port) {}

QuicSocketAddress::QuicSocketAddress(const struct sockaddr_storage& saddr) {
  switch (saddr.ss_family) {
    case AF_INET: {
      const sockaddr_in* v4 = reinterpret_cast<const sockaddr_in*>(&saddr);
      host_ = QuicIpAddress(v4->sin_addr);
      port_ = ntohs(v4->sin_port);
      break;
    }
    case AF_INET6: {
      const sockaddr_in6* v6 = reinterpret_cast<const sockaddr_in6*>(&saddr);
      host_ = QuicIpAddress(v6->sin6_addr);
      port_ = ntohs(v6->sin6_port);
      break;
    }
    default:
      QUIC_BUG << "Unknown address family passed: " << saddr.ss_family;
      break;
  }
}

QuicSocketAddress::QuicSocketAddress(const sockaddr* saddr, socklen_t len) {
  sockaddr_storage storage;
  static_assert(std::numeric_limits<socklen_t>::max() >= sizeof(storage),
                "Cannot cast sizeof(storage) to socklen_t as it does not fit");
  if (len < static_cast<socklen_t>(sizeof(sockaddr)) ||
      (saddr->sa_family == AF_INET &&
       len < static_cast<socklen_t>(sizeof(sockaddr_in))) ||
      (saddr->sa_family == AF_INET6 &&
       len < static_cast<socklen_t>(sizeof(sockaddr_in6))) ||
      len > static_cast<socklen_t>(sizeof(storage))) {
    QUIC_BUG << "Socket address of invalid length provided";
    return;
  }
  memcpy(&storage, saddr, len);
  *this = QuicSocketAddress(storage);
}

bool operator==(const QuicSocketAddress& lhs, const QuicSocketAddress& rhs) {
  return lhs.host_ == rhs.host_ && lhs.port_ == rhs.port_;
}

bool operator!=(const QuicSocketAddress& lhs, const QuicSocketAddress& rhs) {
  return !(lhs == rhs);
}

bool QuicSocketAddress::IsInitialized() const {
  return host_.IsInitialized();
}

std::string QuicSocketAddress::ToString() const {
  switch (host_.address_family()) {
    case IpAddressFamily::IP_V4:
      return QuicStrCat(host_.ToString(), ":", port_);
    case IpAddressFamily::IP_V6:
      return QuicStrCat("[", host_.ToString(), "]:", port_);
    default:
      return "";
  }
}

int QuicSocketAddress::FromSocket(int fd) {
  sockaddr_storage addr;
  socklen_t addr_len = sizeof(addr);
  int result = getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &addr_len);

  bool success = result == 0 && addr_len > 0 &&
                 static_cast<size_t>(addr_len) <= sizeof(addr);
  if (success) {
    *this = QuicSocketAddress(addr);
    return 0;
  }
  return -1;
}

QuicSocketAddress QuicSocketAddress::Normalized() const {
  return QuicSocketAddress(host_.Normalized(), port_);
}

QuicIpAddress QuicSocketAddress::host() const {
  return host_;
}

uint16_t QuicSocketAddress::port() const {
  return port_;
}

sockaddr_storage QuicSocketAddress::generic_address() const {
  union {
    sockaddr_storage storage;
    sockaddr_in v4;
    sockaddr_in6 v6;
  } result;
  memset(&result.storage, 0, sizeof(result.storage));

  switch (host_.address_family()) {
    case IpAddressFamily::IP_V4:
      result.v4.sin_family = AF_INET;
      result.v4.sin_addr = host_.GetIPv4();
      result.v4.sin_port = htons(port_);
      break;
    case IpAddressFamily::IP_V6:
      result.v6.sin6_family = AF_INET6;
      result.v6.sin6_addr = host_.GetIPv6();
      result.v6.sin6_port = htons(port_);
      break;
    default:
      result.storage.ss_family = AF_UNSPEC;
      break;
  }
  return result.storage;
}

}  // namespace quic
<commit_msg>Include <limits> in quic_socket_address.cc for std::numeric_limits.<commit_after>// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h"

#include <limits>
#include <string>

#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_ip_address.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_ip_address_family.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"

namespace quic {

QuicSocketAddress::QuicSocketAddress(QuicIpAddress address, uint16_t port)
    : host_(address), port_(port) {}

QuicSocketAddress::QuicSocketAddress(const struct sockaddr_storage& saddr) {
  switch (saddr.ss_family) {
    case AF_INET: {
      const sockaddr_in* v4 = reinterpret_cast<const sockaddr_in*>(&saddr);
      host_ = QuicIpAddress(v4->sin_addr);
      port_ = ntohs(v4->sin_port);
      break;
    }
    case AF_INET6: {
      const sockaddr_in6* v6 = reinterpret_cast<const sockaddr_in6*>(&saddr);
      host_ = QuicIpAddress(v6->sin6_addr);
      port_ = ntohs(v6->sin6_port);
      break;
    }
    default:
      QUIC_BUG << "Unknown address family passed: " << saddr.ss_family;
      break;
  }
}

QuicSocketAddress::QuicSocketAddress(const sockaddr* saddr, socklen_t len) {
  sockaddr_storage storage;
  static_assert(std::numeric_limits<socklen_t>::max() >= sizeof(storage),
                "Cannot cast sizeof(storage) to socklen_t as it does not fit");
  if (len < static_cast<socklen_t>(sizeof(sockaddr)) ||
      (saddr->sa_family == AF_INET &&
       len < static_cast<socklen_t>(sizeof(sockaddr_in))) ||
      (saddr->sa_family == AF_INET6 &&
       len < static_cast<socklen_t>(sizeof(sockaddr_in6))) ||
      len > static_cast<socklen_t>(sizeof(storage))) {
    QUIC_BUG << "Socket address of invalid length provided";
    return;
  }
  memcpy(&storage, saddr, len);
  *this = QuicSocketAddress(storage);
}

bool operator==(const QuicSocketAddress& lhs, const QuicSocketAddress& rhs) {
  return lhs.host_ == rhs.host_ && lhs.port_ == rhs.port_;
}

bool operator!=(const QuicSocketAddress& lhs, const QuicSocketAddress& rhs) {
  return !(lhs == rhs);
}

bool QuicSocketAddress::IsInitialized() const {
  return host_.IsInitialized();
}

std::string QuicSocketAddress::ToString() const {
  switch (host_.address_family()) {
    case IpAddressFamily::IP_V4:
      return QuicStrCat(host_.ToString(), ":", port_);
    case IpAddressFamily::IP_V6:
      return QuicStrCat("[", host_.ToString(), "]:", port_);
    default:
      return "";
  }
}

int QuicSocketAddress::FromSocket(int fd) {
  sockaddr_storage addr;
  socklen_t addr_len = sizeof(addr);
  int result = getsockname(fd, reinterpret_cast<sockaddr*>(&addr), &addr_len);

  bool success = result == 0 && addr_len > 0 &&
                 static_cast<size_t>(addr_len) <= sizeof(addr);
  if (success) {
    *this = QuicSocketAddress(addr);
    return 0;
  }
  return -1;
}

QuicSocketAddress QuicSocketAddress::Normalized() const {
  return QuicSocketAddress(host_.Normalized(), port_);
}

QuicIpAddress QuicSocketAddress::host() const {
  return host_;
}

uint16_t QuicSocketAddress::port() const {
  return port_;
}

sockaddr_storage QuicSocketAddress::generic_address() const {
  union {
    sockaddr_storage storage;
    sockaddr_in v4;
    sockaddr_in6 v6;
  } result;
  memset(&result.storage, 0, sizeof(result.storage));

  switch (host_.address_family()) {
    case IpAddressFamily::IP_V4:
      result.v4.sin_family = AF_INET;
      result.v4.sin_addr = host_.GetIPv4();
      result.v4.sin_port = htons(port_);
      break;
    case IpAddressFamily::IP_V6:
      result.v6.sin6_family = AF_INET6;
      result.v6.sin6_addr = host_.GetIPv6();
      result.v6.sin6_port = htons(port_);
      break;
    default:
      result.storage.ss_family = AF_UNSPEC;
      break;
  }
  return result.storage;
}

}  // namespace quic
<|endoftext|>


<commit_before>#include <deque>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include "zqrpc/ZSocket.hpp"

namespace zqrpc {

struct Client {
	typedef std::vector<std::string> FramesT;
	zmq::context_t* context_;
	ZSocket socket_;
	const char* url_;
	std::size_t nextreply_;

	Client(zmq::context_t* context, const char* url) :
		context_(context),
		socket_(context,ZMQ_DEALER,boost::lexical_cast<std::string>(boost::this_thread::get_id())),
		url_(url),
		nextreply_(0) {
		socket_.connect(url);
	}

	~Client() {
		socket_.disconnect(url_);
		socket_.close();
	}

	void Send(FramesT frames) {
		bool status = socket_.Send<FramesT>(frames);
		if (!status) throw zqrpc::RetryException();
	}

	FramesT Recv() {
		socket_.Poll(5000);
		return socket_.NonBlockingRecv<FramesT>();
	}

};
}

int main(int argc, char *argv[])
{
	if (argc==1) {
		std::cerr << "Usage : " << argv[0] << " params" << std::endl;
		std::cerr << "Params " << " b: blank, n: request id, i: identity, f: sample pb function , x: sample data" << std::endl;
		exit(1);
	}
	google::InitGoogleLogging(argv[0]);
	try {
		zmq::context_t context;
		zqrpc::Client client(&context,"tcp://127.0.0.1:9089");
		zqrpc::Client::FramesT frames;
		for (int i=1;i<argc;++i) {
			std::string item(argv[i]);
			if (item=="b") item = std::string("");
			if (item=="n") item = boost::lexical_cast<std::string>(++client.nextreply_);
			if (item=="i") item = boost::lexical_cast<std::string>(boost::this_thread::get_id());
			if (item=="f") item = std::string("echo.EchoService.Echo1");
			if (item=="x") {
				boost::format fmt("\n$123456789012345678901234567890");
				item = fmt.str();
			}
			frames.push_back(item);
		}
		client.Send(frames);
		frames = client.Recv();
		BOOST_FOREACH(std::string s, frames) { std::cerr << "## " << s.length() << " " << s << std::endl; }
	} catch (zqrpc::ZError& e) {
		DLOG(INFO) << "ZError THROWN" << std::endl;
	} catch (zqrpc::RetryException& e) {
		DLOG(INFO) << "Retry Exception THROWN" << std::endl;
	} catch (zmq::error_t& e) {
		DLOG(INFO) << "ZMQ ZERROR THROWN : " << e.what() << std::endl;
	}

}
<commit_msg>Wed Jul 23 15:19:41 IST 2014<commit_after>#include <deque>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include "zqrpc/ZSocket.hpp"

namespace zqrpc {

struct Client {
	typedef std::vector<std::string> FramesT;
	zmq::context_t* context_;
	ZSocket socket_;
	const char* url_;
	std::size_t nextreply_;

	Client(zmq::context_t* context, const char* url) :
		context_(context),
		socket_(context,ZMQ_DEALER,boost::lexical_cast<std::string>(boost::this_thread::get_id())),
		url_(url),
		nextreply_(0) {
		socket_.connect(url);
	}

	~Client() {
		socket_.disconnect(url_);
		socket_.close();
	}

	void Send(FramesT frames) {
		bool status = socket_.Send<FramesT>(frames);
		if (!status) throw zqrpc::RetryException();
	}

	FramesT Recv() {
		socket_.Poll(5000);
		return socket_.NonBlockingRecv<FramesT>();
	}

};
}

int main(int argc, char *argv[])
{
	if (argc==1) {
		std::cerr << "Usage : " << argv[0] << " params" << std::endl;
		std::cerr << "Params " << " b: blank, n: request id, i: identity, f: sample pb function , x: sample data" << std::endl;
		exit(1);
	}
	google::InitGoogleLogging(argv[0]);
	try {
		zmq::context_t context;
		zqrpc::Client client(&context,"tcp://127.0.0.1:9089");
		zqrpc::Client::FramesT frames;
		for (int i=1;i<argc;++i) {
			std::string item(argv[i]);
			if (item=="b") item = std::string("");
			if (item=="n") item = boost::lexical_cast<std::string>(++client.nextreply_);
			if (item=="i") item = boost::lexical_cast<std::string>(boost::this_thread::get_id());
			if (item=="f") item = std::string("echo.EchoService.Echo1");
			if (item=="x") {
				boost::format fmt("\n$123456789012345678901234567890");
				item = fmt.str();
			}
			frames.push_back(item);
		}
		BOOST_FOREACH(std::string s, frames) { std::cerr << "OUT## " << s.length() << " " << s << std::endl; }
		client.Send(frames);
		frames = client.Recv();
		BOOST_FOREACH(std::string s, frames) { std::cerr << " IN## " << s.length() << " " << s << std::endl; }
	} catch (zqrpc::ZError& e) {
		DLOG(INFO) << "ZError THROWN" << std::endl;
	} catch (zqrpc::RetryException& e) {
		DLOG(INFO) << "Retry Exception THROWN" << std::endl;
	} catch (zmq::error_t& e) {
		DLOG(INFO) << "ZMQ ZERROR THROWN : " << e.what() << std::endl;
	}

}
<|endoftext|>


<commit_before>#include "p0run/default_garbage_collector.hpp"
#include "p0run/object.hpp"
#include "p0run/raw_storage.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include <algorithm>
#include <array>
using namespace p0::run;

namespace
{
	typedef int vector_safe_bool;

	struct gc_tester : p0::run::object
	{
		explicit gc_tester(vector_safe_bool &is_alive)
			: m_is_alive(is_alive)
		{
			m_is_alive = true;
		}

		virtual ~gc_tester()
		{
			m_is_alive = false;
		}

	private:

		vector_safe_bool &m_is_alive;

		virtual void mark_recursively() PROTOLANG0_OVERRIDE
		{
		}
	};
}

BOOST_AUTO_TEST_CASE(default_gc_test)
{
	std::vector<vector_safe_bool> alive_status(64);

	p0::run::default_garbage_collector gc;

	std::vector<p0::run::object *> test_objects;

	BOOST_FOREACH (auto &is_alive, alive_status)
	{
		test_objects.push_back(
					&construct<gc_tester>(gc, is_alive));
	}

	//all created objects are expected to be alive before garbage collection
	BOOST_CHECK(std::all_of(alive_status.begin(),
							alive_status.end(),
							[](bool a) { return a; }));

	//not strictly required here, but called in practice before marking
	gc.unmark();

	//mark the first half of the objects as required to be alive
	std::for_each(test_objects.begin(),
				  test_objects.begin() + test_objects.size() / 2,
				  [](p0::run::object *object)
	{
		object->mark();
	});

	//let the gc destroy unneeded objects
	gc.sweep(p0::run::sweep_mode::full);

	//the marked half is expected to be still alive
	BOOST_CHECK(std::all_of(alive_status.begin(),
							alive_status.begin() + alive_status.size() / 2,
							[](bool a) { return a; }));

	//the half not marked is expected to not be alive after sweep
	BOOST_CHECK(std::all_of(alive_status.begin() + alive_status.size() / 2,
							alive_status.end(),
							[](bool a) { return !a; }));
}

namespace
{
	struct referencing_gc_tester PROTOLANG0_FINAL_CLASS : gc_tester
	{
		p0::run::value reference;

		referencing_gc_tester(vector_safe_bool &is_alive)
			: gc_tester(is_alive)
		{
		}

	private:

		virtual void mark_recursively() PROTOLANG0_FINAL_METHOD
		{
			mark_value(reference);
		}
	};

	bool test_dependency_cycle(size_t cycle_length, bool is_marked)
	{
		std::vector<vector_safe_bool> is_alive(cycle_length);
		p0::run::default_garbage_collector gc;
		{
			std::vector<referencing_gc_tester *> test_objects(cycle_length);
			for (size_t i = 0; i < is_alive.size(); ++i)
			{
				test_objects[i] = &dynamic_cast<referencing_gc_tester &>(
					construct<referencing_gc_tester>(gc, is_alive[i]));
			}
			for (size_t i = 0; i < test_objects.size(); ++i)
			{
				test_objects[i]->reference = p0::run::value(
							*test_objects[(i + 1) % test_objects.size()]);
			}
			gc.unmark();
			if (is_marked)
			{
				test_objects.front()->mark();
			}
		}
		gc.sweep(p0::run::sweep_mode::full);
		return std::count(begin(is_alive), end(is_alive), !is_marked) == 0;
	}
}

BOOST_AUTO_TEST_CASE(default_gc_cycle_test)
{
	BOOST_CHECK(test_dependency_cycle(1, true));
	BOOST_CHECK(test_dependency_cycle(2, true));
	BOOST_CHECK(test_dependency_cycle(3, true));
	BOOST_CHECK(test_dependency_cycle(4, true));
	BOOST_CHECK(test_dependency_cycle(20, true));

	BOOST_CHECK(test_dependency_cycle(1, false));
	BOOST_CHECK(test_dependency_cycle(2, false));
	BOOST_CHECK(test_dependency_cycle(3, false));
	BOOST_CHECK(test_dependency_cycle(4, false));
	BOOST_CHECK(test_dependency_cycle(20, false));
}

BOOST_AUTO_TEST_CASE(default_gc_deallocate_test)
{
	p0::run::default_garbage_collector gc;
	std::array<size_t, 5> const deallocate_order =
	{{
		3, 2, 4, 0, 1
	}};
	std::array<char *, 5> memory;
	size_t next_size = 1;
	std::generate(begin(memory),
				  end(memory),
				  [&]() -> char *
	{
		char * const allocated = gc.allocate(next_size);

		//check that there is valid memory
		std::memset(allocated, 0xff, next_size);

		next_size *= 4;
		return allocated;
	});

	for (size_t i = 0; i < memory.size(); ++i)
	{
		char * const allocated = memory[deallocate_order[i]];
		gc.deallocate(allocated);
	}
}
<commit_msg>fix include for construct()<commit_after>#include "p0run/default_garbage_collector.hpp"
#include "p0run/object.hpp"
#include "p0run/construct.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/foreach.hpp>
#include <algorithm>
#include <array>
using namespace p0::run;

namespace
{
	typedef int vector_safe_bool;

	struct gc_tester : p0::run::object
	{
		explicit gc_tester(vector_safe_bool &is_alive)
			: m_is_alive(is_alive)
		{
			m_is_alive = true;
		}

		virtual ~gc_tester()
		{
			m_is_alive = false;
		}

	private:

		vector_safe_bool &m_is_alive;

		virtual void mark_recursively() PROTOLANG0_OVERRIDE
		{
		}
	};
}

BOOST_AUTO_TEST_CASE(default_gc_test)
{
	std::vector<vector_safe_bool> alive_status(64);

	p0::run::default_garbage_collector gc;

	std::vector<p0::run::object *> test_objects;

	BOOST_FOREACH (auto &is_alive, alive_status)
	{
		test_objects.push_back(
					&construct<gc_tester>(gc, is_alive));
	}

	//all created objects are expected to be alive before garbage collection
	BOOST_CHECK(std::all_of(alive_status.begin(),
							alive_status.end(),
							[](bool a) { return a; }));

	//not strictly required here, but called in practice before marking
	gc.unmark();

	//mark the first half of the objects as required to be alive
	std::for_each(test_objects.begin(),
				  test_objects.begin() + test_objects.size() / 2,
				  [](p0::run::object *object)
	{
		object->mark();
	});

	//let the gc destroy unneeded objects
	gc.sweep(p0::run::sweep_mode::full);

	//the marked half is expected to be still alive
	BOOST_CHECK(std::all_of(alive_status.begin(),
							alive_status.begin() + alive_status.size() / 2,
							[](bool a) { return a; }));

	//the half not marked is expected to not be alive after sweep
	BOOST_CHECK(std::all_of(alive_status.begin() + alive_status.size() / 2,
							alive_status.end(),
							[](bool a) { return !a; }));
}

namespace
{
	struct referencing_gc_tester PROTOLANG0_FINAL_CLASS : gc_tester
	{
		p0::run::value reference;

		referencing_gc_tester(vector_safe_bool &is_alive)
			: gc_tester(is_alive)
		{
		}

	private:

		virtual void mark_recursively() PROTOLANG0_FINAL_METHOD
		{
			mark_value(reference);
		}
	};

	bool test_dependency_cycle(size_t cycle_length, bool is_marked)
	{
		std::vector<vector_safe_bool> is_alive(cycle_length);
		p0::run::default_garbage_collector gc;
		{
			std::vector<referencing_gc_tester *> test_objects(cycle_length);
			for (size_t i = 0; i < is_alive.size(); ++i)
			{
				test_objects[i] = &dynamic_cast<referencing_gc_tester &>(
					construct<referencing_gc_tester>(gc, is_alive[i]));
			}
			for (size_t i = 0; i < test_objects.size(); ++i)
			{
				test_objects[i]->reference = p0::run::value(
							*test_objects[(i + 1) % test_objects.size()]);
			}
			gc.unmark();
			if (is_marked)
			{
				test_objects.front()->mark();
			}
		}
		gc.sweep(p0::run::sweep_mode::full);
		return std::count(begin(is_alive), end(is_alive), !is_marked) == 0;
	}
}

BOOST_AUTO_TEST_CASE(default_gc_cycle_test)
{
	BOOST_CHECK(test_dependency_cycle(1, true));
	BOOST_CHECK(test_dependency_cycle(2, true));
	BOOST_CHECK(test_dependency_cycle(3, true));
	BOOST_CHECK(test_dependency_cycle(4, true));
	BOOST_CHECK(test_dependency_cycle(20, true));

	BOOST_CHECK(test_dependency_cycle(1, false));
	BOOST_CHECK(test_dependency_cycle(2, false));
	BOOST_CHECK(test_dependency_cycle(3, false));
	BOOST_CHECK(test_dependency_cycle(4, false));
	BOOST_CHECK(test_dependency_cycle(20, false));
}

BOOST_AUTO_TEST_CASE(default_gc_deallocate_test)
{
	p0::run::default_garbage_collector gc;
	std::array<size_t, 5> const deallocate_order =
	{{
		3, 2, 4, 0, 1
	}};
	std::array<char *, 5> memory;
	size_t next_size = 1;
	std::generate(begin(memory),
				  end(memory),
				  [&]() -> char *
	{
		char * const allocated = gc.allocate(next_size);

		//check that there is valid memory
		std::memset(allocated, 0xff, next_size);

		next_size *= 4;
		return allocated;
	});

	for (size_t i = 0; i < memory.size(); ++i)
	{
		char * const allocated = memory[deallocate_order[i]];
		gc.deallocate(allocated);
	}
}
<|endoftext|>


<commit_before>void rec() {
  AliReconstruction reco;

  reco.SetWriteESDfriend();
  reco.SetWriteAlignmentData();

  reco.SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  reco.SetSpecificStorage("GRP/GRP/Data",
			  Form("local://%s",gSystem->pwd()));

  TStopwatch timer;
  timer.Start();
  reco.Run();
  timer.Stop();
  timer.Print();
}
<commit_msg>High multiplicity settings<commit_after>void rec() {
  AliReconstruction reco;

  reco.SetWriteESDfriend();
  reco.SetWriteAlignmentData();

  reco.SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  reco.SetSpecificStorage("GRP/GRP/Data",
			  Form("local://%s",gSystem->pwd()));

  // High multiplicity settings
  Double_t cuts[]={33, 0.1, 0.1, 0.05, 0.99, 0.9, 100};
  AliV0vertexer::SetDefaultCuts(cuts);
  Double_t cts[]={33., 0.05, 0.008, 0.035, 0.1, 0.9985, 0.9,100};
  AliCascadeVertexer::SetDefaultCuts(cts);

  TStopwatch timer;
  timer.Start();
  reco.Run();
  timer.Stop();
  timer.Print();
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <map>

#include <seqan/sequence.h>
#include <seqan/file.h>
#define SEQAN_PROFILE

using namespace seqan;
using namespace std;

int main(int argc, char* argv[]){
    SEQAN_PROTIMESTART(loadTime);
    MultiSeqFile multiSeqFile;
    if (argc < 2 || !open(multiSeqFile.concat, argv[1], OPEN_RDONLY))
        return 1;
    AutoSeqFormat format;
    guessFormat(multiSeqFile.concat, format);
    split(multiSeqFile, format);
    unsigned seqCount = length(multiSeqFile);
    StringSet<String<Dna5Q> > seqs;
    StringSet<CharString> seqIDs;
    reserve(seqs, seqCount, Exact());
    reserve(seqIDs, seqCount, Exact());
    String<Dna5Q> seq;
    CharString qual;
    CharString id;
    for (unsigned i = 0; i < seqCount; ++i)
    {
        assignSeq(seq, multiSeqFile[i], format);    // read sequence
        assignQual(qual, multiSeqFile[i], format);  // read ascii quality values
        assignSeqId(id, multiSeqFile[i], format);   // read sequence id

        // convert ascii to values from 0..62
        // store dna and quality together in Dna5Q
        for (unsigned j = 0; j < length(qual) && j < length(seq); ++j)
            assignQualityValue(seq[j], (int)(ordValue(qual[j]) - 33));
        // we use reserve and append, as assign is not supported
        // by StringSet<..., Owner<ConcatDirect<> > >
        appendValue(seqs, seq, Generous());
        appendValue(seqIDs, id, Generous());
    }
    std::cout << "Loading " << seqCount << " sequences took " << SEQAN_PROTIMEDIFF(loadTime);
    std::cout << " seconds." << std::endl << std::endl;
    //for (unsigned i = 0; i < seqCount && i < 10; ++i){
    //    std::cout << '>' << seqIDs[i] << std::endl;
    //    std::cout << seqs[i] << std::endl;
    //}
    return 0;
}
<commit_msg>Filter RNA-seq reads based on the quality<commit_after>#include <fstream>
#include <iostream>
#include <string>
#include <ctime>

#include <seqan/sequence.h>
#include <seqan/file.h>

using namespace seqan;
using namespace std;

int main(int argc, char* argv[]){
    clock_t tStart = clock();

    MultiSeqFile multiSeqFile;
    if (argc < 4 || !open(multiSeqFile.concat, argv[3], OPEN_RDONLY)){
        std::cout << "Usage: Filter_RNA-seq <quality-threshold> <read-length> <RNA-seq-file>" << std::endl;
        std::cout << std::endl;
        return 1;
    }
    //Output File
    string name(argv[3]);
    size_t k = name.rfind(".");
    if(k != string::npos && k>0){
        name = name.substr(0,k);
    }

    name += ".fa";
    std::cout << name << std::endl;
    std::ofstream out_file;
    out_file.open(name.c_str());

    //Threshold
    int threshold;
    std::istringstream ss(argv[1]);
    ss >> threshold;
    //Read Length
    int read_length;
    std::istringstream ss_length(argv[2]);
    ss_length >> read_length;

    //RNASeq Processing
    AutoSeqFormat format;
    guessFormat(multiSeqFile.concat, format);
    split(multiSeqFile, format);
    unsigned seqCount = length(multiSeqFile);

    String<Dna5Q> seq;
    CharString qual;
    CharString id;
    for (unsigned i = 0; i < seqCount; ++i){
        assignSeq(seq, multiSeqFile[i], format);    // read sequence
        assignQual(qual, multiSeqFile[i], format);  // read ascii quality values
        assignSeqId(id, multiSeqFile[i], format);   // read sequence id

        //std::cout << id << std::endl;
        //std::cout << seq << std::endl;
        // convert ascii to values from 0..62
        int pos = 0;
        string filt_seq = "";
        for (unsigned j = 0; j < length(qual) && j < length(seq); ++j){
            assignQualityValue(seq[j], (int)(ordValue(qual[j]) - 33));
            //std::cout << getQualityValue(seq[j]) << " ";
            if(getQualityValue(seq[j]) >= threshold){
                filt_seq += seq[j];
                pos++;
            }else{
                if(pos >= read_length){
                    //std::cout << filt_seq << std::endl;
                    write(out_file, filt_seq, id, Fasta());
                }
                pos=0;
                filt_seq = "";
            }
        }
        if(pos >= read_length){
            //std::cout << filt_seq << std::endl;
            write(out_file, filt_seq, id, Fasta());
        }
        //std::cout << std::endl;
    }

    std::cerr << "Loading " << seqCount << " sequences took " << (double)(clock() - tStart)/CLOCKS_PER_SEC;
    std::cerr << " seconds." << std::endl << std::endl;
    out_file.close();
    return 0;
}
<|endoftext|>


<commit_before>
#include <iostream>
#include <Eigen/Core>
#include <bench/BenchTimer.h>

using namespace Eigen;
using namespace std;

#define END 9

template<int S> struct map_size { enum { ret = S }; };
template<>  struct map_size<10> { enum { ret = 20 }; };
template<>  struct map_size<11> { enum { ret = 50 }; };
template<>  struct map_size<12> { enum { ret = 100 }; };
template<>  struct map_size<13> { enum { ret = 300 }; };

template<int M, int N,int K> struct alt_prod
{
  enum {
    ret = M==1 && N==1 ? InnerProduct
        : K==1 ? OuterProduct
        : M==1 ? GemvProduct
        : N==1 ? GemvProduct
        : GemmProduct
  };
};

void print_mode(int mode)
{
  if(mode==InnerProduct) std::cout << "i";
  if(mode==OuterProduct) std::cout << "o";
  if(mode==CoeffBasedProductMode) std::cout << "c";
  if(mode==LazyCoeffBasedProductMode) std::cout << "l";
  if(mode==GemvProduct) std::cout << "v";
  if(mode==GemmProduct) std::cout << "m";
}

template<int Mode, typename Lhs, typename Rhs, typename Res>
EIGEN_DONT_INLINE void prod(const Lhs& a, const Rhs& b, Res& c)
{
  c.noalias() += typename ProductReturnType<Lhs,Rhs,Mode>::Type(a,b);
}

template<int M, int N, int K, typename Scalar, int Mode>
EIGEN_DONT_INLINE void bench_prod()
{
  typedef Matrix<Scalar,M,K> Lhs; Lhs a; a.setRandom();
  typedef Matrix<Scalar,K,N> Rhs; Rhs b; b.setRandom();
  typedef Matrix<Scalar,M,N> Res; Res c; c.setRandom();

  BenchTimer t;
  double n = 2.*double(M)*double(N)*double(K);
  int rep = 100000./n;
  rep /= 2;
  if(rep<1) rep = 1;
  do {
    rep *= 2;
    t.reset();
    BENCH(t,1,rep,prod<CoeffBasedProductMode>(a,b,c));
  } while(t.best()<0.1);

  t.reset();
  BENCH(t,5,rep,prod<Mode>(a,b,c));

  print_mode(Mode);
  std::cout << int(1e-6*n*rep/t.best()) << "\t";
}

template<int N> struct print_n;
template<int M, int N, int K> struct loop_on_m;
template<int M, int N, int K, typename Scalar, int Mode> struct loop_on_n;

template<int M, int N, int K>
struct loop_on_k
{
  static void run()
  {
    std::cout << "K=" << K << "\t";
    print_n<N>::run();
    std::cout << "\n";

    loop_on_m<M,N,K>::run();
    std::cout << "\n\n";

    loop_on_k<M,N,K+1>::run();
  }
};

template<int M, int N>
struct loop_on_k<M,N,END> { static void run(){} };

template<int M, int N, int K>
struct loop_on_m
{
  static void run()
  {
    std::cout << M << "f\t";
    loop_on_n<M,N,K,float,CoeffBasedProductMode>::run();
    std::cout << "\n";

    std::cout << M << "f\t";
    loop_on_n<M,N,K,float,-1>::run();
    std::cout << "\n";

    loop_on_m<M+1,N,K>::run();
  }
};

template<int N, int K>
struct loop_on_m<END,N,K> { static void run(){} };

template<int M, int N, int K, typename Scalar, int Mode>
struct loop_on_n
{
  static void run()
  {
    bench_prod<M,N,K,Scalar,Mode==-1? alt_prod<M,N,K>::ret : Mode>();

    loop_on_n<M,N+1,K,Scalar,Mode>::run();
  }
};

template<int M, int K, typename Scalar, int Mode>
struct loop_on_n<M,END,K,Scalar,Mode> { static void run(){} };

template<int N> struct print_n
{
  static void run()
  {
    std::cout << map_size<N>::ret << "\t";
    print_n<N+1>::run();
  }
};

template<> struct print_n<END> { static void run(){} };

int main()
{
  loop_on_k<1,1,1>::run();

  return 0;
}
<commit_msg>Fixed line endings.<commit_after>
#include <iostream>
#include <Eigen/Core>
#include <bench/BenchTimer.h>

using namespace Eigen;
using namespace std;

#define END 9

template<int S> struct map_size { enum { ret = S }; };
template<>  struct map_size<10> { enum { ret = 20 }; };
template<>  struct map_size<11> { enum { ret = 50 }; };
template<>  struct map_size<12> { enum { ret = 100 }; };
template<>  struct map_size<13> { enum { ret = 300 }; };

template<int M, int N,int K> struct alt_prod
{
  enum {
    ret = M==1 && N==1 ? InnerProduct
        : K==1 ? OuterProduct
        : M==1 ? GemvProduct
        : N==1 ? GemvProduct
        : GemmProduct
  };
};

void print_mode(int mode)
{
  if(mode==InnerProduct) std::cout << "i";
  if(mode==OuterProduct) std::cout << "o";
  if(mode==CoeffBasedProductMode) std::cout << "c";
  if(mode==LazyCoeffBasedProductMode) std::cout << "l";
  if(mode==GemvProduct) std::cout << "v";
  if(mode==GemmProduct) std::cout << "m";
}

template<int Mode, typename Lhs, typename Rhs, typename Res>
EIGEN_DONT_INLINE void prod(const Lhs& a, const Rhs& b, Res& c)
{
  c.noalias() += typename ProductReturnType<Lhs,Rhs,Mode>::Type(a,b);
}

template<int M, int N, int K, typename Scalar, int Mode>
EIGEN_DONT_INLINE void bench_prod()
{
  typedef Matrix<Scalar,M,K> Lhs; Lhs a; a.setRandom();
  typedef Matrix<Scalar,K,N> Rhs; Rhs b; b.setRandom();
  typedef Matrix<Scalar,M,N> Res; Res c; c.setRandom();

  BenchTimer t;
  double n = 2.*double(M)*double(N)*double(K);
  int rep = 100000./n;
  rep /= 2;
  if(rep<1) rep = 1;
  do {
    rep *= 2;
    t.reset();
    BENCH(t,1,rep,prod<CoeffBasedProductMode>(a,b,c));
  } while(t.best()<0.1);

  t.reset();
  BENCH(t,5,rep,prod<Mode>(a,b,c));

  print_mode(Mode);
  std::cout << int(1e-6*n*rep/t.best()) << "\t";
}

template<int N> struct print_n;
template<int M, int N, int K> struct loop_on_m;
template<int M, int N, int K, typename Scalar, int Mode> struct loop_on_n;

template<int M, int N, int K>
struct loop_on_k
{
  static void run()
  {
    std::cout << "K=" << K << "\t";
    print_n<N>::run();
    std::cout << "\n";

    loop_on_m<M,N,K>::run();
    std::cout << "\n\n";

    loop_on_k<M,N,K+1>::run();
  }
};

template<int M, int N>
struct loop_on_k<M,N,END> { static void run(){} };

template<int M, int N, int K>
struct loop_on_m
{
  static void run()
  {
    std::cout << M << "f\t";
    loop_on_n<M,N,K,float,CoeffBasedProductMode>::run();
    std::cout << "\n";

    std::cout << M << "f\t";
    loop_on_n<M,N,K,float,-1>::run();
    std::cout << "\n";

    loop_on_m<M+1,N,K>::run();
  }
};

template<int N, int K>
struct loop_on_m<END,N,K> { static void run(){} };

template<int M, int N, int K, typename Scalar, int Mode>
struct loop_on_n
{
  static void run()
  {
    bench_prod<M,N,K,Scalar,Mode==-1? alt_prod<M,N,K>::ret : Mode>();

    loop_on_n<M,N+1,K,Scalar,Mode>::run();
  }
};

template<int M, int K, typename Scalar, int Mode>
struct loop_on_n<M,END,K,Scalar,Mode> { static void run(){} };

template<int N> struct print_n
{
  static void run()
  {
    std::cout << map_size<N>::ret << "\t";
    print_n<N+1>::run();
  }
};

template<> struct print_n<END> { static void run(){} };

int main()
{
  loop_on_k<1,1,1>::run();

  return 0;
}
<|endoftext|>


<commit_before>
#include <map>
#include <unistd.h>
#include <getopt.h>
#include <stdio.h>
#include <vector>
#include <stdio.h>
#include "utils.hpp"
#include "load.hpp"
#include "distr.hpp"
#include "config.hpp"
#include "client.hpp"
#include "args.hpp"
#include "memcached_sock_protocol.hpp"
#include "memcached_protocol.hpp"
#include "mysql_protocol.hpp"
#include "sqlite_protocol.hpp"
#include "sys/stat.h"

using namespace std;

protocol_t *make_protocol(protocol_enum_t protocol, config_t *config) {
    switch (protocol) {
        case protocol_mysql:
            return (protocol_t*) new mysql_protocol_t(config);
            break;
        case protocol_sockmemcached:
            return (protocol_t*) new memcached_sock_protocol_t(config);
            break;
        case protocol_libmemcached:
            return (protocol_t*) new memcached_protocol_t(config);
            break;
        case protocol_sqlite:
            return (protocol_t*) new sqlite_protocol_t(config);
            break;
        default:
            fprintf(stderr, "Unknown protocol\n");
            exit(-1);
    }
}

/* Tie it all together */
int main(int argc, char *argv[])
{
    // Initialize randomness
    srand(time(NULL));

    // Parse the arguments
    config_t config;
    parse(&config, argc, argv);
    if (config.load.verifies > 0 && config.clients > 1) {
        printf("Automatically enabled per-client key suffixes\n");
        config.keys.append_client_suffix = true;
    }
    config.print();

    /* make a directory for our sqlite files */
    if (config.db_file[0]) {
        mkdir(BACKUP_FOLDER, 0777);
    }

    // Gotta run the shared init for each server.
    for (int i = 0; i < config.servers.size(); i++) {
        protocol_t *p = make_protocol(config.servers[i].protocol, &config);
        p->connect(&config.servers[i]);
        p->shared_init();
        delete p;
    }

    for (int i = 0; i < config.clients; i++) {
        if (config.db_file[0]) {
            sqlite_protocol_t *sqlite = new sqlite_protocol_t(&config);
            sqlite->set_id(i);
            sqlite->connect(&config.servers[0]);
            sqlite->shared_init();
            delete sqlite;
        };
    }

    // Let's rock 'n roll
    int res;
    vector<pthread_t> threads(config.clients);

    // Create the shared structure
    shared_t shared(&config);

    client_data_t client_data[config.clients];
    for(int i = 0; i < config.clients; i++) {
        client_data[i].config = &config;
        client_data[i].server = &config.servers[i % config.servers.size()];
        client_data[i].shared = &shared;
        client_data[i].id = i;
        client_data[i].min_seed = 0;
        client_data[i].max_seed = 0;

        // Create and connect all protocols first to avoid weird TCP
        // timeout bugs
        client_data[i].proto = (*make_protocol)(client_data[i].server->protocol, &config);
        client_data[i].proto->connect(client_data[i].server);
        if (config.db_file[0]) {
            client_data[i].sqlite = new sqlite_protocol_t(&config);
            client_data[i].sqlite->set_id(i);
            client_data[i].sqlite->connect(client_data[i].server);
        } else {
            client_data[i].sqlite = NULL;
        }
    }

    // If input keys are provided, read them in
    if(config.in_file[0] != 0) {
        FILE *in_file = fopen(config.in_file, "r");

        if(in_file == NULL) {
            fprintf(stderr, "Could not open output key file\n");
            exit(-1);
        }

        while(feof(in_file) == 0) {
            int id, min_seed, max_seed;
            size_t res __attribute__((unused)) = fread(&id, sizeof(id), 1, in_file);
            res = fread(&min_seed, sizeof(min_seed), 1, in_file);
            res = fread(&max_seed, sizeof(max_seed), 1, in_file);

            client_data[id].min_seed = min_seed;
            client_data[id].max_seed = max_seed;
        }

        fclose(in_file);
    }

    // Create the threads
    for(int i = 0; i < config.clients; i++) {
        int res = pthread_create(&threads[i], NULL, run_client, &client_data[i]);
        if(res != 0) {
            fprintf(stderr, "Can't create thread\n");
            exit(-1);
        }
    }

    // Wait for the threads to finish
    for(int i = 0; i < config.clients; i++) {
        res = pthread_join(threads[i], NULL);
        if(res != 0) {
            fprintf(stderr, "Can't join on the thread\n");
            exit(-1);
        }
    }

    // Disconnect everyone
    for(int i = 0; i < config.clients; i++) {
        delete client_data[i].proto;
    }

    // Dump key vectors if we have an out file
    if(config.out_file[0] != 0) {
        FILE *out_file = fopen(config.out_file, "aw");

        // Dump the keys
        for(int i = 0; i < config.clients; i++) {
            client_data_t *cd = &client_data[i];
            fwrite(&cd->id, sizeof(cd->id), 1, out_file);
            fwrite(&cd->min_seed, sizeof(cd->min_seed), 1, out_file);
            fwrite(&cd->max_seed, sizeof(cd->max_seed), 1, out_file);
        }

        fclose(out_file);
    }

    return 0;
}

<commit_msg>Write client number to key output files and check on load.<commit_after>
#include <map>
#include <unistd.h>
#include <getopt.h>
#include <stdio.h>
#include <vector>
#include <stdio.h>
#include "utils.hpp"
#include "load.hpp"
#include "distr.hpp"
#include "config.hpp"
#include "client.hpp"
#include "args.hpp"
#include "memcached_sock_protocol.hpp"
#include "memcached_protocol.hpp"
#include "mysql_protocol.hpp"
#include "sqlite_protocol.hpp"
#include "sys/stat.h"

using namespace std;

protocol_t *make_protocol(protocol_enum_t protocol, config_t *config) {
    switch (protocol) {
        case protocol_mysql:
            return (protocol_t*) new mysql_protocol_t(config);
            break;
        case protocol_sockmemcached:
            return (protocol_t*) new memcached_sock_protocol_t(config);
            break;
        case protocol_libmemcached:
            return (protocol_t*) new memcached_protocol_t(config);
            break;
        case protocol_sqlite:
            return (protocol_t*) new sqlite_protocol_t(config);
            break;
        default:
            fprintf(stderr, "Unknown protocol\n");
            exit(-1);
    }
}

/* Tie it all together */
int main(int argc, char *argv[])
{
    // Initialize randomness
    srand(time(NULL));

    // Parse the arguments
    config_t config;
    parse(&config, argc, argv);
    if (config.load.verifies > 0 && config.clients > 1) {
        printf("Automatically enabled per-client key suffixes\n");
        config.keys.append_client_suffix = true;
    }
    config.print();

    /* make a directory for our sqlite files */
    if (config.db_file[0]) {
        mkdir(BACKUP_FOLDER, 0777);
    }

    // Gotta run the shared init for each server.
    for (int i = 0; i < config.servers.size(); i++) {
        protocol_t *p = make_protocol(config.servers[i].protocol, &config);
        p->connect(&config.servers[i]);
        p->shared_init();
        delete p;
    }

    for (int i = 0; i < config.clients; i++) {
        if (config.db_file[0]) {
            sqlite_protocol_t *sqlite = new sqlite_protocol_t(&config);
            sqlite->set_id(i);
            sqlite->connect(&config.servers[0]);
            sqlite->shared_init();
            delete sqlite;
        };
    }

    // Let's rock 'n roll
    int res;
    vector<pthread_t> threads(config.clients);

    // Create the shared structure
    shared_t shared(&config);

    client_data_t client_data[config.clients];
    for(int i = 0; i < config.clients; i++) {
        client_data[i].config = &config;
        client_data[i].server = &config.servers[i % config.servers.size()];
        client_data[i].shared = &shared;
        client_data[i].id = i;
        client_data[i].min_seed = 0;
        client_data[i].max_seed = 0;

        // Create and connect all protocols first to avoid weird TCP
        // timeout bugs
        client_data[i].proto = (*make_protocol)(client_data[i].server->protocol, &config);
        client_data[i].proto->connect(client_data[i].server);
        if (config.db_file[0]) {
            client_data[i].sqlite = new sqlite_protocol_t(&config);
            client_data[i].sqlite->set_id(i);
            client_data[i].sqlite->connect(client_data[i].server);
        } else {
            client_data[i].sqlite = NULL;
        }
    }

    // If input keys are provided, read them in
    if(config.in_file[0] != 0) {
        FILE *in_file = fopen(config.in_file, "r");

        if(in_file == NULL) {
            fprintf(stderr, "Could not open output key file\n");
            exit(-1);
        }

        int check_clients = 0;
        fread(&check_clients, sizeof(check_clients), 1, in_file);

        if (check_clients != config.clients) {
            fprintf(stderr, "Client number mismatch. Input file is for %d clients, attempted to run with %d.\n", check_clients, config.clients);
            exit(-1);
        }

        while(feof(in_file) == 0) {
            int id, min_seed, max_seed;
            size_t res __attribute__((unused)) = fread(&id, sizeof(id), 1, in_file);
            res = fread(&min_seed, sizeof(min_seed), 1, in_file);
            res = fread(&max_seed, sizeof(max_seed), 1, in_file);

            client_data[id].min_seed = min_seed;
            client_data[id].max_seed = max_seed;
        }

        fclose(in_file);
    }

    // Create the threads
    for(int i = 0; i < config.clients; i++) {
        int res = pthread_create(&threads[i], NULL, run_client, &client_data[i]);
        if(res != 0) {
            fprintf(stderr, "Can't create thread\n");
            exit(-1);
        }
    }

    // Wait for the threads to finish
    for(int i = 0; i < config.clients; i++) {
        res = pthread_join(threads[i], NULL);
        if(res != 0) {
            fprintf(stderr, "Can't join on the thread\n");
            exit(-1);
        }
    }

    // Disconnect everyone
    for(int i = 0; i < config.clients; i++) {
        delete client_data[i].proto;
    }

    // Dump key vectors if we have an out file
    if(config.out_file[0] != 0) {
        FILE *out_file = fopen(config.out_file, "aw");

        fwrite(&config.clients, sizeof(config.clients), 1, out_file);

        // Dump the keys
        for(int i = 0; i < config.clients; i++) {
            client_data_t *cd = &client_data[i];
            fwrite(&cd->id, sizeof(cd->id), 1, out_file);
            fwrite(&cd->min_seed, sizeof(cd->min_seed), 1, out_file);
            fwrite(&cd->max_seed, sizeof(cd->max_seed), 1, out_file);
        }

        fclose(out_file);
    }

    return 0;
}

<|endoftext|>


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

#ifndef _SC_XMLCHANGETRACKINGIMPORTHELPER_HXX
#define _SC_XMLCHANGETRACKINGIMPORTHELPER_HXX

#ifndef SC_CHGTRACK_HXX
#include "chgtrack.hxx"
#endif

#ifndef __SGI_STL_LIST
#include <list>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_
#include <com/sun/star/util/DateTime.hpp>
#endif

class ScBaseCell;
class ScDocument;
class DateTime;

struct ScMyActionInfo
{
    rtl::OUString sUser;
    rtl::OUString sComment;
    com::sun::star::util::DateTime aDateTime;
};

struct ScMyCellInfo
{
    ScBaseCell*     pCell;
    rtl::OUString   sFormulaAddress;
    rtl::OUString   sFormula;
    String          sResult;
    double          fValue;
    sal_Int32       nMatrixCols;
    sal_Int32       nMatrixRows;
    sal_uInt16      nType;
    sal_uInt8       nMatrixFlag;

    ScMyCellInfo();
    ScMyCellInfo(ScBaseCell* pCell, const rtl::OUString& sFormulaAddress, const rtl::OUString& sFormula,
                const double& fValue, const sal_uInt16 nType, const sal_uInt8 nMatrixFlag, const sal_Int32 nMatrixCols,
                const sal_Int32 nMatrixRows);
    ~ScMyCellInfo();

    ScBaseCell* CreateCell(ScDocument* pDoc);
};

struct ScMyDeleted
{
    sal_uInt32 nID;
    ScMyCellInfo* pCellInfo;

    ScMyDeleted();
    ~ScMyDeleted();
};

typedef std::list<ScMyDeleted*> ScMyDeletedList;

struct ScMyGenerated
{
    ScBigRange      aBigRange;
    sal_uInt32      nID;
    ScMyCellInfo*   pCellInfo;

    ScMyGenerated(ScMyCellInfo* pCellInfo, const ScBigRange& aBigRange);
    ~ScMyGenerated();
};

typedef std::list<ScMyGenerated*> ScMyGeneratedList;

struct ScMyInsertionCutOff
{
    sal_uInt32 nID;
    sal_Int32 nPosition;

    ScMyInsertionCutOff(const sal_uInt32 nTempID, const sal_Int32 nTempPosition) :
            nID(nTempID), nPosition(nTempPosition) {}
};

struct ScMyMoveCutOff
{
    sal_uInt32 nID;
    sal_Int32 nStartPosition;
    sal_Int32 nEndPosition;

    ScMyMoveCutOff(const sal_uInt32 nTempID, const sal_Int32 nStartPos, const sal_Int32 nEndPos) :
            nID(nTempID), nStartPosition(nStartPos), nEndPosition(nEndPos) {}
};

typedef std::list<ScMyMoveCutOff> ScMyMoveCutOffs;

struct ScMyMoveRanges
{
    ScBigRange aSourceRange;
    ScBigRange aTargetRange;

    ScMyMoveRanges(const ScBigRange& aSource, const ScBigRange aTarget) :
            aSourceRange(aSource), aTargetRange(aTarget) {}
};

typedef std::list<sal_uInt32> ScMyDependences;

struct ScMyBaseAction
{
    ScMyActionInfo aInfo;
    ScBigRange aBigRange;
    ScMyDependences aDependences;
    ScMyDeletedList aDeletedList;
    sal_uInt32 nActionNumber;
    sal_uInt32 nRejectingNumber;
    sal_uInt32 nPreviousAction;
    ScChangeActionType nActionType;
    ScChangeActionState nActionState;

    ScMyBaseAction(const ScChangeActionType nActionType);
    ~ScMyBaseAction();
};

struct ScMyInsAction : public ScMyBaseAction
{
    ScMyInsAction(const ScChangeActionType nActionType);
    ~ScMyInsAction();
};

struct ScMyDelAction : public ScMyBaseAction
{
    ScMyGeneratedList aGeneratedList;
    ScMyInsertionCutOff* pInsCutOff;
    ScMyMoveCutOffs aMoveCutOffs;
    sal_Int16 nD;

    ScMyDelAction(const ScChangeActionType nActionType);
    ~ScMyDelAction();
};

struct ScMyMoveAction : public ScMyBaseAction
{
    ScMyGeneratedList aGeneratedList;
    ScMyMoveRanges* pMoveRanges;

    ScMyMoveAction();
    ~ScMyMoveAction();
};

struct ScMyContentAction : public ScMyBaseAction
{
    ScMyCellInfo*   pCellInfo;

    ScMyContentAction();
    ~ScMyContentAction();
};

struct ScMyRejAction : public ScMyBaseAction
{
    ScMyRejAction();
    ~ScMyRejAction();
};

typedef std::list<ScMyBaseAction*> ScMyActions;

class ScChangeViewSettings;

class ScXMLChangeTrackingImportHelper
{
    StrCollection       aUsers;
    ScMyActions         aActions;
    com::sun::star::uno::Sequence<sal_Int8> aProtect;
    ScDocument*         pDoc;
    ScChangeTrack*      pTrack;
    ScMyBaseAction*     pCurrentAction;
    rtl::OUString       sIDPrefix;
    sal_uInt32          nPrefixLength;
    sal_Int16           nMultiSpanned;
    sal_Int16           nMultiSpannedSlaveCount;
    sal_Bool            bChangeTrack : 1;

private:
    void ConvertInfo(const ScMyActionInfo& aInfo, String& rUser, DateTime& aDateTime);
    ScChangeAction* CreateInsertAction(ScMyInsAction* pAction);
    ScChangeAction* CreateDeleteAction(ScMyDelAction* pAction);
    ScChangeAction* CreateMoveAction(ScMyMoveAction* pAction);
    ScChangeAction* CreateRejectionAction(ScMyRejAction* pAction);
    ScChangeAction* CreateContentAction(ScMyContentAction* pAction);

    void CreateGeneratedActions(ScMyGeneratedList& rList);

public:
    ScXMLChangeTrackingImportHelper();
    ~ScXMLChangeTrackingImportHelper();

    void SetChangeTrack(sal_Bool bValue) { bChangeTrack = bValue; }
    void SetProtection(const com::sun::star::uno::Sequence<sal_Int8>& rProtect) { aProtect = rProtect; }
    void StartChangeAction(const ScChangeActionType nActionType);

    sal_uInt32 GetIDFromString(const rtl::OUString& sID);

    void SetActionNumber(const sal_uInt32 nActionNumber) { pCurrentAction->nActionNumber = nActionNumber; }
    void SetActionState(const ScChangeActionState nActionState) { pCurrentAction->nActionState = nActionState; }
    void SetRejectingNumber(const sal_uInt32 nRejectingNumber) { pCurrentAction->nRejectingNumber = nRejectingNumber; }
    void SetActionInfo(const ScMyActionInfo& aInfo);
    void SetBigRange(const ScBigRange& aBigRange) { pCurrentAction->aBigRange = aBigRange; }
    void SetPreviousChange(const sal_uInt32 nPreviousAction, ScMyCellInfo* pCellInfo);
    void SetPosition(const sal_Int32 nPosition, const sal_Int32 nCount, const sal_Int32 nTable);
    void AddDependence(const sal_uInt32 nID) { pCurrentAction->aDependences.push_front(nID); }
    void AddDeleted(const sal_uInt32 nID);
    void AddDeleted(const sal_uInt32 nID, ScMyCellInfo* pCellInfo);
    void SetMultiSpanned(const sal_Int16 nMultiSpanned);
    void SetInsertionCutOff(const sal_uInt32 nID, const sal_Int32 nPosition);
    void AddMoveCutOff(const sal_uInt32 nID, const sal_Int32 nStartPosition, const sal_Int32 nEndPosition);
    void SetMoveRanges(const ScBigRange& aSourceRange, const ScBigRange& aTargetRange);
    void GetMultiSpannedRange();
    void AddGenerated(ScMyCellInfo* pCellInfo, const ScBigRange& aBigRange);

    void EndChangeAction();

    void SetDeletionDependences(ScMyDelAction* pAction, ScChangeActionDel* pDelAct);
    void SetMovementDependences(ScMyMoveAction* pAction, ScChangeActionMove* pMoveAct);
    void SetContentDependences(ScMyContentAction* pAction, ScChangeActionContent* pActContent);
    void SetDependences(ScMyBaseAction* pAction);

    void SetNewCell(ScMyContentAction* pAction);

    void CreateChangeTrack(ScDocument* pDoc);
};

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

#ifndef _SC_XMLCHANGETRACKINGIMPORTHELPER_HXX
#define _SC_XMLCHANGETRACKINGIMPORTHELPER_HXX

#ifndef SC_CHGTRACK_HXX
#include "chgtrack.hxx"
#endif

#ifndef __SGI_STL_LIST
#include <list>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_
#include <com/sun/star/util/DateTime.hpp>
#endif

class ScBaseCell;
class ScDocument;
class DateTime;

struct ScMyActionInfo
{
    rtl::OUString sUser;
    rtl::OUString sComment;
    com::sun::star::util::DateTime aDateTime;
};

struct ScMyCellInfo
{
    ScBaseCell*     pCell;
    rtl::OUString   sFormulaAddress;
    rtl::OUString   sFormula;
    String          sInputString;
    double          fValue;
    sal_Int32       nMatrixCols;
    sal_Int32       nMatrixRows;
    sal_uInt16      nType;
    sal_uInt8       nMatrixFlag;

    ScMyCellInfo();
    ScMyCellInfo(ScBaseCell* pCell, const rtl::OUString& sFormulaAddress, const rtl::OUString& sFormula, const rtl::OUString& sInputString,
                const double& fValue, const sal_uInt16 nType, const sal_uInt8 nMatrixFlag, const sal_Int32 nMatrixCols,
                const sal_Int32 nMatrixRows);
    ~ScMyCellInfo();

    ScBaseCell* CreateCell(ScDocument* pDoc);
};

struct ScMyDeleted
{
    sal_uInt32 nID;
    ScMyCellInfo* pCellInfo;

    ScMyDeleted();
    ~ScMyDeleted();
};

typedef std::list<ScMyDeleted*> ScMyDeletedList;

struct ScMyGenerated
{
    ScBigRange      aBigRange;
    sal_uInt32      nID;
    ScMyCellInfo*   pCellInfo;

    ScMyGenerated(ScMyCellInfo* pCellInfo, const ScBigRange& aBigRange);
    ~ScMyGenerated();
};

typedef std::list<ScMyGenerated*> ScMyGeneratedList;

struct ScMyInsertionCutOff
{
    sal_uInt32 nID;
    sal_Int32 nPosition;

    ScMyInsertionCutOff(const sal_uInt32 nTempID, const sal_Int32 nTempPosition) :
            nID(nTempID), nPosition(nTempPosition) {}
};

struct ScMyMoveCutOff
{
    sal_uInt32 nID;
    sal_Int32 nStartPosition;
    sal_Int32 nEndPosition;

    ScMyMoveCutOff(const sal_uInt32 nTempID, const sal_Int32 nStartPos, const sal_Int32 nEndPos) :
            nID(nTempID), nStartPosition(nStartPos), nEndPosition(nEndPos) {}
};

typedef std::list<ScMyMoveCutOff> ScMyMoveCutOffs;

struct ScMyMoveRanges
{
    ScBigRange aSourceRange;
    ScBigRange aTargetRange;

    ScMyMoveRanges(const ScBigRange& aSource, const ScBigRange aTarget) :
            aSourceRange(aSource), aTargetRange(aTarget) {}
};

typedef std::list<sal_uInt32> ScMyDependences;

struct ScMyBaseAction
{
    ScMyActionInfo aInfo;
    ScBigRange aBigRange;
    ScMyDependences aDependences;
    ScMyDeletedList aDeletedList;
    sal_uInt32 nActionNumber;
    sal_uInt32 nRejectingNumber;
    sal_uInt32 nPreviousAction;
    ScChangeActionType nActionType;
    ScChangeActionState nActionState;

    ScMyBaseAction(const ScChangeActionType nActionType);
    ~ScMyBaseAction();
};

struct ScMyInsAction : public ScMyBaseAction
{
    ScMyInsAction(const ScChangeActionType nActionType);
    ~ScMyInsAction();
};

struct ScMyDelAction : public ScMyBaseAction
{
    ScMyGeneratedList aGeneratedList;
    ScMyInsertionCutOff* pInsCutOff;
    ScMyMoveCutOffs aMoveCutOffs;
    sal_Int16 nD;

    ScMyDelAction(const ScChangeActionType nActionType);
    ~ScMyDelAction();
};

struct ScMyMoveAction : public ScMyBaseAction
{
    ScMyGeneratedList aGeneratedList;
    ScMyMoveRanges* pMoveRanges;

    ScMyMoveAction();
    ~ScMyMoveAction();
};

struct ScMyContentAction : public ScMyBaseAction
{
    ScMyCellInfo*   pCellInfo;

    ScMyContentAction();
    ~ScMyContentAction();
};

struct ScMyRejAction : public ScMyBaseAction
{
    ScMyRejAction();
    ~ScMyRejAction();
};

typedef std::list<ScMyBaseAction*> ScMyActions;

class ScChangeViewSettings;

class ScXMLChangeTrackingImportHelper
{
    StrCollection       aUsers;
    ScMyActions         aActions;
    com::sun::star::uno::Sequence<sal_Int8> aProtect;
    ScDocument*         pDoc;
    ScChangeTrack*      pTrack;
    ScMyBaseAction*     pCurrentAction;
    rtl::OUString       sIDPrefix;
    sal_uInt32          nPrefixLength;
    sal_Int16           nMultiSpanned;
    sal_Int16           nMultiSpannedSlaveCount;
    sal_Bool            bChangeTrack : 1;

private:
    void ConvertInfo(const ScMyActionInfo& aInfo, String& rUser, DateTime& aDateTime);
    ScChangeAction* CreateInsertAction(ScMyInsAction* pAction);
    ScChangeAction* CreateDeleteAction(ScMyDelAction* pAction);
    ScChangeAction* CreateMoveAction(ScMyMoveAction* pAction);
    ScChangeAction* CreateRejectionAction(ScMyRejAction* pAction);
    ScChangeAction* CreateContentAction(ScMyContentAction* pAction);

    void CreateGeneratedActions(ScMyGeneratedList& rList);

public:
    ScXMLChangeTrackingImportHelper();
    ~ScXMLChangeTrackingImportHelper();

    void SetChangeTrack(sal_Bool bValue) { bChangeTrack = bValue; }
    void SetProtection(const com::sun::star::uno::Sequence<sal_Int8>& rProtect) { aProtect = rProtect; }
    void StartChangeAction(const ScChangeActionType nActionType);

    sal_uInt32 GetIDFromString(const rtl::OUString& sID);

    void SetActionNumber(const sal_uInt32 nActionNumber) { pCurrentAction->nActionNumber = nActionNumber; }
    void SetActionState(const ScChangeActionState nActionState) { pCurrentAction->nActionState = nActionState; }
    void SetRejectingNumber(const sal_uInt32 nRejectingNumber) { pCurrentAction->nRejectingNumber = nRejectingNumber; }
    void SetActionInfo(const ScMyActionInfo& aInfo);
    void SetBigRange(const ScBigRange& aBigRange) { pCurrentAction->aBigRange = aBigRange; }
    void SetPreviousChange(const sal_uInt32 nPreviousAction, ScMyCellInfo* pCellInfo);
    void SetPosition(const sal_Int32 nPosition, const sal_Int32 nCount, const sal_Int32 nTable);
    void AddDependence(const sal_uInt32 nID) { pCurrentAction->aDependences.push_front(nID); }
    void AddDeleted(const sal_uInt32 nID);
    void AddDeleted(const sal_uInt32 nID, ScMyCellInfo* pCellInfo);
    void SetMultiSpanned(const sal_Int16 nMultiSpanned);
    void SetInsertionCutOff(const sal_uInt32 nID, const sal_Int32 nPosition);
    void AddMoveCutOff(const sal_uInt32 nID, const sal_Int32 nStartPosition, const sal_Int32 nEndPosition);
    void SetMoveRanges(const ScBigRange& aSourceRange, const ScBigRange& aTargetRange);
    void GetMultiSpannedRange();
    void AddGenerated(ScMyCellInfo* pCellInfo, const ScBigRange& aBigRange);

    void EndChangeAction();

    void SetDeletionDependences(ScMyDelAction* pAction, ScChangeActionDel* pDelAct);
    void SetMovementDependences(ScMyMoveAction* pAction, ScChangeActionMove* pMoveAct);
    void SetContentDependences(ScMyContentAction* pAction, ScChangeActionContent* pActContent);
    void SetDependences(ScMyBaseAction* pAction);

    void SetNewCell(ScMyContentAction* pAction);

    void CreateChangeTrack(ScDocument* pDoc);
};

#endif
<|endoftext|>


<commit_before>#include "VideoWriter.hpp"
extern "C" {
#include "libavutil/avstring.h"
}

std::unique_ptr<vio::VideoWriter> vio::VideoWriter::Open(const std::string& fileName,
                                                         int width, int height,
                                                         AVPixelFormat pixelFormat)
{
    // ReĩtH[}bgAVI
    AVOutputFormat* format = av_guess_format("avi", fileName.c_str(), nullptr);
    if (!format)
        return nullptr;

    std::shared_ptr<AVFormatContext> formatContext(avformat_alloc_context(),
                                                   avformat_free_context);
    if (!formatContext)
        return nullptr;
    formatContext->oformat = format;
    av_strlcpy(formatContext->filename, fileName.c_str(), sizeof(formatContext->filename));

    AVStream* stream = av_new_stream(formatContext.get(), 0);
    if (!stream)
        return nullptr;

    CodecID codecId = AV_CODEC_ID_RAWVIDEO;         // R[fbNrawvideo (k)
    AVCodec* codec = avcodec_find_encoder(codecId);
    if (!codec)
        return nullptr;

    std::shared_ptr<AVCodecContext> codecContext(stream->codec, avcodec_close);
    codecContext->codec_id = codec->id;
    codecContext->codec_type = AVMEDIA_TYPE_VIDEO;
    codecContext->width = width;
    codecContext->height = height;
    codecContext->time_base.num = 1;
    codecContext->time_base.den = 30;

    codecContext->pix_fmt = pixelFormat;
    if (codec && codec->pix_fmts) {
        const PixelFormat* p = codec->pix_fmts;
        for (; *p != -1; ++p) {
            if (*p == codecContext->pix_fmt)
                break;
        }
        if (*p == -1)   // R[fbNw肵sNZtH[}bgT|[gĂȂ
            return nullptr;
    }
    if (format->flags & AVFMT_GLOBALHEADER)
        codecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;

    if (avcodec_open(codecContext.get(), codec) != 0)
        return nullptr;

    if (!(format->flags & AVFMT_NOFILE)) {
        if (avio_open(&formatContext->pb, formatContext->filename, AVIO_FLAG_WRITE) < 0)
            return nullptr;
    }

    if (avformat_write_header(formatContext.get(), nullptr) < 0)
        return nullptr;

    int size = codecContext->width * codecContext->height * 4 + 1024;
    std::shared_ptr<uint8_t> buffer(static_cast<uint8_t*>(av_malloc(size)), av_free);

    std::unique_ptr<VideoWriter> writer(new VideoWriter());
    writer->mFormat = format;
    writer->mStream = stream;
    writer->mFormatContext = formatContext;
    writer->mCodecContext = codecContext;
    writer->mBuffer = buffer;
    writer->mBufferSize = size;
    return writer;
}

void vio::VideoWriter::Close()
{
    if (mClosed)
        return;

    av_write_trailer(mFormatContext.get());
    if (!(mFormat->flags & AVFMT_NOFILE)) {
        avio_close(mFormatContext->pb);
    }
    mClosed = true;
}

vio::VideoWriter::~VideoWriter()
{
    if (!mClosed)
        Close();
}

bool vio::VideoWriter::WriteFrame(const AVFrame* frame)
{
    if (mClosed)
        return false;

    AVPacket packet;
    av_init_packet(&packet);

    int outSize = avcodec_encode_video(mCodecContext.get(), mBuffer.get(),
                                       mBufferSize, frame);
    if (outSize == 0)
        return true;
    if (outSize < 0)
        return false;

    packet.stream_index = mStream->index;
    packet.data = mBuffer.get();
    packet.size = outSize;

    int64_t pts = mCodecContext->coded_frame->pts;
    packet.pts = av_rescale_q(pts != AV_NOPTS_VALUE ? pts : mFrameCount + 1,
                              mCodecContext->time_base,
                              mStream->time_base);
    if (mCodecContext->coded_frame->key_frame)
        packet.flags |= AV_PKT_FLAG_KEY;

    if (av_interleaved_write_frame(mFormatContext.get(), &packet) != 0)
        return false;

    mFrameCount += 1;
    return true;
}
<commit_msg>Free packet after av_interleaved_write_frame.<commit_after>#include "VideoWriter.hpp"
extern "C" {
#include "libavutil/avstring.h"
}

std::unique_ptr<vio::VideoWriter> vio::VideoWriter::Open(const std::string& fileName,
                                                         int width, int height,
                                                         AVPixelFormat pixelFormat)
{
    // ReĩtH[}bgAVI
    AVOutputFormat* format = av_guess_format("avi", fileName.c_str(), nullptr);
    if (!format)
        return nullptr;

    std::shared_ptr<AVFormatContext> formatContext(avformat_alloc_context(),
                                                   avformat_free_context);
    if (!formatContext)
        return nullptr;
    formatContext->oformat = format;
    av_strlcpy(formatContext->filename, fileName.c_str(), sizeof(formatContext->filename));

    AVStream* stream = av_new_stream(formatContext.get(), 0);
    if (!stream)
        return nullptr;

    CodecID codecId = AV_CODEC_ID_RAWVIDEO;         // R[fbNrawvideo (k)
    AVCodec* codec = avcodec_find_encoder(codecId);
    if (!codec)
        return nullptr;

    std::shared_ptr<AVCodecContext> codecContext(stream->codec, avcodec_close);
    codecContext->codec_id = codec->id;
    codecContext->codec_type = AVMEDIA_TYPE_VIDEO;
    codecContext->width = width;
    codecContext->height = height;
    codecContext->time_base.num = 1;
    codecContext->time_base.den = 30;

    codecContext->pix_fmt = pixelFormat;
    if (codec && codec->pix_fmts) {
        const PixelFormat* p = codec->pix_fmts;
        for (; *p != -1; ++p) {
            if (*p == codecContext->pix_fmt)
                break;
        }
        if (*p == -1)   // R[fbNw肵sNZtH[}bgT|[gĂȂ
            return nullptr;
    }
    if (format->flags & AVFMT_GLOBALHEADER)
        codecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;

    if (avcodec_open(codecContext.get(), codec) != 0)
        return nullptr;

    if (!(format->flags & AVFMT_NOFILE)) {
        if (avio_open(&formatContext->pb, formatContext->filename, AVIO_FLAG_WRITE) < 0)
            return nullptr;
    }

    if (avformat_write_header(formatContext.get(), nullptr) < 0)
        return nullptr;

    int size = codecContext->width * codecContext->height * 4 + 1024;
    std::shared_ptr<uint8_t> buffer(static_cast<uint8_t*>(av_malloc(size)), av_free);

    std::unique_ptr<VideoWriter> writer(new VideoWriter());
    writer->mFormat = format;
    writer->mStream = stream;
    writer->mFormatContext = formatContext;
    writer->mCodecContext = codecContext;
    writer->mBuffer = buffer;
    writer->mBufferSize = size;
    return writer;
}

void vio::VideoWriter::Close()
{
    if (mClosed)
        return;

    av_write_trailer(mFormatContext.get());
    if (!(mFormat->flags & AVFMT_NOFILE)) {
        avio_close(mFormatContext->pb);
    }
    mClosed = true;
}

vio::VideoWriter::~VideoWriter()
{
    if (!mClosed)
        Close();
}

bool vio::VideoWriter::WriteFrame(const AVFrame* frame)
{
    if (mClosed)
        return false;

    AVPacket packet;
    av_init_packet(&packet);

    int outSize = avcodec_encode_video(mCodecContext.get(), mBuffer.get(),
                                       mBufferSize, frame);
    if (outSize == 0)
        return true;
    if (outSize < 0)
        return false;

    packet.stream_index = mStream->index;
    packet.data = mBuffer.get();
    packet.size = outSize;

    int64_t pts = mCodecContext->coded_frame->pts;
    packet.pts = av_rescale_q(pts != AV_NOPTS_VALUE ? pts : mFrameCount + 1,
                              mCodecContext->time_base,
                              mStream->time_base);
    if (mCodecContext->coded_frame->key_frame)
        packet.flags |= AV_PKT_FLAG_KEY;

    int ret = av_interleaved_write_frame(mFormatContext.get(), &packet);
    av_free_packet(&packet);

    if (ret == 0) {
        mFrameCount += 1;
        return true;
    } else {
        return false;
    }
}
<|endoftext|>


<commit_before>/* This file is part of python_mapnik (c++/python mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko
 *
 * Mapnik is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id: mapnik_parameters.cc 17 2005-03-08 23:58:43Z pavlenko $

#include <mapnik.hpp>
#include <boost/python.hpp>
#include <boost/python/detail/api_placeholder.hpp>

using mapnik::Parameter;
using mapnik::Parameters;

void (Parameters::*add1)(const Parameter& param)=&Parameters::add;
void (Parameters::*add2)(const std::string&,const std::string&)=&Parameters::add;

struct parameter_pickle_suite : boost::python::pickle_suite
{
    static boost::python::tuple
    getinitargs(const Parameter& p)
    {
        using namespace boost::python;
        return boost::python::make_tuple(p.first,p.second);
    }
};

struct parameters_pickle_suite : boost::python::pickle_suite
{
    static boost::python::tuple
    getstate(const Parameters& p)
    {
        using namespace boost::python;
        dict d;
        Parameters::const_iterator pos=p.begin();
        while(pos!=p.end())
        {
            d[pos->first]=pos->second;
            ++pos;
        }
        return boost::python::make_tuple(d);
    }

    static void setstate(Parameters& p, boost::python::tuple state)
    {
        using namespace boost::python;
        if (len(state) != 1)
        {
            PyErr_SetObject(PyExc_ValueError,
			    ("expected 1-item tuple in call to __setstate__; got %s"
			     % state).ptr()
			    );
            throw_error_already_set();
        }
        dict d = extract<dict>(state[0]);
        list keys=d.keys();
        for (int i=0;i<len(keys);++i)
        {
            std::string key=extract<std::string>(keys[i]);
            std::string value=extract<std::string>(d[key]);
            p.add(key,value);
        }
    }
};

void export_parameters()
{
    using namespace boost::python;
    class_<Parameter>("parameter",init<std::string,std::string>())
        .def_pickle(parameter_pickle_suite())
        ;

    class_<Parameters>("parameters",init<>())
        .def("add",add1)
        .def("add",add2)
        .def("get",&Parameters::get)
        .def_pickle(parameters_pickle_suite())
        ;
}
<commit_msg>small clean-up<commit_after>/* This file is part of python_mapnik (c++/python mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko
 *
 * Mapnik is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id: mapnik_parameters.cc 17 2005-03-08 23:58:43Z pavlenko $

#include <mapnik.hpp>
#include <boost/python.hpp>
#include <boost/python/detail/api_placeholder.hpp>

using mapnik::Parameter;
using mapnik::Parameters;

void (Parameters::*add1)(const Parameter&)=&Parameters::add;
void (Parameters::*add2)(const std::string&,const std::string&)=&Parameters::add;

struct parameter_pickle_suite : boost::python::pickle_suite
{
    static boost::python::tuple
    getinitargs(const Parameter& p)
    {
        using namespace boost::python;
        return boost::python::make_tuple(p.first,p.second);
    }
};

struct parameters_pickle_suite : boost::python::pickle_suite
{
    static boost::python::tuple
    getstate(const Parameters& p)
    {
        using namespace boost::python;
        dict d;
        Parameters::const_iterator pos=p.begin();
        while(pos!=p.end())
        {
            d[pos->first]=pos->second;
            ++pos;
        }
        return boost::python::make_tuple(d);
    }

    static void setstate(Parameters& p, boost::python::tuple state)
    {
        using namespace boost::python;
        if (len(state) != 1)
        {
            PyErr_SetObject(PyExc_ValueError,
			    ("expected 1-item tuple in call to __setstate__; got %s"
			     % state).ptr()
			    );
            throw_error_already_set();
        }
        dict d = extract<dict>(state[0]);
        list keys=d.keys();
        for (int i=0;i<len(keys);++i)
        {
            std::string key=extract<std::string>(keys[i]);
            std::string value=extract<std::string>(d[key]);
            p.add(key,value);
        }
    }
};

void export_parameters()
{
    using namespace boost::python;
    class_<Parameter>("parameter",init<std::string,std::string>())
        .def_pickle(parameter_pickle_suite())
        ;

    class_<Parameters>("parameters",init<>())
        .def("add",add1)
        .def("add",add2)
        .def("get",&Parameters::get)
        .def_pickle(parameters_pickle_suite())
        ;
}
<|endoftext|>