<commit_before>/* Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 *
 * Copyright 2018 INRIA.
 *
 * 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.
*/

/*! \file RigidBodyDS.hpp
  \brief Definition of an abstract 3D rigid body above NewtonEulerDS
*/

#ifndef RigidBodyDS_h
#define RigidBodyDS_h

#include <MechanicsFwd.hpp>
#include <NewtonEulerDS.hpp>
#include <SiconosVisitor.hpp>
#include <SiconosContactor.hpp>

class RigidBodyDS : public NewtonEulerDS,
               public std::enable_shared_from_this<RigidBodyDS>
{
protected:
  /** serialization hooks
  */
  ACCEPT_SERIALIZATION(RigidBodyDS);

  RigidBodyDS() : NewtonEulerDS() {};

  SP::SiconosContactorSet _contactors;
  bool _useContactorInertia;

  /** If false, bodies connected to this body by a joint will not
   * collide. See also NewtonEulerJointR::_allowSelfCollide */
  bool _allowSelfCollide true;

public:

  RigidBodyDS(SP::SiconosVector position,
         SP::SiconosVector velocity,
         double mass,
         SP::SimpleMatrix inertia = SP::SimpleMatrix());

  virtual ~RigidBodyDS();

  void setUseContactorInertia(bool use) { _useContactorInertia = use; }

  bool useContactorInertia() { return _useContactorInertia; }

  /** Return the value of the _allowSelfCollide flag. */
  bool allowSelfCollide() { return _allowSelfCollide; }

  /** Set the value of the _allowSelfCollide flag. */
  void setAllowSelfCollide(bool x) { _allowSelfCollide = x; }

  /** Access the contactor set associated with this body.
   * \return A SP::SiconosContactorSet */
  SP::SiconosContactorSet contactors() const { return _contactors; }

  /** Provide a set of contactors to the body.
   * \param c A SP::SiconosContactorSet */
  void setContactors(SP::SiconosContactorSet c) { _contactors = c; }

  /** Make the base position of the contactors equal to the DS q vector.
   * \return a SP::SiconosVector */
  virtual SP::SiconosVector base_position() { return q(); }

  /** visitors hook
   */
  ACCEPT_BASE_VISITORS(NewtonEulerDS);
};

#endif /* RigidBodyDS_h */
<commit_msg>[kernel,mechanics] initialize attributes<commit_after>/* Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 *
 * Copyright 2018 INRIA.
 *
 * 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.
*/

/*! \file RigidBodyDS.hpp
  \brief Definition of an abstract 3D rigid body above NewtonEulerDS
*/

#ifndef RigidBodyDS_h
#define RigidBodyDS_h

#include <MechanicsFwd.hpp>
#include <NewtonEulerDS.hpp>
#include <SiconosVisitor.hpp>
#include <SiconosContactor.hpp>

class RigidBodyDS : public NewtonEulerDS,
               public std::enable_shared_from_this<RigidBodyDS>
{
protected:
  /** serialization hooks
  */
  ACCEPT_SERIALIZATION(RigidBodyDS);

  RigidBodyDS() : NewtonEulerDS() {};

  SP::SiconosContactorSet _contactors;
  bool _useContactorInertia;

  /** If false, bodies connected to this body by a joint will not
   * collide. See also NewtonEulerJointR::_allowSelfCollide */
  bool _allowSelfCollide = true;

public:

  RigidBodyDS(SP::SiconosVector position,
         SP::SiconosVector velocity,
         double mass,
         SP::SimpleMatrix inertia = SP::SimpleMatrix());

  virtual ~RigidBodyDS();

  void setUseContactorInertia(bool use) { _useContactorInertia = use; }

  bool useContactorInertia() { return _useContactorInertia; }

  /** Return the value of the _allowSelfCollide flag. */
  bool allowSelfCollide() { return _allowSelfCollide; }

  /** Set the value of the _allowSelfCollide flag. */
  void setAllowSelfCollide(bool x) { _allowSelfCollide = x; }

  /** Access the contactor set associated with this body.
   * \return A SP::SiconosContactorSet */
  SP::SiconosContactorSet contactors() const { return _contactors; }

  /** Provide a set of contactors to the body.
   * \param c A SP::SiconosContactorSet */
  void setContactors(SP::SiconosContactorSet c) { _contactors = c; }

  /** Make the base position of the contactors equal to the DS q vector.
   * \return a SP::SiconosVector */
  virtual SP::SiconosVector base_position() { return q(); }

  /** visitors hook
   */
  ACCEPT_BASE_VISITORS(NewtonEulerDS);
};

#endif /* RigidBodyDS_h */
<|endoftext|>


<commit_before>// Copyright (c) 2009 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 "base/string_util.h"
#include "media/base/buffers.h"
#include "media/base/mock_filters.h"
#include "media/base/video_frame_impl.h"
#include "media/base/yuv_convert.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace media {

// Helper function that initializes a YV12 frame with white and black scan
// lines based on the |white_to_black| parameter.  If 0, then the entire
// frame will be black, if 1 then the entire frame will be white.
void InitializeYV12Frame(VideoFrame* frame, double white_to_black) {
  VideoSurface surface;
  if (!frame->Lock(&surface)) {
    ADD_FAILURE();
    return;
  }
  EXPECT_EQ(VideoSurface::YV12, surface.format);
  size_t first_black_row = static_cast<size_t>(surface.height * white_to_black);
  uint8* y_plane = surface.data[VideoSurface::kYPlane];
  for (size_t row = 0; row < surface.height; ++row) {
    int color = (row < first_black_row) ? 0xFF : 0x00;
    memset(y_plane, color, surface.width);
    y_plane += surface.strides[VideoSurface::kYPlane];
  }
  uint8* u_plane = surface.data[VideoSurface::kUPlane];
  uint8* v_plane = surface.data[VideoSurface::kVPlane];
  for (size_t row = 0; row < surface.height; row += 2) {
    memset(u_plane, 0x80, surface.width / 2);
    memset(v_plane, 0x80, surface.width / 2);
    u_plane += surface.strides[VideoSurface::kUPlane];
    v_plane += surface.strides[VideoSurface::kVPlane];
  }
  frame->Unlock();
}

// Given a |yv12_frame| this method converts the YV12 frame to RGBA and
// makes sure that all the pixels of the RBG frame equal |expect_rgb_color|.
void ExpectFrameColor(media::VideoFrame* yv12_frame, uint32 expect_rgb_color) {
  // On linux and mac builds if you directly compare using EXPECT_EQ and use
  // the VideoSurface::kNumxxxPlanes constants, it generates an error when
  // linking.  These are declared so that we can compare against locals.
  const size_t expect_yuv_planes = VideoSurface::kNumYUVPlanes;
  const size_t expect_rgb_planes = VideoSurface::kNumRGBPlanes;

  VideoSurface yuv_surface;
  ASSERT_TRUE(yv12_frame->Lock(&yuv_surface));
  ASSERT_EQ(VideoSurface::YV12, yuv_surface.format);
  ASSERT_EQ(expect_yuv_planes, yuv_surface.planes);
  ASSERT_EQ(yuv_surface.strides[VideoSurface::kUPlane],
            yuv_surface.strides[VideoSurface::kVPlane]);

  scoped_refptr<media::VideoFrame> rgb_frame;
  media::VideoFrameImpl::CreateFrame(VideoSurface::RGBA,
                                     yuv_surface.width,
                                     yuv_surface.height,
                                     yv12_frame->GetTimestamp(),
                                     yv12_frame->GetDuration(),
                                     &rgb_frame);
  media::VideoSurface rgb_surface;
  ASSERT_TRUE(rgb_frame->Lock(&rgb_surface));
  ASSERT_EQ(yuv_surface.width, rgb_surface.width);
  ASSERT_EQ(yuv_surface.height, rgb_surface.height);
  ASSERT_EQ(expect_rgb_planes, rgb_surface.planes);

  media::ConvertYUVToRGB32(yuv_surface.data[VideoSurface::kYPlane],
                           yuv_surface.data[VideoSurface::kUPlane],
                           yuv_surface.data[VideoSurface::kVPlane],
                           rgb_surface.data[VideoSurface::kRGBPlane],
                           rgb_surface.width,
                           rgb_surface.height,
                           yuv_surface.strides[VideoSurface::kYPlane],
                           yuv_surface.strides[VideoSurface::kUPlane],
                           rgb_surface.strides[VideoSurface::kRGBPlane],
                           media::YV12);

  for (size_t row = 0; row < rgb_surface.height; ++row) {
    uint32* rgb_row_data = reinterpret_cast<uint32*>(
        rgb_surface.data[VideoSurface::kRGBPlane] +
        (rgb_surface.strides[VideoSurface::kRGBPlane] * row));
    for (size_t col = 0; col < rgb_surface.width; ++col) {
      SCOPED_TRACE(StringPrintf("Checking (%zd, %u)", row, col));
      EXPECT_EQ(expect_rgb_color, rgb_row_data[col]);
    }
  }
  rgb_frame->Unlock();
  yv12_frame->Unlock();
}

TEST(VideoFrameImpl, CreateFrame) {
  const size_t kWidth = 64;
  const size_t kHeight = 48;
  const base::TimeDelta kTimestampA = base::TimeDelta::FromMicroseconds(1337);
  const base::TimeDelta kDurationA = base::TimeDelta::FromMicroseconds(1667);
  const base::TimeDelta kTimestampB = base::TimeDelta::FromMicroseconds(1234);
  const base::TimeDelta kDurationB = base::TimeDelta::FromMicroseconds(5678);

  // Create a YV12 Video Frame.
  scoped_refptr<media::VideoFrame> frame;
  VideoFrameImpl::CreateFrame(media::VideoSurface::YV12, kWidth, kHeight,
                              kTimestampA, kDurationA, &frame);
  ASSERT_TRUE(frame);

  // Test StreamSample implementation.
  EXPECT_EQ(kTimestampA.InMicroseconds(),
            frame->GetTimestamp().InMicroseconds());
  EXPECT_EQ(kDurationA.InMicroseconds(), frame->GetDuration().InMicroseconds());
  EXPECT_FALSE(frame->IsEndOfStream());
  EXPECT_FALSE(frame->IsDiscontinuous());
  frame->SetTimestamp(kTimestampB);
  frame->SetDuration(kDurationB);
  EXPECT_EQ(kTimestampB.InMicroseconds(),
            frame->GetTimestamp().InMicroseconds());
  EXPECT_EQ(kDurationB.InMicroseconds(), frame->GetDuration().InMicroseconds());
  EXPECT_FALSE(frame->IsEndOfStream());
  frame->SetDiscontinuous(true);
  EXPECT_TRUE(frame->IsDiscontinuous());
  frame->SetDiscontinuous(false);
  EXPECT_FALSE(frame->IsDiscontinuous());

  // Test VideoFrame implementation.
  {
    SCOPED_TRACE("");
    InitializeYV12Frame(frame, 0.0f);
    ExpectFrameColor(frame, 0xFF000000);
  }
  {
    SCOPED_TRACE("");
    InitializeYV12Frame(frame, 1.0f);
    ExpectFrameColor(frame, 0xFFFFFFFF);
  }

  // Test an empty frame.
  VideoFrameImpl::CreateEmptyFrame(&frame);
  EXPECT_TRUE(frame->IsEndOfStream());
}

TEST(VideoFrameImpl, CreateBlackFrame) {
  const size_t kWidth = 2;
  const size_t kHeight = 2;
  const uint8 kExpectedYRow[] = { 0, 0 };
  const uint8 kExpectedUVRow[] = { 128 };

  scoped_refptr<media::VideoFrame> frame;
  VideoFrameImpl::CreateBlackFrame(kWidth, kHeight, &frame);
  ASSERT_TRUE(frame);

  // Test basic properties.
  EXPECT_EQ(0, frame->GetTimestamp().InMicroseconds());
  EXPECT_EQ(0, frame->GetDuration().InMicroseconds());
  EXPECT_FALSE(frame->IsEndOfStream());

  // Test surface properties.
  VideoSurface surface;
  EXPECT_TRUE(frame->Lock(&surface));
  EXPECT_EQ(VideoSurface::YV12, surface.format);
  EXPECT_EQ(kWidth, surface.width);
  EXPECT_EQ(kHeight, surface.height);
  EXPECT_EQ(3u, surface.planes);

  // Test surfaces themselves.
  for (size_t y = 0; y < surface.height; ++y) {
    EXPECT_EQ(0, memcmp(kExpectedYRow, surface.data[VideoSurface::kYPlane],
                        arraysize(kExpectedYRow)));
    surface.data[VideoSurface::kYPlane] +=
        surface.strides[VideoSurface::kYPlane];
  }
  for (size_t y = 0; y < surface.height / 2; ++y) {
    EXPECT_EQ(0, memcmp(kExpectedUVRow, surface.data[VideoSurface::kUPlane],
                        arraysize(kExpectedUVRow)));
    EXPECT_EQ(0, memcmp(kExpectedUVRow, surface.data[VideoSurface::kVPlane],
                        arraysize(kExpectedUVRow)));
    surface.data[VideoSurface::kUPlane] +=
        surface.strides[VideoSurface::kUPlane];
    surface.data[VideoSurface::kVPlane] +=
        surface.strides[VideoSurface::kVPlane];
  }
}

}  // namespace media
<commit_msg>Fixing build bustage caused by r26759<commit_after>// Copyright (c) 2009 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 "base/string_util.h"
#include "media/base/buffers.h"
#include "media/base/mock_filters.h"
#include "media/base/video_frame_impl.h"
#include "media/base/yuv_convert.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace media {

// Helper function that initializes a YV12 frame with white and black scan
// lines based on the |white_to_black| parameter.  If 0, then the entire
// frame will be black, if 1 then the entire frame will be white.
void InitializeYV12Frame(VideoFrame* frame, double white_to_black) {
  VideoSurface surface;
  if (!frame->Lock(&surface)) {
    ADD_FAILURE();
    return;
  }
  EXPECT_EQ(VideoSurface::YV12, surface.format);
  size_t first_black_row = static_cast<size_t>(surface.height * white_to_black);
  uint8* y_plane = surface.data[VideoSurface::kYPlane];
  for (size_t row = 0; row < surface.height; ++row) {
    int color = (row < first_black_row) ? 0xFF : 0x00;
    memset(y_plane, color, surface.width);
    y_plane += surface.strides[VideoSurface::kYPlane];
  }
  uint8* u_plane = surface.data[VideoSurface::kUPlane];
  uint8* v_plane = surface.data[VideoSurface::kVPlane];
  for (size_t row = 0; row < surface.height; row += 2) {
    memset(u_plane, 0x80, surface.width / 2);
    memset(v_plane, 0x80, surface.width / 2);
    u_plane += surface.strides[VideoSurface::kUPlane];
    v_plane += surface.strides[VideoSurface::kVPlane];
  }
  frame->Unlock();
}

// Given a |yv12_frame| this method converts the YV12 frame to RGBA and
// makes sure that all the pixels of the RBG frame equal |expect_rgb_color|.
void ExpectFrameColor(media::VideoFrame* yv12_frame, uint32 expect_rgb_color) {
  // On linux and mac builds if you directly compare using EXPECT_EQ and use
  // the VideoSurface::kNumxxxPlanes constants, it generates an error when
  // linking.  These are declared so that we can compare against locals.
  const size_t expect_yuv_planes = VideoSurface::kNumYUVPlanes;
  const size_t expect_rgb_planes = VideoSurface::kNumRGBPlanes;

  VideoSurface yuv_surface;
  ASSERT_TRUE(yv12_frame->Lock(&yuv_surface));
  ASSERT_EQ(VideoSurface::YV12, yuv_surface.format);
  ASSERT_EQ(expect_yuv_planes, yuv_surface.planes);
  ASSERT_EQ(yuv_surface.strides[VideoSurface::kUPlane],
            yuv_surface.strides[VideoSurface::kVPlane]);

  scoped_refptr<media::VideoFrame> rgb_frame;
  media::VideoFrameImpl::CreateFrame(VideoSurface::RGBA,
                                     yuv_surface.width,
                                     yuv_surface.height,
                                     yv12_frame->GetTimestamp(),
                                     yv12_frame->GetDuration(),
                                     &rgb_frame);
  media::VideoSurface rgb_surface;
  ASSERT_TRUE(rgb_frame->Lock(&rgb_surface));
  ASSERT_EQ(yuv_surface.width, rgb_surface.width);
  ASSERT_EQ(yuv_surface.height, rgb_surface.height);
  ASSERT_EQ(expect_rgb_planes, rgb_surface.planes);

  media::ConvertYUVToRGB32(yuv_surface.data[VideoSurface::kYPlane],
                           yuv_surface.data[VideoSurface::kUPlane],
                           yuv_surface.data[VideoSurface::kVPlane],
                           rgb_surface.data[VideoSurface::kRGBPlane],
                           rgb_surface.width,
                           rgb_surface.height,
                           yuv_surface.strides[VideoSurface::kYPlane],
                           yuv_surface.strides[VideoSurface::kUPlane],
                           rgb_surface.strides[VideoSurface::kRGBPlane],
                           media::YV12);

  for (size_t row = 0; row < rgb_surface.height; ++row) {
    uint32* rgb_row_data = reinterpret_cast<uint32*>(
        rgb_surface.data[VideoSurface::kRGBPlane] +
        (rgb_surface.strides[VideoSurface::kRGBPlane] * row));
    for (size_t col = 0; col < rgb_surface.width; ++col) {
      SCOPED_TRACE(StringPrintf("Checking (%u, %u)", row, col));
      EXPECT_EQ(expect_rgb_color, rgb_row_data[col]);
    }
  }
  rgb_frame->Unlock();
  yv12_frame->Unlock();
}

TEST(VideoFrameImpl, CreateFrame) {
  const size_t kWidth = 64;
  const size_t kHeight = 48;
  const base::TimeDelta kTimestampA = base::TimeDelta::FromMicroseconds(1337);
  const base::TimeDelta kDurationA = base::TimeDelta::FromMicroseconds(1667);
  const base::TimeDelta kTimestampB = base::TimeDelta::FromMicroseconds(1234);
  const base::TimeDelta kDurationB = base::TimeDelta::FromMicroseconds(5678);

  // Create a YV12 Video Frame.
  scoped_refptr<media::VideoFrame> frame;
  VideoFrameImpl::CreateFrame(media::VideoSurface::YV12, kWidth, kHeight,
                              kTimestampA, kDurationA, &frame);
  ASSERT_TRUE(frame);

  // Test StreamSample implementation.
  EXPECT_EQ(kTimestampA.InMicroseconds(),
            frame->GetTimestamp().InMicroseconds());
  EXPECT_EQ(kDurationA.InMicroseconds(), frame->GetDuration().InMicroseconds());
  EXPECT_FALSE(frame->IsEndOfStream());
  EXPECT_FALSE(frame->IsDiscontinuous());
  frame->SetTimestamp(kTimestampB);
  frame->SetDuration(kDurationB);
  EXPECT_EQ(kTimestampB.InMicroseconds(),
            frame->GetTimestamp().InMicroseconds());
  EXPECT_EQ(kDurationB.InMicroseconds(), frame->GetDuration().InMicroseconds());
  EXPECT_FALSE(frame->IsEndOfStream());
  frame->SetDiscontinuous(true);
  EXPECT_TRUE(frame->IsDiscontinuous());
  frame->SetDiscontinuous(false);
  EXPECT_FALSE(frame->IsDiscontinuous());

  // Test VideoFrame implementation.
  {
    SCOPED_TRACE("");
    InitializeYV12Frame(frame, 0.0f);
    ExpectFrameColor(frame, 0xFF000000);
  }
  {
    SCOPED_TRACE("");
    InitializeYV12Frame(frame, 1.0f);
    ExpectFrameColor(frame, 0xFFFFFFFF);
  }

  // Test an empty frame.
  VideoFrameImpl::CreateEmptyFrame(&frame);
  EXPECT_TRUE(frame->IsEndOfStream());
}

TEST(VideoFrameImpl, CreateBlackFrame) {
  const size_t kWidth = 2;
  const size_t kHeight = 2;
  const uint8 kExpectedYRow[] = { 0, 0 };
  const uint8 kExpectedUVRow[] = { 128 };

  scoped_refptr<media::VideoFrame> frame;
  VideoFrameImpl::CreateBlackFrame(kWidth, kHeight, &frame);
  ASSERT_TRUE(frame);

  // Test basic properties.
  EXPECT_EQ(0, frame->GetTimestamp().InMicroseconds());
  EXPECT_EQ(0, frame->GetDuration().InMicroseconds());
  EXPECT_FALSE(frame->IsEndOfStream());

  // Test surface properties.
  VideoSurface surface;
  EXPECT_TRUE(frame->Lock(&surface));
  EXPECT_EQ(VideoSurface::YV12, surface.format);
  EXPECT_EQ(kWidth, surface.width);
  EXPECT_EQ(kHeight, surface.height);
  EXPECT_EQ(3u, surface.planes);

  // Test surfaces themselves.
  for (size_t y = 0; y < surface.height; ++y) {
    EXPECT_EQ(0, memcmp(kExpectedYRow, surface.data[VideoSurface::kYPlane],
                        arraysize(kExpectedYRow)));
    surface.data[VideoSurface::kYPlane] +=
        surface.strides[VideoSurface::kYPlane];
  }
  for (size_t y = 0; y < surface.height / 2; ++y) {
    EXPECT_EQ(0, memcmp(kExpectedUVRow, surface.data[VideoSurface::kUPlane],
                        arraysize(kExpectedUVRow)));
    EXPECT_EQ(0, memcmp(kExpectedUVRow, surface.data[VideoSurface::kVPlane],
                        arraysize(kExpectedUVRow)));
    surface.data[VideoSurface::kUPlane] +=
        surface.strides[VideoSurface::kUPlane];
    surface.data[VideoSurface::kVPlane] +=
        surface.strides[VideoSurface::kVPlane];
  }
}

}  // namespace media
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include "Huffman.h"

using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;

template <typename K, typename V>
using MapIterator = typename map<K,V>::iterator;

template <typename K, typename V>
void printMap(map<K, V> table) {
    MapIterator<K, V> tableIterator = table.begin();
    for (; tableIterator != table.end(); tableIterator++) {
        cout << tableIterator->first << " " << tableIterator->second << endl;
    }
}

template <typename T>
void printVector(vector<T> v) {
    unsigned long size = v.size();
    for (int i = 0; i < size; i++) {
        cout << v[i] << " ";
    }
    cout << endl;
}

int main() {
    string input = "abracadabra1231231121";
    //cin >> input;

    map<char, int> table = Huffman::buildOccurrenceTable(input);
    printMap(table);
    Tree &tree = Huffman::buildTree(table);
    cout << tree << endl;
    map<char, string> codeTable = Huffman::buildCodeTable(tree);
    printMap(codeTable);

    string encoded = Huffman::encode(input, codeTable);
    cout << encoded << endl;

    cout << Huffman::decode(encoded, tree) << endl;

    printVector(Huffman::groupEncoded8bit(encoded));

    cout << Huffman::compressionRatio(input, encoded) << endl;

    Huffman::encodeToFile(input, "comp", "tree");
    cout << "FROMFILE:: " << Huffman::decodeFromFile("comp", "tree") << " ::FROMFILE\n";

    // Test serialization/deserialization of a huffman tree
    ofstream outFile("export");
    outFile << tree;
    outFile.close();

    Tree *testTree;
    ifstream inFile("export");
    inFile >> testTree;
    inFile.close();

    cout << *testTree;

    cout << "\nEND\n" << endl;

    return 0;
}<commit_msg>Added function template parameters for printMap calls in order to remove IDE linter errors (CLion).<commit_after>#include <iostream>
#include <fstream>
#include "Huffman.h"

using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;

template <typename K, typename V>
using MapIterator = typename map<K,V>::iterator;

template <typename K, typename V>
void printMap(map<K, V> table) {
    MapIterator<K, V> tableIterator = table.begin();
    for (; tableIterator != table.end(); tableIterator++) {
        cout << tableIterator->first << " " << tableIterator->second << endl;
    }
}

template <typename T>
void printVector(vector<T> v) {
    unsigned long size = v.size();
    for (int i = 0; i < size; i++) {
        cout << v[i] << " ";
    }
    cout << endl;
}

int main() {
    string input = "abracadabra1231231121";
    //cin >> input;

    map<char, int> table = Huffman::buildOccurrenceTable(input);
    printMap<char, int>(table);
    Tree &tree = Huffman::buildTree(table);
    cout << tree << endl;
    map<char, string> codeTable = Huffman::buildCodeTable(tree);
    printMap<char, string>(codeTable);

    string encoded = Huffman::encode(input, codeTable);
    cout << encoded << endl;

    cout << Huffman::decode(encoded, tree) << endl;

    printVector(Huffman::groupEncoded8bit(encoded));

    cout << Huffman::compressionRatio(input, encoded) << endl;

    Huffman::encodeToFile(input, "comp", "tree");
    cout << "FROMFILE:: " << Huffman::decodeFromFile("comp", "tree") << " ::FROMFILE\n";

    // Test serialization/deserialization of a huffman tree
    ofstream outFile("export");
    outFile << tree;
    outFile.close();

    Tree *testTree;
    ifstream inFile("export");
    inFile >> testTree;
    inFile.close();

    cout << *testTree;

    cout << "\nEND\n" << endl;

    return 0;
}<|endoftext|>


<commit_before>
#include <boost/test/unit_test.hpp>

#include "SoftXMT.hpp"
#include "Addressing.hpp"

BOOST_AUTO_TEST_SUITE( Addressing_tests );

// template< typename T >
// T bazf( T t ) {
//   GlobalPointer< T >( t );
//   return t.pointer();
// }

BOOST_AUTO_TEST_CASE( test1 ) {

  SoftXMT_init( &(boost::unit_test::framework::master_test_suite().argc),
                &(boost::unit_test::framework::master_test_suite().argv) );

  SoftXMT_activate();

  int foo;
  int bar;
  GlobalPointer< int > foop( &foo );
  GlobalPointer< int > barp( &bar );
  BOOST_CHECK_EQUAL( &foo, foop.pointer() );
  BOOST_CHECK_EQUAL( &bar, barp.pointer() );
  BOOST_CHECK_EQUAL( 8, sizeof( barp ) );

  GlobalPointer< int > gp2 = localToGlobal( &foo );
  BOOST_CHECK_EQUAL( gp2.pointer(), &foo );

  SoftXMT_finish( 0 );
}

BOOST_AUTO_TEST_SUITE_END();

<commit_msg>fixed GlobalAddress usage<commit_after>
#include <boost/test/unit_test.hpp>

#include "SoftXMT.hpp"
#include "Addressing.hpp"

BOOST_AUTO_TEST_SUITE( Addressing_tests );

// template< typename T >
// T bazf( T t ) {
//   GlobalPointer< T >( t );
//   return t.pointer();
// }

BOOST_AUTO_TEST_CASE( test1 ) {

  SoftXMT_init( &(boost::unit_test::framework::master_test_suite().argc),
                &(boost::unit_test::framework::master_test_suite().argv) );

  SoftXMT_activate();

  int foo;
  int bar;
  GlobalAddress< int > foop( &foo );
  GlobalAddress< int > barp( &bar );
  BOOST_CHECK_EQUAL( &foo, foop.pointer() );
  BOOST_CHECK_EQUAL( &bar, barp.pointer() );
  BOOST_CHECK_EQUAL( 8, sizeof( barp ) );

  GlobalAddress< int > gp2 = localToGlobal( &foo );
  BOOST_CHECK_EQUAL( gp2.pointer(), &foo );

  SoftXMT_finish( 0 );
}

BOOST_AUTO_TEST_SUITE_END();

<|endoftext|>


<commit_before>#include <GLFW/glfw3.h>

#include "GLFWSystem.hpp"
#include "EntityManager.hpp"

#include "data/InputBufferComponent.hpp"
#include "data/GLFWWindowComponent.hpp"
#include "data/WindowComponent.hpp"

#include "functions/OnTerminate.hpp"
#include "functions/OnMouseCaptured.hpp"
#include "functions/Execute.hpp"

#include "imgui.h"
#include "with.hpp"

static kengine::EntityManager * g_em;

namespace kengine {
#pragma region Input
	namespace Input {
		static InputBufferComponent * g_buffer;

		static void onKey(GLFWwindow * window, int key, int scancode, int action, int mods) {
			if (g_buffer == nullptr || (ImGui::GetCurrentContext() != nullptr && ImGui::GetIO().WantCaptureKeyboard))
				return;

			const auto id = (Entity::ID)glfwGetWindowUserPointer(window);

			if (action == GLFW_PRESS)
				g_buffer->keys.try_push_back(InputBufferComponent::KeyEvent{ id, key, true });
			else if (action == GLFW_RELEASE)
				g_buffer->keys.try_push_back(InputBufferComponent::KeyEvent{ id, key, false });
		}

		static putils::Point2f lastPos{ FLT_MAX, FLT_MAX };

		static void onClick(GLFWwindow * window, int button, int action, int mods) {
			if (g_buffer == nullptr || (ImGui::GetCurrentContext() != nullptr && ImGui::GetIO().WantCaptureMouse))
				return;

			const auto id = (Entity::ID)glfwGetWindowUserPointer(window);

			if (action == GLFW_PRESS)
				g_buffer->clicks.try_push_back(InputBufferComponent::ClickEvent{ id, lastPos, button, true });
			else if (action == GLFW_RELEASE)
				g_buffer->clicks.try_push_back(InputBufferComponent::ClickEvent{ id, lastPos, button, false });
		}

		static void onMouseMove(GLFWwindow * window, double xpos, double ypos) {
			if (lastPos.x == FLT_MAX) {
				lastPos.x = (float)xpos;
				lastPos.y = (float)ypos;
			}

			if (g_buffer == nullptr || (ImGui::GetCurrentContext() != nullptr && ImGui::GetIO().WantCaptureMouse))
				return;

			const auto id = (Entity::ID)glfwGetWindowUserPointer(window);

			InputBufferComponent::MouseMoveEvent info;
			info.window = id;
			info.pos = { (float)xpos, (float)ypos };
			info.rel = { (float)xpos - lastPos.x, (float)ypos - lastPos.y };
			lastPos = info.pos;

			g_buffer->moves.try_push_back(info);
		}

		static void onScroll(GLFWwindow * window, double xoffset, double yoffset) {
			if (g_buffer == nullptr || (ImGui::GetCurrentContext() != nullptr && ImGui::GetIO().WantCaptureMouse))
				return;

			const auto id = (Entity::ID)glfwGetWindowUserPointer(window);
			g_buffer->scrolls.try_push_back(InputBufferComponent::MouseScrollEvent{ id, (float)xoffset, (float)yoffset, lastPos });
		}
	}
#pragma endregion Input

#pragma region declarations
	static void terminate();
	static void onMouseCaptured(Entity::ID window, bool captured);
	static void execute(float deltaTime);
	static void onEntityCreated(Entity & e);
#pragma endregion
	EntityCreator * GLFWSystem(EntityManager & em) {
		g_em = &em;
		glfwInit();

		return [](Entity & e) {
			e += functions::OnTerminate{ terminate };
			e += functions::OnMouseCaptured{ onMouseCaptured };
			e += functions::Execute{ execute };
			e += functions::OnEntityCreated{ onEntityCreated };
		};
	}

#pragma region execute
#pragma region declarations
	static void init(Entity & e, WindowComponent & window);
#pragma endregion
	static void execute(float deltaTime) {
		for (const auto & [e, window, glfw] : g_em->getEntities<WindowComponent, GLFWWindowComponent>())
			if (glfwWindowShouldClose(glfw.window.get())) {
				if (window.shutdownOnClose)
					g_em->running = false;
				else
					g_em->removeEntity(e.id);
			}

		for (auto & [e, window, noGLFW] : g_em->getEntities<WindowComponent, no<GLFWWindowComponent>>())
			init(e, window);
	}

	static void init(Entity & e, WindowComponent & window) {
		auto & glfwComp = e.attach<GLFWWindowComponent>();

		glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
		glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
		glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
#ifndef KENGINE_NDEBUG
		glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
#endif
		// TODO: depend on g_windowComponent->fullscreen
		glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);

		glfwComp.window = glfwCreateWindow((int)window.size.x, (int)window.size.y, window.name, nullptr, nullptr);
		// Desired size may not have been available, update to actual size
		int width, height;
		glfwGetWindowSize(glfwComp.window.get(), &width, &height);
		window.size = { (unsigned int)width, (unsigned int)height };
		glfwSetWindowAspectRatio(glfwComp.window.get(), window.size.x, window.size.y);

		glfwMakeContextCurrent(glfwComp.window.get());
		glfwSetWindowSizeCallback(glfwComp.window.get(), [](auto window, int width, int height) {
			const auto id = (Entity::ID)glfwGetWindowUserPointer(window);
			auto & comp = g_em->getEntity(id).get<WindowComponent>();
			comp.size = { (unsigned int)width, (unsigned int)height };
		});

		glfwSetMouseButtonCallback(glfwComp.window.get(), Input::onClick);
		glfwSetCursorPosCallback(glfwComp.window.get(), Input::onMouseMove);
		glfwSetScrollCallback(glfwComp.window.get(), Input::onScroll);
		glfwSetKeyCallback(glfwComp.window.get(), Input::onKey);

		glfwSetWindowUserPointer(glfwComp.window.get(), (void *)e.id);
	}
#pragma endregion execute

	static void onEntityCreated(Entity & e) {
		const auto window = e.tryGet<WindowComponent>();
		if (window)
			init(e, *window);
	}

	static void terminate() {
		glfwTerminate();
	}

	static void onMouseCaptured(Entity::ID window, bool captured) {
		const auto inputMode = captured ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL;

		if (captured)
			ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NoMouse;
		else
			ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_NoMouse;

		if (window == Entity::INVALID_ID) {
			for (const auto & [e, glfw] : g_em->getEntities<GLFWWindowComponent>())
				glfwSetInputMode(glfw.window.get(), GLFW_CURSOR, inputMode);
			return;
		}

		const auto glfw = g_em->getEntity(window).tryGet<GLFWWindowComponent>();
		if (glfw == nullptr)
			return;

		glfwSetInputMode(glfw->window.get(), GLFW_CURSOR, inputMode);
	}
}<commit_msg>glfw -- initialize input buffer + initialize pre-existing windows<commit_after>#include <GLFW/glfw3.h>

#include "GLFWSystem.hpp"
#include "EntityManager.hpp"

#include "data/InputBufferComponent.hpp"
#include "data/GLFWWindowComponent.hpp"
#include "data/WindowComponent.hpp"

#include "functions/OnTerminate.hpp"
#include "functions/OnMouseCaptured.hpp"
#include "functions/Execute.hpp"

#include "imgui.h"
#include "with.hpp"

static kengine::EntityManager * g_em;

namespace kengine {
#pragma region Input
	namespace Input {
		static InputBufferComponent * g_buffer;

		static void onKey(GLFWwindow * window, int key, int scancode, int action, int mods) {
			if (g_buffer == nullptr || (ImGui::GetCurrentContext() != nullptr && ImGui::GetIO().WantCaptureKeyboard))
				return;

			const auto id = (Entity::ID)glfwGetWindowUserPointer(window);

			if (action == GLFW_PRESS)
				g_buffer->keys.try_push_back(InputBufferComponent::KeyEvent{ id, key, true });
			else if (action == GLFW_RELEASE)
				g_buffer->keys.try_push_back(InputBufferComponent::KeyEvent{ id, key, false });
		}

		static putils::Point2f lastPos{ FLT_MAX, FLT_MAX };

		static void onClick(GLFWwindow * window, int button, int action, int mods) {
			if (g_buffer == nullptr || (ImGui::GetCurrentContext() != nullptr && ImGui::GetIO().WantCaptureMouse))
				return;

			const auto id = (Entity::ID)glfwGetWindowUserPointer(window);

			if (action == GLFW_PRESS)
				g_buffer->clicks.try_push_back(InputBufferComponent::ClickEvent{ id, lastPos, button, true });
			else if (action == GLFW_RELEASE)
				g_buffer->clicks.try_push_back(InputBufferComponent::ClickEvent{ id, lastPos, button, false });
		}

		static void onMouseMove(GLFWwindow * window, double xpos, double ypos) {
			if (lastPos.x == FLT_MAX) {
				lastPos.x = (float)xpos;
				lastPos.y = (float)ypos;
			}

			if (g_buffer == nullptr || (ImGui::GetCurrentContext() != nullptr && ImGui::GetIO().WantCaptureMouse))
				return;

			const auto id = (Entity::ID)glfwGetWindowUserPointer(window);

			InputBufferComponent::MouseMoveEvent info;
			info.window = id;
			info.pos = { (float)xpos, (float)ypos };
			info.rel = { (float)xpos - lastPos.x, (float)ypos - lastPos.y };
			lastPos = info.pos;

			g_buffer->moves.try_push_back(info);
		}

		static void onScroll(GLFWwindow * window, double xoffset, double yoffset) {
			if (g_buffer == nullptr || (ImGui::GetCurrentContext() != nullptr && ImGui::GetIO().WantCaptureMouse))
				return;

			const auto id = (Entity::ID)glfwGetWindowUserPointer(window);
			g_buffer->scrolls.try_push_back(InputBufferComponent::MouseScrollEvent{ id, (float)xoffset, (float)yoffset, lastPos });
		}
	}
#pragma endregion Input

#pragma region declarations
	static void terminate();
	static void onMouseCaptured(Entity::ID window, bool captured);
	static void execute(float deltaTime);
	static void onEntityCreated(Entity & e);
#pragma endregion
	EntityCreator * GLFWSystem(EntityManager & em) {
		g_em = &em;

		for (const auto & [e, buffer] : em.getEntities<InputBufferComponent>()) {
			Input::g_buffer = &buffer;
			break;
		}

		glfwInit();
		execute(0.f); // init already existing windows

		return [](Entity & e) {
			e += functions::Execute{ execute };
			e += functions::OnEntityCreated{ onEntityCreated };
			e += functions::OnTerminate{ terminate };
			e += functions::OnMouseCaptured{ onMouseCaptured };
		};
	}

#pragma region execute
#pragma region declarations
	static void init(Entity & e, WindowComponent & window);
#pragma endregion
	static void execute(float deltaTime) {
		for (const auto & [e, window, glfw] : g_em->getEntities<WindowComponent, GLFWWindowComponent>())
			if (glfwWindowShouldClose(glfw.window.get())) {
				if (window.shutdownOnClose)
					g_em->running = false;
				else
					g_em->removeEntity(e.id);
			}

		for (auto & [e, window, noGLFW] : g_em->getEntities<WindowComponent, no<GLFWWindowComponent>>())
			init(e, window);
	}

	static void init(Entity & e, WindowComponent & window) {
		auto & glfwComp = e.attach<GLFWWindowComponent>();

		glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
		glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
		glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
#ifndef KENGINE_NDEBUG
		glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
#endif
		// TODO: depend on g_windowComponent->fullscreen
		glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);

		glfwComp.window = glfwCreateWindow((int)window.size.x, (int)window.size.y, window.name, nullptr, nullptr);
		// Desired size may not have been available, update to actual size
		int width, height;
		glfwGetWindowSize(glfwComp.window.get(), &width, &height);
		window.size = { (unsigned int)width, (unsigned int)height };
		glfwSetWindowAspectRatio(glfwComp.window.get(), window.size.x, window.size.y);

		glfwMakeContextCurrent(glfwComp.window.get());
		glfwSetWindowSizeCallback(glfwComp.window.get(), [](auto window, int width, int height) {
			const auto id = (Entity::ID)glfwGetWindowUserPointer(window);
			auto & comp = g_em->getEntity(id).get<WindowComponent>();
			comp.size = { (unsigned int)width, (unsigned int)height };
		});

		glfwSetMouseButtonCallback(glfwComp.window.get(), Input::onClick);
		glfwSetCursorPosCallback(glfwComp.window.get(), Input::onMouseMove);
		glfwSetScrollCallback(glfwComp.window.get(), Input::onScroll);
		glfwSetKeyCallback(glfwComp.window.get(), Input::onKey);

		glfwSetWindowUserPointer(glfwComp.window.get(), (void *)e.id);
	}
#pragma endregion execute

	static void onEntityCreated(Entity & e) {
		const auto window = e.tryGet<WindowComponent>();
		if (window)
			init(e, *window);
	}

	static void terminate() {
		glfwTerminate();
	}

	static void onMouseCaptured(Entity::ID window, bool captured) {
		const auto inputMode = captured ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL;

		if (captured)
			ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NoMouse;
		else
			ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_NoMouse;

		if (window == Entity::INVALID_ID) {
			for (const auto & [e, glfw] : g_em->getEntities<GLFWWindowComponent>())
				glfwSetInputMode(glfw.window.get(), GLFW_CURSOR, inputMode);
			return;
		}

		const auto glfw = g_em->getEntity(window).tryGet<GLFWWindowComponent>();
		if (glfw == nullptr)
			return;

		glfwSetInputMode(glfw->window.get(), GLFW_CURSOR, inputMode);
	}
}<|endoftext|>


<commit_before>#include "pileup.h"
#include <htslib/sam.h>
#include "samio.h"
#include <iostream>

Pileup::Pileup(std::string samfile, std::string reffile): reader(samfile), ref(reffile), tid(), pos(), cov(), pileup(nullptr), iter(), alleles(), qual(), names(), readgroups(), counts({{'A',0},{'T',0},{'G',0},{'C',0}})  {
	iter = bam_plp_init(&Pileup::plp_get_read, &reader);
}

Pileup::Pileup(std::string samfile, std::string reffile, std::string region): reader(samfile, region), ref(reffile), tid(), pos(), cov(), pileup(nullptr), iter(), alleles(), qual(), names(), readgroups(), counts({{'A',0},{'T',0},{'G',0},{'C',0}}) {
	iter = bam_plp_init(&Pileup::plp_get_read, &reader);
}

Pileup::~Pileup(){
	std::cout << "calling pileup destructor" << std::endl;
	bam_plp_destroy(iter);
	std::cout << "bam_plp_destroy success" << std::endl;
}

//typedef int (*bam_plp_auto_f)(void *data, bam1_t *b);
int Pileup::plp_get_read(void *data, bam1_t *b){
	SamReader *reader = (SamReader*)data;
	return reader->next(b);
}

//possible optimization: store sequence strings in a hash w/ alignment, throw out of hash once no longer in pileup
int Pileup::next(){
	if((pileup = bam_plp_auto(iter, &tid, &pos, &cov)) != nullptr){ //successfully pile up new position
		alleles.clear(); qual.clear(); names.clear(); readgroups.clear(); counts.clear();
		std::cout << "cleared arrays OK" << std::endl;
		alleles.reserve(cov); qual.reserve(cov); names.reserve(cov); readgroups.reserve(cov);
		std::cout << "reserved memory OK" << std::endl;
		for (int i = 0; i < cov; ++i){
			bam1_t* alignment = pileup[i].b;
			uint8_t* seq = bam_get_seq(alignment);
			char* rg = bam_aux2Z(bam_aux_get(alignment, "RG"));
			int qpos = pileup[i].qpos;
			int baseint = bam_seqi(seq,qpos);
			char allele = seq_nt16_str[baseint];
			std::string name(bam_get_qname(alignment));
			std::string readgroup(rg);
			std::cout<< "got variables OK" << std::endl;
			alleles[i] = allele;
			++counts[allele];
			std::cout << "counted OK" << std::endl;
			qual[i] = bam_get_qual(alignment)[qpos];
			std::cout << "set qualities OK" << std::endl;
			names[i] = name;
			std::cout << "set names OK" << std::endl;
			std::cout << "readgroup = " << readgroup << std::endl;
			readgroups[i] = readgroup;
			std::cout<< "set readgroups OK" << std::endl;
			bam_destroy1(alignment);
		}
		return 1;
	} else {
		return 0;
	}
}

int Pileup::get_tid(){
	return tid;
}

int Pileup::get_pos(){
	return pos;
}

std::string Pileup::chr_name(){
	return reader.get_ref_name(tid);
}

int Pileup::get_ref_tid(std::string name){
	return reader.get_ref_tid(name);
}

std::map<std::string,int> Pileup::get_name_map(){
	return reader.get_name_map();
}

<commit_msg>try to make things better<commit_after>#include "pileup.h"
#include <htslib/sam.h>
#include "samio.h"
#include <iostream>

Pileup::Pileup(std::string samfile, std::string reffile): reader(samfile), ref(reffile), tid(), pos(), cov(), pileup(nullptr), iter(), alleles(), qual(), names(), readgroups(), counts({{'A',0},{'T',0},{'G',0},{'C',0}})  {
	iter = bam_plp_init(&Pileup::plp_get_read, &reader);
}

Pileup::Pileup(std::string samfile, std::string reffile, std::string region): reader(samfile, region), ref(reffile), tid(), pos(), cov(), pileup(nullptr), iter(), alleles(), qual(), names(), readgroups(), counts({{'A',0},{'T',0},{'G',0},{'C',0}}) {
	iter = bam_plp_init(&Pileup::plp_get_read, &reader);
}

Pileup::~Pileup(){
	std::cout << "calling pileup destructor" << std::endl;
	bam_plp_destroy(iter);
	std::cout << "bam_plp_destroy success" << std::endl;
}

//typedef int (*bam_plp_auto_f)(void *data, bam1_t *b);
int Pileup::plp_get_read(void *data, bam1_t *b){
	SamReader *reader = (SamReader*)data;
	return reader->next(b);
}

//possible optimization: store sequence strings in a hash w/ alignment, throw out of hash once no longer in pileup
int Pileup::next(){
	if((pileup = bam_plp_auto(iter, &tid, &pos, &cov)) != nullptr){ //successfully pile up new position
		alleles.clear(); qual.clear(); names.clear(); readgroups.clear(); counts.clear();
		std::cout << "cleared arrays OK" << std::endl;
		alleles.reserve(cov); qual.reserve(cov); names.reserve(cov); readgroups.reserve(cov);
		std::cout << "reserved memory OK" << std::endl;
		for (int i = 0; i < cov; ++i){
			bam1_t* alignment = pileup[i].b;
			uint8_t* seq = bam_get_seq(alignment);
			int qpos = pileup[i].qpos;
			int baseint = bam_seqi(seq,qpos);
			char allele = seq_nt16_str[baseint];
			std::string name(bam_get_qname(alignment));
			std::cout<< "got variables OK" << std::endl;
			alleles[i] = allele;
			++counts[allele];
			std::cout << "counted OK" << std::endl;
			qual[i] = bam_get_qual(alignment)[qpos];
			std::cout << "set qualities OK" << std::endl;
			names[i] = name;
			std::cout << "set names OK" << std::endl;

			// if (rg == NULL){
			// 	readgroups[i] = "";
			// }
			// else{
			// 	char* readgroup = bam_aux2Z(rg);
			// 	if (readgroup != NULL){
			// 		readgroups[i] = std::string(readgroup);
			// 	}
			// }

			readgroups[i] = std::string(bam_aux2Z(bam_aux_get(alignment, "RG")))2;

			std::cout<< "set readgroups OK" << std::endl;
			// bam_destroy1(alignment);
		}
		return 1;
	} else {
		return 0;
	}
}

int Pileup::get_tid(){
	return tid;
}

int Pileup::get_pos(){
	return pos;
}

std::string Pileup::chr_name(){
	return reader.get_ref_name(tid);
}

int Pileup::get_ref_tid(std::string name){
	return reader.get_ref_tid(name);
}

std::map<std::string,int> Pileup::get_name_map(){
	return reader.get_name_map();
}

<|endoftext|>


<commit_before>#include "plugin.h"

#include <prtypes.h>

#include <algorithm>
#include <cstring>

#include "emacsinstance.h"
#include "npapi-headers/npfunctions.h"

NPNetscapeFuncs g_browser_functions = { 0 };

namespace {

NPError initializeBrowserFuncs(NPNetscapeFuncs* bFuncs)
{
    if (!bFuncs)
        return NPERR_INVALID_FUNCTABLE_ERROR;

    int major_version = bFuncs->version >> 8;
    int minor_version = bFuncs->version & 0xff;

    if (major_version != NP_VERSION_MAJOR)
        return NPERR_INCOMPATIBLE_VERSION_ERROR;

    // TODO: Assert support in minor_version for features we care
    // about.

    memcpy(&g_browser_functions, bFuncs,
           std::min(sizeof(g_browser_functions), (size_t)bFuncs->size));

    return NPERR_NO_ERROR;
}

}  // namespace

NP_EXPORT(NPError) OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs)
{
    pFuncs->size = sizeof(*pFuncs);
    pFuncs->version = 0; // My version?
    pFuncs->newp = NPP_New;
    pFuncs->destroy = NPP_Destroy;
    pFuncs->setwindow = NPP_SetWindow;
    pFuncs->getvalue = NPP_GetValue;
    // TODO: implement the functions I need.
    return NPERR_NO_ERROR;
}

NP_EXPORT(NPError) OSCALL NP_Initialize(NPNetscapeFuncs* bFuncs,
					NPPluginFuncs* pFuncs)
{
    NPError err = initializeBrowserFuncs(bFuncs);
    if (err != NPERR_NO_ERROR)
        return err;

    // Require XEmbed support.
    PRBool has_xembed = PR_FALSE;
    if (!g_browser_functions.getvalue)
        return NPERR_INCOMPATIBLE_VERSION_ERROR;
    err = g_browser_functions.getvalue(NULL, NPNVSupportsXEmbedBool, &has_xembed);
    if (err != NPERR_NO_ERROR || !has_xembed)
        return NPERR_INCOMPATIBLE_VERSION_ERROR;

    // On Unix, it looks like NP_GetEntryPoints isn't called directly?
    // The prototype for NP_Initialize is different from everyone
    // else. Meh.
    return NP_GetEntryPoints(pFuncs);
}

NP_EXPORT(NPError) OSCALL NP_GetValue(void *instance,
                                      NPPVariable variable,
                                      void *value)
{
    NPError err = NPERR_NO_ERROR;
    switch (variable) {
        case NPPVpluginNameString:
            *reinterpret_cast<const char **>(value) = "Embedded Emacs";
            break;
        case NPPVpluginDescriptionString:
            *reinterpret_cast<const char **>(value) =
                    "Embeds emacs into your browser window with XEmbed.";
            break;
        default:
            err = NPERR_GENERIC_ERROR;
    }
    return err;
}

// This probably should be const char *, but NPAPI messed up.
NP_EXPORT(char*) OSCALL NP_GetMIMEDescription(void)
{
    return const_cast<char*>("application/x-emacs-npapi::Embed emacs with NPAPI");
}

/*****************************/
/* NPP Functions             */
/*****************************/

NPError NPP_New(NPMIMEType pluginType, NPP instance,
                uint16_t mode, int16_t argc, char* argn[],
                char* argv[], NPSavedData* saved)
{
    return NPERR_GENERIC_ERROR;
}

NPError NPP_Destroy(NPP instance, NPSavedData** save)
{
    return NPERR_GENERIC_ERROR;
}

NPError NPP_SetWindow(NPP instance, NPWindow* window)
{
    return NPERR_GENERIC_ERROR;
}

NPError NPP_GetValue(NPP instance, NPPVariable variable, void* value)
{
    NPError err = NPERR_NO_ERROR;
    switch (variable) {
        case NPPVpluginNeedsXEmbed:
            *reinterpret_cast<PRBool*>(value) = PR_TRUE;
            break;
        default:
            err = NPERR_GENERIC_ERROR;
    }
    return err;
}
<commit_msg>Implement NPP_Destroy<commit_after>#include "plugin.h"

#include <prtypes.h>

#include <algorithm>
#include <cstring>

#include "emacsinstance.h"
#include "npapi-headers/npfunctions.h"

NPNetscapeFuncs g_browser_functions = { 0 };

namespace {

NPError initializeBrowserFuncs(NPNetscapeFuncs* bFuncs)
{
    if (!bFuncs)
        return NPERR_INVALID_FUNCTABLE_ERROR;

    int major_version = bFuncs->version >> 8;
    int minor_version = bFuncs->version & 0xff;

    if (major_version != NP_VERSION_MAJOR)
        return NPERR_INCOMPATIBLE_VERSION_ERROR;

    // TODO: Assert support in minor_version for features we care
    // about.

    memcpy(&g_browser_functions, bFuncs,
           std::min(sizeof(g_browser_functions), (size_t)bFuncs->size));

    return NPERR_NO_ERROR;
}

}  // namespace

NP_EXPORT(NPError) OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs)
{
    pFuncs->size = sizeof(*pFuncs);
    pFuncs->version = 0; // My version?
    pFuncs->newp = NPP_New;
    pFuncs->destroy = NPP_Destroy;
    pFuncs->setwindow = NPP_SetWindow;
    pFuncs->getvalue = NPP_GetValue;
    // TODO: implement the functions I need.
    return NPERR_NO_ERROR;
}

NP_EXPORT(NPError) OSCALL NP_Initialize(NPNetscapeFuncs* bFuncs,
					NPPluginFuncs* pFuncs)
{
    NPError err = initializeBrowserFuncs(bFuncs);
    if (err != NPERR_NO_ERROR)
        return err;

    // Require XEmbed support.
    PRBool has_xembed = PR_FALSE;
    if (!g_browser_functions.getvalue)
        return NPERR_INCOMPATIBLE_VERSION_ERROR;
    err = g_browser_functions.getvalue(NULL, NPNVSupportsXEmbedBool, &has_xembed);
    if (err != NPERR_NO_ERROR || !has_xembed)
        return NPERR_INCOMPATIBLE_VERSION_ERROR;

    // On Unix, it looks like NP_GetEntryPoints isn't called directly?
    // The prototype for NP_Initialize is different from everyone
    // else. Meh.
    return NP_GetEntryPoints(pFuncs);
}

NP_EXPORT(NPError) OSCALL NP_GetValue(void *instance,
                                      NPPVariable variable,
                                      void *value)
{
    NPError err = NPERR_NO_ERROR;
    switch (variable) {
        case NPPVpluginNameString:
            *reinterpret_cast<const char **>(value) = "Embedded Emacs";
            break;
        case NPPVpluginDescriptionString:
            *reinterpret_cast<const char **>(value) =
                    "Embeds emacs into your browser window with XEmbed.";
            break;
        default:
            err = NPERR_GENERIC_ERROR;
    }
    return err;
}

// This probably should be const char *, but NPAPI messed up.
NP_EXPORT(char*) OSCALL NP_GetMIMEDescription(void)
{
    return const_cast<char*>("application/x-emacs-npapi::Embed emacs with NPAPI");
}

/*****************************/
/* NPP Functions             */
/*****************************/

NPError NPP_New(NPMIMEType pluginType, NPP instance,
                uint16_t mode, int16_t argc, char* argn[],
                char* argv[], NPSavedData* saved)
{
    return NPERR_GENERIC_ERROR;
}

NPError NPP_Destroy(NPP instance, NPSavedData** save)
{
    if (!instance || !instance->pdata)
        return NPERR_INVALID_INSTANCE_ERROR;
    EmacsInstance* emacs = static_cast<EmacsInstance*>(instance->pdata);
    delete emacs;
    return NPERR_NO_ERROR;
}

NPError NPP_SetWindow(NPP instance, NPWindow* window)
{
    return NPERR_GENERIC_ERROR;
}

NPError NPP_GetValue(NPP instance, NPPVariable variable, void* value)
{
    NPError err = NPERR_NO_ERROR;
    switch (variable) {
        case NPPVpluginNeedsXEmbed:
            *reinterpret_cast<PRBool*>(value) = PR_TRUE;
            break;
        default:
            err = NPERR_GENERIC_ERROR;
    }
    return err;
}
<|endoftext|>


<commit_before>#include<iostream>
#include<cmath>
#include <kv/interval.hpp>
#include <kv/rdouble.hpp>
using namespace std;
int main(void)
{
  // verification program for the Ramanujan theta function
  // defined as f(a,b)=Sum[(a^(n*(n+1)/2))*b^(n*(n-1)/2),{n,-Infinity,Infinity}]
  // this function is the generalized form of Jacobi theta functions
  // this function is defined when |ab|<1
  // Jacobi triple product identity is used for verification
  // f(a,b)=(-a,ab)_Infinity (-b,ab)_Infinity (ab,ab)_Infinity
  // f(a,b) is expressed with q exponential functions
cout.precision(16);
 int K=1000;
 int j=1;
 kv::interval<double> A;
 kv::interval<double> B;
 A=0.1;
 B=0.2;
 // calculate (-a,ab)_Infinity
 kv::interval<double> q1;
 kv::interval<double> z1;
 z1=-A;
 q1=A*B;
 kv::interval<double> a;
 kv::interval<double> b;
  a=1/(1-z1);
  b=1.;
 // derived from the definition of q-Pochhammer symbol
  for (int k=1; k<=K; k++){
    j = -1*j;
    b=b*(1-pow(q1,k));
    a=a+j*pow(q1,k*(k+1)/2)/(b*(1-z1*pow(q1,k)));
  }
  b=b*(1-pow(q1,K+1));
  double rad1=abs(pow(-1,K+1)*pow(q1,(K+1)*(K+2)/2)/(b*(1-z1*pow(q1,K+1)))).upper();
  kv::interval<double> series1=a+rad1; // result must be an interval
  // calculate the value of Euler function
 kv::interval<double> c=1-q1;
 int m=1;
 for (int l=1; l<=K; l++){
   m = -1*m;
   c = c+m*(1-pow(q1,2*l+1))*pow(q1,l*(3*l+1)/2);
  }
  double eulerrad1=abs(pow(-1,K+1)*(1-pow(q1,2*K+3))*pow(q1,(K+1)*(3*K+4)/2)).upper();
  kv::interval<double> euler=c+eulerrad1;
  kv::interval<double> exp1=series1/euler;
  kv::interval<double> pro1=1/exp1;
 // calculate (-b,ab)_Infinity
 kv::interval<double> z2;
 z2=-B;
 // reuse q1
 kv::interval<double> a2;
 kv::interval<double> b2;
  a2=1/(1-z2);
  b2=1.;
 // derived from the definition of q-Pochhammer symbol
 int j2=1;
  for (int k2=1; k2<=K; k2++){
    j2 = -1*j2;
    b2=b2*(1-pow(q1,k2));
    a2=a2+j2*pow(q1,k2*(k2+1)/2)/(b2*(1-z2*pow(q1,k2)));
  }
  b2=b2*(1-pow(q1,K+1));
  double rad2=abs(pow(-1,K+1)*pow(q1,(K+1)*(K+2)/2)/(b2*(1-z2*pow(q1,K+1)))).upper();
  kv::interval<double> series2=a2+rad2; // result must be an interval
  // reuse the value of Euler function

  kv::interval<double> exp2=series2/euler;
  kv::interval<double> pro2=1/exp2;
// reuse (ab,ab)_Infinity (Euler function)
  kv::interval<double> res=pro1*pro2*euler;
  cout << res << endl;// final result
}
<commit_msg>Delete Ramanujan-theta.cc<commit_after><|endoftext|>


<commit_before>#include "fenwick_tree.h"
#include "string/kmp.h"
#include "string/algorithm.h"
#include "string/ustring.h"
#include "string/utility.h"
#include "optional.h"
#include "suffix_array/checker.h"
#include "suffix_array/lcp.h"
#include "suffix_array/rmq.h"
#include "suffix_array/invsa.h"
#include <stddef.h>
#include <deque>
#include <string>
#include <vector>

namespace pfi {
namespace data {

template class fenwick_tree<int>;

namespace string {

template class kmp<std::string>;

template int edit_distance<std::string>(const std::string&, const std::string&);
template int longest_common_subsequence<std::string>(const std::string&, const std::string&);
template int longest_increasing_subsequence<std::string>(const std::string&);

template ustring::ustring<char*>(char*, char*);
template uchar chars_to_uchar<char*>(char*&);
template void uchar_to_chars<char*>(uchar, char*&);

template void split<std::string, char, std::string*>(const std::string&, char, std::string*);
template std::deque<std::string> split<std::deque<std::string>, std::string, char>(const std::string&, char);
template std::vector<std::string> split<std::string, char>(const std::string&, char);
template void split<std::string, std::string*>(const std::string&, const std::string&, std::string*);
template std::deque<std::string> split<std::deque<std::string>, std::string>(const std::string&, const std::string&);
template std::vector<std::string> split<std::string>(const std::string&, const std::string&);
template void strip<std::string>(const std::string&, std::string&);
template std::string strip<std::string>(const std::string&);
template void lstrip<std::string>(const std::string&, std::string&);
template std::string lstrip<std::string>(const std::string&);
template void rstrip<std::string>(const std::string&, std::string&);
template std::string rstrip<std::string>(const std::string&);
template void join<std::string*, std::string>(std::string*, std::string*, const std::string&, std::string&);
template void join<std::vector<std::string>, std::string>(const std::vector<std::string>&, const std::string&, std::string&);
template std::string join<std::string*, std::string>(std::string*, std::string*, const std::string&);
template std::string join<std::vector<std::string>, std::string>(const std::vector<std::string>&, const std::string&);
template bool starts_with<std::string>(const std::string&, const std::string&);
template bool ends_with<std::string>(const std::string&, const std::string&);
template void replace<std::string>(const std::string&, const std::string&, const std::string&, std::string&);
template std::string replace<std::string>(const std::string&, const std::string&, const std::string&);

} // namespace string

template class optional<int>;
template optional<int>::optional<long>(const optional<long>&);
template optional<int>& optional<int>::operator=<long>(const optional<long>&);
template bool operator==<optional<int> >(const optional<optional<int> >&, const optional<optional<int> >&);
template bool operator!=<optional<int> >(const optional<optional<int> >&, const optional<optional<int> >&);
template bool operator< <optional<int> >(const optional<optional<int> >&, const optional<optional<int> >&);
template bool operator><optional<int> >(const optional<optional<int> >&, const optional<optional<int> >&);
template bool operator<=<optional<int> >(const optional<optional<int> >&, const optional<optional<int> >&);
template bool operator>=<optional<int> >(const optional<optional<int> >&, const optional<optional<int> >&);

namespace suffix_array {

template bool check_sa<std::string*, size_t*>(std::string*, std::string*, size_t*);

template void lcp(std::string*, std::string*, size_t*, std::vector<int>&);

template int cartesian_type<size_t*>(size_t*);
template int cartesian_type<size_t*>(size_t*, size_t*);
template class rmq<std::vector<int> >;
template void rmq<std::vector<size_t> >::construct_type<size_t*>(size_t*, size_t*, int);
template void rmq<std::vector<size_t> >::construct_log_table<size_t*>(size_t*, size_t*);

template void invert_suffix_array<size_t*>(size_t*, size_t*, std::vector<int>&);

} // namespace suffix_array
} // namespace data
} // namespace pfi
<commit_msg>Added instantiation test for data/intern.h.<commit_after>#include "fenwick_tree.h"
#include "string/kmp.h"
#include "string/algorithm.h"
#include "string/ustring.h"
#include "string/utility.h"
#include "optional.h"
#include "suffix_array/checker.h"
#include "suffix_array/lcp.h"
#include "suffix_array/rmq.h"
#include "suffix_array/invsa.h"
#include "intern.h"
#include <stddef.h>
#include <deque>
#include <functional>
#include <string>
#include <vector>

namespace pfi {
namespace data {

template class fenwick_tree<int>;

namespace string {

template class kmp<std::string>;

template int edit_distance<std::string>(const std::string&, const std::string&);
template int longest_common_subsequence<std::string>(const std::string&, const std::string&);
template int longest_increasing_subsequence<std::string>(const std::string&);

template ustring::ustring<char*>(char*, char*);
template uchar chars_to_uchar<char*>(char*&);
template void uchar_to_chars<char*>(uchar, char*&);

template void split<std::string, char, std::string*>(const std::string&, char, std::string*);
template std::deque<std::string> split<std::deque<std::string>, std::string, char>(const std::string&, char);
template std::vector<std::string> split<std::string, char>(const std::string&, char);
template void split<std::string, std::string*>(const std::string&, const std::string&, std::string*);
template std::deque<std::string> split<std::deque<std::string>, std::string>(const std::string&, const std::string&);
template std::vector<std::string> split<std::string>(const std::string&, const std::string&);
template void strip<std::string>(const std::string&, std::string&);
template std::string strip<std::string>(const std::string&);
template void lstrip<std::string>(const std::string&, std::string&);
template std::string lstrip<std::string>(const std::string&);
template void rstrip<std::string>(const std::string&, std::string&);
template std::string rstrip<std::string>(const std::string&);
template void join<std::string*, std::string>(std::string*, std::string*, const std::string&, std::string&);
template void join<std::vector<std::string>, std::string>(const std::vector<std::string>&, const std::string&, std::string&);
template std::string join<std::string*, std::string>(std::string*, std::string*, const std::string&);
template std::string join<std::vector<std::string>, std::string>(const std::vector<std::string>&, const std::string&);
template bool starts_with<std::string>(const std::string&, const std::string&);
template bool ends_with<std::string>(const std::string&, const std::string&);
template void replace<std::string>(const std::string&, const std::string&, const std::string&, std::string&);
template std::string replace<std::string>(const std::string&, const std::string&, const std::string&);

} // namespace string

template class optional<int>;
template optional<int>::optional<long>(const optional<long>&);
template optional<int>& optional<int>::operator=<long>(const optional<long>&);
template bool operator==<optional<int> >(const optional<optional<int> >&, const optional<optional<int> >&);
template bool operator!=<optional<int> >(const optional<optional<int> >&, const optional<optional<int> >&);
template bool operator< <optional<int> >(const optional<optional<int> >&, const optional<optional<int> >&);
template bool operator><optional<int> >(const optional<optional<int> >&, const optional<optional<int> >&);
template bool operator<=<optional<int> >(const optional<optional<int> >&, const optional<optional<int> >&);
template bool operator>=<optional<int> >(const optional<optional<int> >&, const optional<optional<int> >&);

namespace suffix_array {

template bool check_sa<std::string*, size_t*>(std::string*, std::string*, size_t*);

template void lcp(std::string*, std::string*, size_t*, std::vector<int>&);

template int cartesian_type<size_t*>(size_t*);
template int cartesian_type<size_t*>(size_t*, size_t*);
template class rmq<std::vector<int> >;
template void rmq<std::vector<size_t> >::construct_type<size_t*>(size_t*, size_t*, int);
template void rmq<std::vector<size_t> >::construct_log_table<size_t*>(size_t*, size_t*);

template void invert_suffix_array<size_t*>(size_t*, size_t*, std::vector<int>&);

} // namespace suffix_array

template class intern<int, std::greater<int> >;
template void intern<int>::serialize<serialization::binary_iarchive>(serialization::binary_iarchive&);

} // namespace data
} // namespace pfi
<|endoftext|>


<commit_before>/*
 * ngtcp2
 *
 * Copyright (c) 2017 ngtcp2 contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#include "debug.h"

#include <cinttypes>
#include <random>

#include "util.h"

namespace ngtcp2 {

namespace debug {

namespace {
auto randgen = util::make_mt19937();
} // namespace

namespace {
std::chrono::steady_clock::time_point ts_base;
} // namespace

void reset_timestamp() { ts_base = std::chrono::steady_clock::now(); }

std::chrono::microseconds timestamp() {
  return std::chrono::duration_cast<std::chrono::microseconds>(
      std::chrono::steady_clock::now() - ts_base);
}

namespace {
auto color_output = false;
} // namespace

void set_color_output(bool f) { color_output = f; }

namespace {
auto *outfile = stderr;
} // namespace

namespace {
const char *ansi_esc(const char *code) { return color_output ? code : ""; }
} // namespace

namespace {
const char *ansi_escend() { return color_output ? "\033[0m" : ""; }
} // namespace

enum ngtcp2_dir {
  NGTCP2_DIR_SEND,
  NGTCP2_DIR_RECV,
};

namespace {
std::string strpkttype_long(uint8_t type) {
  switch (type) {
  case NGTCP2_PKT_VERSION_NEGOTIATION:
    return "Version Negotiation";
  case NGTCP2_PKT_CLIENT_INITIAL:
    return "Client Initial";
  case NGTCP2_PKT_SERVER_STATELESS_RETRY:
    return "Server Stateless Retry";
  case NGTCP2_PKT_SERVER_CLEARTEXT:
    return "Server Cleartext";
  case NGTCP2_PKT_CLIENT_CLEARTEXT:
    return "Client Cleartext";
  case NGTCP2_PKT_0RTT_PROTECTED:
    return "0-RTT Protected";
  case NGTCP2_PKT_1RTT_PROTECTED_K0:
    return "1-RTT Protected (key phase 0)";
  case NGTCP2_PKT_1RTT_PROTECTED_K1:
    return "1-RTT Protected (key phase 1)";
  case NGTCP2_PKT_PUBLIC_RESET:
    return "Public Reset";
  default:
    return "UNKNOWN (0x" + util::format_hex(type) + ")";
  }
}
} // namespace

namespace {
std::string strpkttype_short(uint8_t type) {
  switch (type) {
  case NGTCP2_PKT_01:
    return "Short 01";
  case NGTCP2_PKT_02:
    return "Short 02";
  case NGTCP2_PKT_03:
    return "Short 03";
  default:
    return "UNKNOWN (0x" + util::format_hex(type) + ")";
  }
}
} // namespace

namespace {
std::string strframetype(uint8_t type) {
  switch (type) {
  case NGTCP2_FRAME_PADDING:
    return "PADDING";
  case NGTCP2_FRAME_RST_STREAM:
    return "RST_STREAM";
  case NGTCP2_FRAME_CONNECTION_CLOSE:
    return "CONNECTION_CLOSE";
  case NGTCP2_FRAME_GOAWAY:
    return "GOAWAY";
  case NGTCP2_FRAME_MAX_DATA:
    return "MAX_DATA";
  case NGTCP2_FRAME_MAX_STREAM_DATA:
    return "MAX_STREAM_DATA";
  case NGTCP2_FRAME_MAX_STREAM_ID:
    return "MAX_STREAM_ID";
  case NGTCP2_FRAME_PING:
    return "PING";
  case NGTCP2_FRAME_BLOCKED:
    return "BLOCKED";
  case NGTCP2_FRAME_STREAM_BLOCKED:
    return "STREAM_BLOCKED";
  case NGTCP2_FRAME_STREAM_ID_NEEDED:
    return "STREAM_ID_NEEDED";
  case NGTCP2_FRAME_NEW_CONNECTION_ID:
    return "NEW_CONNECTION_ID";
  case NGTCP2_FRAME_ACK:
    return "ACK";
  case NGTCP2_FRAME_STREAM:
    return "STREAM";
  default:
    return "UNKNOWN (0x" + util::format_hex(type) + ")";
  }
}
} // namespace

void print_timestamp() {
  auto t = timestamp().count();
  fprintf(outfile, "%st=%d.%06d%s ", ansi_esc("\033[33m"),
          static_cast<int32_t>(t / 1000000), static_cast<int32_t>(t % 1000000),
          ansi_escend());
}

namespace {
const char *pkt_ansi_esc(ngtcp2_dir dir) {
  return ansi_esc(dir == NGTCP2_DIR_SEND ? "\033[1;35m" : "\033[1;36m");
}
} // namespace

namespace {
const char *frame_ansi_esc(ngtcp2_dir dir) {
  return ansi_esc(dir == NGTCP2_DIR_SEND ? "\033[1;35m" : "\033[1;36m");
}
} // namespace

namespace {
void print_indent() { fprintf(outfile, "           "); }
} // namespace

namespace {
void print_pkt_long(ngtcp2_dir dir, const ngtcp2_pkt_hd *hd) {
  fprintf(outfile, "%s%s%s CID=%016lx PKN=%" PRIu64 " V=%08x\n",
          pkt_ansi_esc(dir), strpkttype_long(hd->type).c_str(), ansi_escend(),
          hd->conn_id, hd->pkt_num, hd->version);
}
} // namespace

namespace {
void print_pkt_short(ngtcp2_dir dir, const ngtcp2_pkt_hd *hd) {
  fprintf(outfile, "%s%s%s CID=%016lx PKN=%" PRIu64 "\n", pkt_ansi_esc(dir),
          strpkttype_short(hd->type).c_str(), ansi_escend(), hd->conn_id,
          hd->pkt_num);
}
} // namespace

namespace {
void print_pkt(ngtcp2_dir dir, const ngtcp2_pkt_hd *hd) {
  if (hd->flags & NGTCP2_PKT_FLAG_LONG_FORM) {
    print_pkt_long(dir, hd);
  } else {
    print_pkt_short(dir, hd);
  }
}
} // namespace

namespace {
void print_frame(ngtcp2_dir dir, const ngtcp2_frame *fr) {
  fprintf(outfile, "%s%s%s\n", frame_ansi_esc(dir),
          strframetype(fr->type).c_str(), ansi_escend());

  switch (fr->type) {
  case NGTCP2_FRAME_STREAM:
    print_indent();
    fprintf(outfile,
            "stream_id=%08x fin=%u offset=%" PRIu64 " data_length=%zu\n",
            fr->stream.stream_id, fr->stream.fin, fr->stream.offset,
            fr->stream.datalen);
    break;
  case NGTCP2_FRAME_PADDING:
    print_indent();
    fprintf(outfile, "length=%zu\n", fr->padding.len);
    break;
  case NGTCP2_FRAME_ACK:
    print_indent();
    fprintf(outfile,
            "num_blks=%zu num_ts=%zu largest_ack=%" PRIu64 " ack_delay=%u\n",
            fr->ack.num_blks, fr->ack.num_ts, fr->ack.largest_ack,
            fr->ack.ack_delay);
    print_indent();
    fprintf(outfile, "first_ack_block_length=%" PRIu64 "\n",
            fr->ack.first_ack_blklen);
    for (size_t i = 0; i < fr->ack.num_blks; ++i) {
      auto blk = &fr->ack.blks[i];
      print_indent();
      fprintf(outfile, "gap=%u ack_block_length=%" PRIu64 "\n", blk->gap,
              blk->blklen);
    }
    break;
  case NGTCP2_FRAME_RST_STREAM:
    print_indent();
    fprintf(outfile,
            "stream_id=%08x error_code=%08x final_offset=%" PRIu64 "\n",
            fr->rst_stream.stream_id, fr->rst_stream.error_code,
            fr->rst_stream.final_offset);
    break;
  case NGTCP2_FRAME_CONNECTION_CLOSE:
    print_indent();
    fprintf(outfile, "error_code=%08x reason_length=%zu\n",
            fr->connection_close.error_code, fr->connection_close.reasonlen);
    break;
  case NGTCP2_FRAME_GOAWAY:
    print_indent();
    fprintf(outfile,
            "largest_client_stream_id=%08x largest_server_stream_id=%08x\n",
            fr->goaway.largest_client_stream_id,
            fr->goaway.largest_server_stream_id);
    break;
  case NGTCP2_FRAME_MAX_DATA:
    print_indent();
    fprintf(outfile, "max_data=%" PRIu64 "\n", fr->max_data.max_data);
    break;
  case NGTCP2_FRAME_MAX_STREAM_DATA:
    print_indent();
    fprintf(outfile, "stream_id=%08x max_stream_data=%" PRIu64 "\n",
            fr->max_stream_data.stream_id, fr->max_stream_data.max_stream_data);
    break;
  case NGTCP2_FRAME_MAX_STREAM_ID:
    print_indent();
    fprintf(outfile, "max_stream_id=%08x\n", fr->max_stream_id.max_stream_id);
    break;
  case NGTCP2_FRAME_PING:
    break;
  case NGTCP2_FRAME_BLOCKED:
    break;
  case NGTCP2_FRAME_STREAM_BLOCKED:
    print_indent();
    fprintf(outfile, "stream_id=%08x\n", fr->stream_blocked.stream_id);
    break;
  case NGTCP2_FRAME_STREAM_ID_NEEDED:
    break;
  case NGTCP2_FRAME_NEW_CONNECTION_ID:
    print_indent();
    fprintf(outfile, "seq=%u conn_id=%016lx\n", fr->new_connection_id.seq,
            fr->new_connection_id.conn_id);
    break;
  }
}
} // namespace

int send_pkt(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd, void *user_data) {
  print_timestamp();
  fprintf(outfile, "TX ");
  print_pkt(NGTCP2_DIR_SEND, hd);
  return 0;
}

int send_frame(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
               const ngtcp2_frame *fr, void *user_data) {
  print_indent();
  print_frame(NGTCP2_DIR_SEND, fr);
  return 0;
}

int recv_pkt(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd, void *user_data) {
  print_timestamp();
  fprintf(outfile, "RX ");
  print_pkt(NGTCP2_DIR_RECV, hd);
  return 0;
}

int recv_frame(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
               const ngtcp2_frame *fr, void *user_data) {
  print_indent();
  print_frame(NGTCP2_DIR_RECV, fr);
  return 0;
}

int handshake_completed(ngtcp2_conn *conn, void *user_data) {
  print_timestamp();
  fprintf(outfile, "QUIC handshake has completed\n");
  return 0;
}

int recv_version_negotiation(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
                             const uint32_t *sv, size_t nsv, void *user_data) {
  for (size_t i = 0; i < nsv; ++i) {
    print_indent();
    fprintf(outfile, "version=%08x\n", sv[i]);
  }
  return 0;
}

bool packet_lost(double prob) {
  auto p = std::uniform_real_distribution<>(0, 1)(randgen);
  return p < prob;
}

void print_transport_params(const ngtcp2_transport_params *params, int type) {
  switch (type) {
  case NGTCP2_TRANSPORT_PARAMS_TYPE_CLIENT_HELLO:
    print_indent();
    fprintf(outfile, "negotiated_version=%08x\n",
            params->v.ch.negotiated_version);
    print_indent();
    fprintf(outfile, "initial_version=%08x\n", params->v.ch.initial_version);
    break;
  case NGTCP2_TRANSPORT_PARAMS_TYPE_ENCRYPTED_EXTENSIONS:
    for (size_t i = 0; i < params->v.ee.len; ++i) {
      print_indent();
      fprintf(outfile, "supported_version[%zu]=%08x\n", i,
              params->v.ee.supported_versions[i]);
    }
    break;
  }

  print_indent();
  fprintf(outfile, "initial_max_stream_data=%u\n",
          params->initial_max_stream_data);
  print_indent();
  fprintf(outfile, "initial_max_data=%u\n", params->initial_max_data);
  print_indent();
  fprintf(outfile, "initial_max_stream_id=%u\n", params->initial_max_stream_id);
  print_indent();
  fprintf(outfile, "idle_timeout=%u\n", params->idle_timeout);
  print_indent();
  fprintf(outfile, "omit_connection_id=%u\n", params->omit_connection_id);
  print_indent();
  fprintf(outfile, "max_packet_size=%u\n", params->max_packet_size);
}

void print_stream_data(uint32_t stream_id, const uint8_t *data,
                       size_t datalen) {
  print_timestamp();
  fprintf(outfile, "%sSTREAM%s data stream_id=%08x\n",
          frame_ansi_esc(NGTCP2_DIR_RECV), ansi_escend(), stream_id);
  util::hexdump(outfile, data, datalen);
}

} // namespace debug

} // namespace ngtcp2
<commit_msg>Print indent instead of timestamp<commit_after>/*
 * ngtcp2
 *
 * Copyright (c) 2017 ngtcp2 contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#include "debug.h"

#include <cinttypes>
#include <random>

#include "util.h"

namespace ngtcp2 {

namespace debug {

namespace {
auto randgen = util::make_mt19937();
} // namespace

namespace {
std::chrono::steady_clock::time_point ts_base;
} // namespace

void reset_timestamp() { ts_base = std::chrono::steady_clock::now(); }

std::chrono::microseconds timestamp() {
  return std::chrono::duration_cast<std::chrono::microseconds>(
      std::chrono::steady_clock::now() - ts_base);
}

namespace {
auto color_output = false;
} // namespace

void set_color_output(bool f) { color_output = f; }

namespace {
auto *outfile = stderr;
} // namespace

namespace {
const char *ansi_esc(const char *code) { return color_output ? code : ""; }
} // namespace

namespace {
const char *ansi_escend() { return color_output ? "\033[0m" : ""; }
} // namespace

enum ngtcp2_dir {
  NGTCP2_DIR_SEND,
  NGTCP2_DIR_RECV,
};

namespace {
std::string strpkttype_long(uint8_t type) {
  switch (type) {
  case NGTCP2_PKT_VERSION_NEGOTIATION:
    return "Version Negotiation";
  case NGTCP2_PKT_CLIENT_INITIAL:
    return "Client Initial";
  case NGTCP2_PKT_SERVER_STATELESS_RETRY:
    return "Server Stateless Retry";
  case NGTCP2_PKT_SERVER_CLEARTEXT:
    return "Server Cleartext";
  case NGTCP2_PKT_CLIENT_CLEARTEXT:
    return "Client Cleartext";
  case NGTCP2_PKT_0RTT_PROTECTED:
    return "0-RTT Protected";
  case NGTCP2_PKT_1RTT_PROTECTED_K0:
    return "1-RTT Protected (key phase 0)";
  case NGTCP2_PKT_1RTT_PROTECTED_K1:
    return "1-RTT Protected (key phase 1)";
  case NGTCP2_PKT_PUBLIC_RESET:
    return "Public Reset";
  default:
    return "UNKNOWN (0x" + util::format_hex(type) + ")";
  }
}
} // namespace

namespace {
std::string strpkttype_short(uint8_t type) {
  switch (type) {
  case NGTCP2_PKT_01:
    return "Short 01";
  case NGTCP2_PKT_02:
    return "Short 02";
  case NGTCP2_PKT_03:
    return "Short 03";
  default:
    return "UNKNOWN (0x" + util::format_hex(type) + ")";
  }
}
} // namespace

namespace {
std::string strframetype(uint8_t type) {
  switch (type) {
  case NGTCP2_FRAME_PADDING:
    return "PADDING";
  case NGTCP2_FRAME_RST_STREAM:
    return "RST_STREAM";
  case NGTCP2_FRAME_CONNECTION_CLOSE:
    return "CONNECTION_CLOSE";
  case NGTCP2_FRAME_GOAWAY:
    return "GOAWAY";
  case NGTCP2_FRAME_MAX_DATA:
    return "MAX_DATA";
  case NGTCP2_FRAME_MAX_STREAM_DATA:
    return "MAX_STREAM_DATA";
  case NGTCP2_FRAME_MAX_STREAM_ID:
    return "MAX_STREAM_ID";
  case NGTCP2_FRAME_PING:
    return "PING";
  case NGTCP2_FRAME_BLOCKED:
    return "BLOCKED";
  case NGTCP2_FRAME_STREAM_BLOCKED:
    return "STREAM_BLOCKED";
  case NGTCP2_FRAME_STREAM_ID_NEEDED:
    return "STREAM_ID_NEEDED";
  case NGTCP2_FRAME_NEW_CONNECTION_ID:
    return "NEW_CONNECTION_ID";
  case NGTCP2_FRAME_ACK:
    return "ACK";
  case NGTCP2_FRAME_STREAM:
    return "STREAM";
  default:
    return "UNKNOWN (0x" + util::format_hex(type) + ")";
  }
}
} // namespace

void print_timestamp() {
  auto t = timestamp().count();
  fprintf(outfile, "%st=%d.%06d%s ", ansi_esc("\033[33m"),
          static_cast<int32_t>(t / 1000000), static_cast<int32_t>(t % 1000000),
          ansi_escend());
}

namespace {
const char *pkt_ansi_esc(ngtcp2_dir dir) {
  return ansi_esc(dir == NGTCP2_DIR_SEND ? "\033[1;35m" : "\033[1;36m");
}
} // namespace

namespace {
const char *frame_ansi_esc(ngtcp2_dir dir) {
  return ansi_esc(dir == NGTCP2_DIR_SEND ? "\033[1;35m" : "\033[1;36m");
}
} // namespace

namespace {
void print_indent() { fprintf(outfile, "           "); }
} // namespace

namespace {
void print_pkt_long(ngtcp2_dir dir, const ngtcp2_pkt_hd *hd) {
  fprintf(outfile, "%s%s%s CID=%016lx PKN=%" PRIu64 " V=%08x\n",
          pkt_ansi_esc(dir), strpkttype_long(hd->type).c_str(), ansi_escend(),
          hd->conn_id, hd->pkt_num, hd->version);
}
} // namespace

namespace {
void print_pkt_short(ngtcp2_dir dir, const ngtcp2_pkt_hd *hd) {
  fprintf(outfile, "%s%s%s CID=%016lx PKN=%" PRIu64 "\n", pkt_ansi_esc(dir),
          strpkttype_short(hd->type).c_str(), ansi_escend(), hd->conn_id,
          hd->pkt_num);
}
} // namespace

namespace {
void print_pkt(ngtcp2_dir dir, const ngtcp2_pkt_hd *hd) {
  if (hd->flags & NGTCP2_PKT_FLAG_LONG_FORM) {
    print_pkt_long(dir, hd);
  } else {
    print_pkt_short(dir, hd);
  }
}
} // namespace

namespace {
void print_frame(ngtcp2_dir dir, const ngtcp2_frame *fr) {
  fprintf(outfile, "%s%s%s\n", frame_ansi_esc(dir),
          strframetype(fr->type).c_str(), ansi_escend());

  switch (fr->type) {
  case NGTCP2_FRAME_STREAM:
    print_indent();
    fprintf(outfile,
            "stream_id=%08x fin=%u offset=%" PRIu64 " data_length=%zu\n",
            fr->stream.stream_id, fr->stream.fin, fr->stream.offset,
            fr->stream.datalen);
    break;
  case NGTCP2_FRAME_PADDING:
    print_indent();
    fprintf(outfile, "length=%zu\n", fr->padding.len);
    break;
  case NGTCP2_FRAME_ACK:
    print_indent();
    fprintf(outfile,
            "num_blks=%zu num_ts=%zu largest_ack=%" PRIu64 " ack_delay=%u\n",
            fr->ack.num_blks, fr->ack.num_ts, fr->ack.largest_ack,
            fr->ack.ack_delay);
    print_indent();
    fprintf(outfile, "first_ack_block_length=%" PRIu64 "\n",
            fr->ack.first_ack_blklen);
    for (size_t i = 0; i < fr->ack.num_blks; ++i) {
      auto blk = &fr->ack.blks[i];
      print_indent();
      fprintf(outfile, "gap=%u ack_block_length=%" PRIu64 "\n", blk->gap,
              blk->blklen);
    }
    break;
  case NGTCP2_FRAME_RST_STREAM:
    print_indent();
    fprintf(outfile,
            "stream_id=%08x error_code=%08x final_offset=%" PRIu64 "\n",
            fr->rst_stream.stream_id, fr->rst_stream.error_code,
            fr->rst_stream.final_offset);
    break;
  case NGTCP2_FRAME_CONNECTION_CLOSE:
    print_indent();
    fprintf(outfile, "error_code=%08x reason_length=%zu\n",
            fr->connection_close.error_code, fr->connection_close.reasonlen);
    break;
  case NGTCP2_FRAME_GOAWAY:
    print_indent();
    fprintf(outfile,
            "largest_client_stream_id=%08x largest_server_stream_id=%08x\n",
            fr->goaway.largest_client_stream_id,
            fr->goaway.largest_server_stream_id);
    break;
  case NGTCP2_FRAME_MAX_DATA:
    print_indent();
    fprintf(outfile, "max_data=%" PRIu64 "\n", fr->max_data.max_data);
    break;
  case NGTCP2_FRAME_MAX_STREAM_DATA:
    print_indent();
    fprintf(outfile, "stream_id=%08x max_stream_data=%" PRIu64 "\n",
            fr->max_stream_data.stream_id, fr->max_stream_data.max_stream_data);
    break;
  case NGTCP2_FRAME_MAX_STREAM_ID:
    print_indent();
    fprintf(outfile, "max_stream_id=%08x\n", fr->max_stream_id.max_stream_id);
    break;
  case NGTCP2_FRAME_PING:
    break;
  case NGTCP2_FRAME_BLOCKED:
    break;
  case NGTCP2_FRAME_STREAM_BLOCKED:
    print_indent();
    fprintf(outfile, "stream_id=%08x\n", fr->stream_blocked.stream_id);
    break;
  case NGTCP2_FRAME_STREAM_ID_NEEDED:
    break;
  case NGTCP2_FRAME_NEW_CONNECTION_ID:
    print_indent();
    fprintf(outfile, "seq=%u conn_id=%016lx\n", fr->new_connection_id.seq,
            fr->new_connection_id.conn_id);
    break;
  }
}
} // namespace

int send_pkt(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd, void *user_data) {
  print_timestamp();
  fprintf(outfile, "TX ");
  print_pkt(NGTCP2_DIR_SEND, hd);
  return 0;
}

int send_frame(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
               const ngtcp2_frame *fr, void *user_data) {
  print_indent();
  print_frame(NGTCP2_DIR_SEND, fr);
  return 0;
}

int recv_pkt(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd, void *user_data) {
  print_timestamp();
  fprintf(outfile, "RX ");
  print_pkt(NGTCP2_DIR_RECV, hd);
  return 0;
}

int recv_frame(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
               const ngtcp2_frame *fr, void *user_data) {
  print_indent();
  print_frame(NGTCP2_DIR_RECV, fr);
  return 0;
}

int handshake_completed(ngtcp2_conn *conn, void *user_data) {
  print_timestamp();
  fprintf(outfile, "QUIC handshake has completed\n");
  return 0;
}

int recv_version_negotiation(ngtcp2_conn *conn, const ngtcp2_pkt_hd *hd,
                             const uint32_t *sv, size_t nsv, void *user_data) {
  for (size_t i = 0; i < nsv; ++i) {
    print_indent();
    fprintf(outfile, "version=%08x\n", sv[i]);
  }
  return 0;
}

bool packet_lost(double prob) {
  auto p = std::uniform_real_distribution<>(0, 1)(randgen);
  return p < prob;
}

void print_transport_params(const ngtcp2_transport_params *params, int type) {
  switch (type) {
  case NGTCP2_TRANSPORT_PARAMS_TYPE_CLIENT_HELLO:
    print_indent();
    fprintf(outfile, "negotiated_version=%08x\n",
            params->v.ch.negotiated_version);
    print_indent();
    fprintf(outfile, "initial_version=%08x\n", params->v.ch.initial_version);
    break;
  case NGTCP2_TRANSPORT_PARAMS_TYPE_ENCRYPTED_EXTENSIONS:
    for (size_t i = 0; i < params->v.ee.len; ++i) {
      print_indent();
      fprintf(outfile, "supported_version[%zu]=%08x\n", i,
              params->v.ee.supported_versions[i]);
    }
    break;
  }

  print_indent();
  fprintf(outfile, "initial_max_stream_data=%u\n",
          params->initial_max_stream_data);
  print_indent();
  fprintf(outfile, "initial_max_data=%u\n", params->initial_max_data);
  print_indent();
  fprintf(outfile, "initial_max_stream_id=%u\n", params->initial_max_stream_id);
  print_indent();
  fprintf(outfile, "idle_timeout=%u\n", params->idle_timeout);
  print_indent();
  fprintf(outfile, "omit_connection_id=%u\n", params->omit_connection_id);
  print_indent();
  fprintf(outfile, "max_packet_size=%u\n", params->max_packet_size);
}

void print_stream_data(uint32_t stream_id, const uint8_t *data,
                       size_t datalen) {
  print_indent();
  fprintf(outfile, "ordered STREAM data stream_id=%08x\n", stream_id);
  util::hexdump(outfile, data, datalen);
}

} // namespace debug

} // namespace ngtcp2
<|endoftext|>