//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: libcpp-has-no-threads

// [[nodiscard]] on constructors isn't supported by all compilers
// UNSUPPORTED: clang-6, clang-7, clang-8, clang-9
// UNSUPPORTED: apple-clang-9, apple-clang-10, apple-clang-11

// <mutex>

// template <class Mutex> class lock_guard;

// [[nodiscard]] explicit lock_guard(mutex_type& m);
// [[nodiscard]] lock_guard(mutex_type& m, adopt_lock_t);

// Test that we properly apply [[nodiscard]] to lock_guard's constructors,
// which is a libc++ extension.

// MODULES_DEFINES: _LIBCPP_ENABLE_NODISCARD
#define _LIBCPP_ENABLE_NODISCARD
#include <mutex>

int main(int, char**) {
    std::mutex m;
    std::lock_guard<std::mutex>{m}; // expected-error{{ignoring temporary created by a constructor declared with 'nodiscard' attribute}}
    std::lock_guard<std::mutex>{m, std::adopt_lock}; // expected-error{{ignoring temporary created by a constructor declared with 'nodiscard' attribute}}
    return 0;
}

//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: libcpp-has-no-threads

// [[nodiscard]] on constructors isn't supported by all compilers
// UNSUPPORTED: clang-6, clang-7, clang-8, clang-9
// UNSUPPORTED: apple-clang-9, apple-clang-10, apple-clang-11

// [[nodiscard]] isn't supported in C++98 and C++03 (not even as an extension)
// UNSUPPORTED: c++98, c++03

// <mutex>

// template <class Mutex> class lock_guard;

// [[nodiscard]] explicit lock_guard(mutex_type& m);
// [[nodiscard]] lock_guard(mutex_type& m, adopt_lock_t);

// Test that we properly apply [[nodiscard]] to lock_guard's constructors,
// which is a libc++ extension.

// MODULES_DEFINES: _LIBCPP_ENABLE_NODISCARD
#define _LIBCPP_ENABLE_NODISCARD
#include <mutex>

int main(int, char**) {
    std::mutex m;
    std::lock_guard<std::mutex>{m}; // expected-error{{ignoring temporary created by a constructor declared with 'nodiscard' attribute}}
    std::lock_guard<std::mutex>{m, std::adopt_lock}; // expected-error{{ignoring temporary created by a constructor declared with 'nodiscard' attribute}}
    return 0;
}

[libc++] Mark lock_guard nodiscard test as unsupported in C++03

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@369672 91177308-0d34-0410-b5e6-96231b3b80d8


#include "./video_recorder_controller.h"
#include <QDateTime>
#include "./video_recorder.h"

VideoRecorderController::VideoRecorderController(
    std::shared_ptr<VideoRecorder> videoRecorder)
  : videoRecorder(videoRecorder)
{
  connect(this, SIGNAL(toggleRecording()), this,
          SLOT(toggleRecordingInMainThread()), Qt::QueuedConnection);
}

void VideoRecorderController::startNewVideo()
{
  const QDateTime now = QDateTime::currentDateTime();
  const QString timestamp = now.toString(QLatin1String("yyyy-MM-dd-hhmmsszzz"));
  auto filename = QString::fromLatin1("video_%1.mpeg").arg(timestamp);

  videoRecorder->createNewVideo(filename.toStdString());
  videoRecorder->startRecording();
}

QString VideoRecorderController::getToggleText()
{
  if (videoRecorder->getIsRecording())
    return "Stop recording";

  return "Start recording";
}

void VideoRecorderController::toggleRecordingInMainThread()
{
  if (videoRecorder->getIsRecording())
  {
    videoRecorder->stopRecording();
  }
  else
  {
    videoRecorder->startRecording();
  }

  emit recordingStateSwitched();
}

#include "./video_recorder_controller.h"
#include <QDateTime>
#include "./video_recorder.h"

VideoRecorderController::VideoRecorderController(
    std::shared_ptr<VideoRecorder> videoRecorder)
  : videoRecorder(videoRecorder)
{
  connect(this, SIGNAL(toggleRecording()), this,
          SLOT(toggleRecordingInMainThread()), Qt::QueuedConnection);
}

void VideoRecorderController::startNewVideo()
{
  const QDateTime now = QDateTime::currentDateTime();
  const QString timestamp = now.toString(QLatin1String("yyyy-MM-dd-hhmmsszzz"));
  auto filename = QString::fromLatin1("video_%1.mpeg").arg(timestamp);

  videoRecorder->createNewVideo(filename.toStdString());
  videoRecorder->startRecording();

  emit recordingStateSwitched();
}

QString VideoRecorderController::getToggleText()
{
  if (videoRecorder->getIsRecording())
    return "Stop recording";

  return "Start recording";
}

void VideoRecorderController::toggleRecordingInMainThread()
{
  if (videoRecorder->getIsRecording())
  {
    videoRecorder->stopRecording();
  }
  else
  {
    videoRecorder->startRecording();
  }

  emit recordingStateSwitched();
}

Fix toggle text after first video recording start.


/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include <glib-object.h>
#include <QDir>

#include "components.h"
#include "launcher.h"
#include "roundedimage.h"
#include "viewfinder.h"
#include "zoomarea.h"

components::components ()
{
  // Initialise the GObject type system
  g_type_init ();

  if (QDir::home ().mkpath ("Pictures/Camera") == false) {
    qDebug () << "Error making camera directory: " << QDir::homePath () << "/Pictures/Camera";
  }

  if (QDir::home ().mkpath ("Videos/Camera") == false) {
    qDebug () << "Error making camera directory: " << QDir::homePath () << "/Pictures/Camera";
  }
}

void components::registerTypes(const char *uri)
{
  qmlRegisterType<Launcher>(uri, 0, 1, "Launcher");
  qmlRegisterType<RoundedImage>(uri, 0, 1, "RoundedImage");
  qmlRegisterType<ViewFinder>(uri, 0, 1, "ViewFinder");
  qmlRegisterType<ZoomArea>(uri, 0, 1, "ZoomArea");
}

Q_EXPORT_PLUGIN(components);

/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include <glib-object.h>
#include <QDir>

#include "components.h"
#include "launcher.h"
#include "roundedimage.h"
#include "viewfinder.h"

components::components ()
{
  // Initialise the GObject type system
  g_type_init ();

  if (QDir::home ().mkpath ("Pictures/Camera") == false) {
    qDebug () << "Error making camera directory: " << QDir::homePath () << "/Pictures/Camera";
  }

  if (QDir::home ().mkpath ("Videos/Camera") == false) {
    qDebug () << "Error making camera directory: " << QDir::homePath () << "/Pictures/Camera";
  }
}

void components::registerTypes(const char *uri)
{
  qmlRegisterType<Launcher>(uri, 0, 1, "Launcher");
  qmlRegisterType<RoundedImage>(uri, 0, 1, "RoundedImage");
  qmlRegisterType<ViewFinder>(uri, 0, 1, "ViewFinder");
}

Q_EXPORT_PLUGIN(components);

[Components] Remove the unused ZoomArea from the elements


#include <QApplication>
#include "gtest/gtest.h"

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    ::testing::InitGoogleTest(&argc, argv);
    int returnValue = RUN_ALL_TESTS();
    return returnValue;
}

#include <QCoreApplication>
#include "gtest/gtest.h"

int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);
    ::testing::InitGoogleTest(&argc, argv);
    int returnValue = RUN_ALL_TESTS();
    return returnValue;
}

Use QCoreApplication for unit tests as it should not depend on GUI stuff.


#include<iostream>

using namespace std;

int removeElement(int A[], int n, int elem) {
    int length = n-1;
    for(int i = 0; i <= length; ++i) {
        if(A[i] == elem) {
            while (A[length] != elem) {
                length--;
            }
            A[i] = A[length--];
        }
    }

    return length + 1;
}

int main() {
    int A[] = {1,2,3,4,1,6,3,4};

    int length = removeElement(A, 8, 1);
    for(int i = 0; i < length; ++i) {
        cout << A[i] << endl;
    }

    return 0;
}

#include<iostream>

using namespace std;

int removeElement(int A[], int n, int elem) {
    if (n == 0) {
        return n;
    }

    if (n == 1 && A[0] == elem) {
        return 0;
    }

    if (n == 1 && A[0] !=  elem) {
        return n;
    }

    int tail = n - 1;
    int i = 0;
    while (i <= tail) {
        if (A[i] == elem) {
            A[i] = A[tail];
            --tail;
        } else {
            ++i;
        }
    }

    return tail + 1;
}

int main() {
    int A[] = {1,2,3};

    int length = removeElement(A, 3, 1);
    for(int i = 0; i < length; ++i) {
        cout << A[i] << endl;
    }

    cout << endl;

    int B[] = {1,1};

    length = removeElement(B, 2, 1);
    for(int i = 0; i < length; ++i) {
        cout << B[i] << endl;
    }
    return 0;
}

Remove an element from a list completed

Remove an element from a list completed


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

#include "//third_party/open_spiel/spiel_utils.h"
#include "<torch/torch.h>"

namespace {

void TestMatrixMultiplication() {
  at::Tensor mat = torch::rand({3, 3});
  at::Tensor identity = torch::ones({3, 3});
  at::Tensor multiplied = mat * identity;
  int num_identical_elements = (mat == multiplied).sum().item().to<int>();
  SPIEL_CHECK_EQ(num_identical_elements, 9);
}

}  // namespace

int main() { TestMatrixMultiplication(); }

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

#include "open_spiel/spiel_utils.h"
#include "torch/torch.h"

namespace {

void TestMatrixMultiplication() {
  at::Tensor mat = torch::rand({3, 3});
  at::Tensor identity = torch::ones({3, 3});
  at::Tensor multiplied = mat * identity;
  int num_identical_elements = (mat == multiplied).sum().item().to<int>();
  SPIEL_CHECK_EQ(num_identical_elements, 9);
}

}  // namespace

int main() { TestMatrixMultiplication(); }

Fix includes in integration test example.


#include <unistd.h>
#include <gtest/gtest.h>
#include "getusername.h"

TEST(GetUserName,simple)
{
	// allocate a WCHAR_T buffer to receive username
	DWORD lpnSize = 64;
	WCHAR_T lpBuffer[lpnSize];

	BOOL result = GetUserName(lpBuffer, &lpnSize);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// get expected username
	const char *username = getlogin();

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(strlen(username)+1, lpnSize);

	// TODO: ASSERT_STREQ(username, Utf16leToUtf8(lpBuffer))
}

#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"

using std::string;
using std::vector;
using SCXCoreLib::Utf16leToUtf8;

TEST(GetUserName,simple)
{
	// allocate a WCHAR_T buffer to receive username
	DWORD lpnSize = 64;
	WCHAR_T lpBuffer[lpnSize];

	BOOL result = GetUserName(lpBuffer, &lpnSize);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// get expected username
	string username = string(getlogin());

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(username.size()+1, lpnSize);

	// copy UTF-16 bytes from lpBuffer to vector for conversion
	vector<unsigned char> input(reinterpret_cast<unsigned char *>(&lpBuffer[0]),
	                            reinterpret_cast<unsigned char *>(&lpBuffer[lpnSize-1]));
	// convert to UTF-8 for assertion
	string output;
	Utf16leToUtf8(input, output);

	EXPECT_EQ(username, output);
}

Test UTF-16 output of GetUserName

Test UTF-16 output of GetUserName


/**
 * \file bs_log_scribers.cpp
 * \brief
 * \author Sergey Miryanov
 * \date 07.07.2009
 * */
#include "bs_log_scribers.h"

using namespace std;

namespace blue_sky {
namespace log {
namespace detail {

	void cout_scriber::write(const std::string &str) const {
//#ifdef _DEBUG
    // TODO: miryanov
    static bool is_buffer_installed = false;
    if (!is_buffer_installed)
      {
        static char cout_buffer [2*4096] = {0};
        cout.rdbuf ()->pubsetbuf (cout_buffer, sizeof (cout_buffer));
        is_buffer_installed = true;
      }

    cout << str.c_str ();
//#endif
	}

	file_scriber::file_scriber(const std::string &filename, ios_base::openmode mode)
		: file(new fstream(filename.c_str(),mode))
	{}

	//file_scriber::~file_scriber() {
	//	file.lock()->close();
	//}

	void file_scriber::write(const std::string &str) const {
#ifdef _DEBUG
    // TODO: miryanov
		*(file.lock()) << str;
#endif
	}

} // namespace detail
} // namespace log
} // namespace blue_sky

/**
 * \file bs_log_scribers.cpp
 * \brief
 * \author Sergey Miryanov
 * \date 07.07.2009
 * */
#include "bs_log_scribers.h"

using namespace std;

namespace blue_sky {
namespace log {
namespace detail {

	void cout_scriber::write(const std::string &str) const {
#ifndef _DEBUG
    static bool is_buffer_installed = false;
    if (!is_buffer_installed)
      {
        static char cout_buffer [2*4096] = {0};
        cout.rdbuf ()->pubsetbuf (cout_buffer, sizeof (cout_buffer));
        is_buffer_installed = true;
      }
#endif

    cout << str.c_str ();
	}

	file_scriber::file_scriber(const std::string &filename, ios_base::openmode mode)
		: file(new fstream(filename.c_str(),mode))
	{}

	//file_scriber::~file_scriber() {
	//	file.lock()->close();
	//}

	void file_scriber::write(const std::string &str) const {
#ifdef _DEBUG
    // TODO: miryanov
		*(file.lock()) << str;
#endif
	}

} // namespace detail
} // namespace log
} // namespace blue_sky

Edit: Enable output buffer in log only for Release


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

#include "prng_user.hpp"

PrngUser::PrngUser(std::shared_ptr<std::mt19937> generator)
: generator_{generator}
{
}

std::shared_ptr<std::mt19937> PrngUser::getGenerator() const
{
  return generator_;
}

void PrngUser::setGenerator(std::shared_ptr<std::mt19937> generator)
{
  generator_ = generator;
}

Add a missing license header

Add a missing license header


#include "net/resolver.h"
#include <string>
#include <gtest/gtest.h>

using namespace net;

TEST(LookupAddress, Localhost) {
    {
        std::string addr;
        error err = LookupAddress("localhost", &addr);
        EXPECT_EQ(error::nil, err);
        EXPECT_EQ("127.0.0.1", addr);
    }
    {
        std::string addr;
        error err = LookupAddress("127.0.0.1", &addr);
        EXPECT_EQ(error::nil, err);
        EXPECT_EQ("127.0.0.1", addr);
    }
}

TEST(LookupAddress, Nullptr) {
    ASSERT_DEATH({ LookupAddress("localhost", nullptr); }, "");
}

#include "net/resolver.h"
#include <string>
#include <gtest/gtest.h>

using namespace net;

TEST(LookupAddress, Localhost) {
    std::string addr;
    error err = LookupAddress("localhost", &addr);

    EXPECT_EQ(error::nil, err);
    EXPECT_EQ("127.0.0.1", addr);
}

TEST(LookupAddress, LocalIPv4) {
    std::string addr;
    error err = LookupAddress("127.0.0.1", &addr);

    EXPECT_EQ(error::nil, err);
    EXPECT_EQ("127.0.0.1", addr);
}

TEST(LookupAddress, Nullptr) {
    ASSERT_DEATH({ LookupAddress("localhost", nullptr); }, "");
}

Refactor the resolver test code

refactor/test: Refactor the resolver test code


#include <string>
#include <vector>
#include <map>
#include <iostream>

#include <qitype/signature.hpp>

//sample foo function to take the signature from
int foo(int a, int b)
{
  return a + b + 42;
}

int main()
{
  typedef std::map<std::string , std::string> StringMap;
  typedef std::vector<int>                    IntVector;

  StringMap   mymap;
  int         myint;
  std::string mystring;
  IntVector   myvector;

  return 0;
}

#include <string>
#include <vector>
#include <map>
#include <iostream>

#include <qitype/signature.hpp>

//sample foo function to take the signature from
int foo(int a, int b)
{
  return a + b + 42;
}

int main()
{
  typedef std::map<std::string , std::string> StringMap;
  typedef std::vector<int>                    IntVector;

  StringMap   mymap;
//  int         myint;
  std::string mystring;
  IntVector   myvector;

  return 0;
}

Fix unused variable on outdated example

Fix unused variable on outdated example

Change-Id: I9e257c3123b68044b34531cd71837db9a9ef2bc8


/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#include <unordered_map>
#include "unimplemented.hh"
#include "core/sstring.hh"
#include "core/enum.hh"

namespace unimplemented {

static std::unordered_map<cause, bool> _warnings;

std::ostream& operator<<(std::ostream& out, cause c) {
    switch(c) {
        case cause::INDEXES: return out << "INDEXES";
        case cause::LWT: return out << "LWT";
        case cause::PAGING: return out << "PAGING";
        case cause::AUTH: return out << "AUTH";
        case cause::PERMISSIONS: return out << "PERMISSIONS";
        case cause::TRIGGERS: return out << "TRIGGERS";
        case cause::COLLECTIONS: return out << "COLLECTIONS";
        case cause::COUNTERS: return out << "COUNTERS";
        case cause::METRICS: return out << "METRICS";
        case cause::COMPACT_TABLES: return out << "COMPACT_TABLES";
    }
    assert(0);
}

void warn(cause c) {
    auto i = _warnings.find(c);
    if (i == _warnings.end()) {
        _warnings.insert({c, true});
        std::cerr << "WARNING: Not implemented: " << c << std::endl;
    }
}

void fail(cause c) {
    throw std::runtime_error(sprint("Not implemented: %s", c));
}

}

/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#include <unordered_map>
#include "unimplemented.hh"
#include "core/sstring.hh"
#include "core/enum.hh"

namespace unimplemented {

static thread_local std::unordered_map<cause, bool> _warnings;

std::ostream& operator<<(std::ostream& out, cause c) {
    switch(c) {
        case cause::INDEXES: return out << "INDEXES";
        case cause::LWT: return out << "LWT";
        case cause::PAGING: return out << "PAGING";
        case cause::AUTH: return out << "AUTH";
        case cause::PERMISSIONS: return out << "PERMISSIONS";
        case cause::TRIGGERS: return out << "TRIGGERS";
        case cause::COLLECTIONS: return out << "COLLECTIONS";
        case cause::COUNTERS: return out << "COUNTERS";
        case cause::METRICS: return out << "METRICS";
        case cause::COMPACT_TABLES: return out << "COMPACT_TABLES";
    }
    assert(0);
}

void warn(cause c) {
    auto i = _warnings.find(c);
    if (i == _warnings.end()) {
        _warnings.insert({c, true});
        std::cerr << "WARNING: Not implemented: " << c << std::endl;
    }
}

void fail(cause c) {
    throw std::runtime_error(sprint("Not implemented: %s", c));
}

}

Fix warnings map to be thread-local

Fix warnings map to be thread-local

The map is mutated so it should be thread-local. This will make the
warnings printed once per core, but I guess it's not a big deal.


/* localsearch.cpp

   Ian Westrope
   Evolutionary Computation
   Spring 2015

*/

#include <iostream>
#include <cstdlib>

#include "bitHelpers.h"
#include "rand.h"

using namespace std;

int main() {

  cout << "Test makefile" << endl;

}

/* localsearch.cpp

   Ian Westrope
   Evolutionary Computation
   Spring 2015

*/

#include <iostream>
#include <cstdlib>

#include "bitHelpers.h"
#include "rand.h"

using namespace std;

int main( int argc, char* argv[] ) {

  // variables for command line arguments
  int grayFlag = 0;     // Gray code
  int binaryFlag = 0;
  int randomFlag = 0;
  int bitFlag = 0;
  int incFlag = 0;      // increment decrement mutation

  // check if there are the correct number of arguments
  if( argc > 3 || argc < 3 ) {
    cout << "Two arguments required" << endl;
    exit( -1 );
  }

  int arg1 = atoi( argv[1] );
  int arg2 = atoi( argv[2] );

  // get first argument
  if( arg1 == 0 ) {
    grayFlag = 1;
  } else if( arg1 == 1 ) {
    binaryFlag = 1;
  } else {
    cout << "First argument must be a 0 or 1" << endl;
    exit( -1 );
  }

  // get second argument
  if( arg2 == 0 ) {
    randomFlag = 1;
  } else if( arg2 == 1 ) {
    bitFlag = 1;
  } else if( arg2 == 2 ) {
    incFlag = 1;
  } else {
    cout << "Second argument must be a 0, 1, or 2" << endl;
    exit( -1 );
  }

  cout << "Test makefile" << endl;

}

Add command line argument support

Add command line argument support


#include "zg01_fsm.h"

// max time between ZG01 bits, until a new frame is assumed to have started
#define ZG01_MAX_MS  3

// all of the state of the FSM
typedef struct {
    uint8_t *buffer;
    int num_bits;
    int prev_ms;
} fsm_t;

static fsm_t fsm;
static fsm_t *s = &fsm;

// resets the FSM
static void fsm_reset(void)
{
    s->num_bits = 0;
}

void zg01_init(uint8_t buffer[5])
{
    s->buffer = buffer;
    fsm_reset();
}

bool zg01_process(unsigned long ms, uint8_t data)
{
    // check if a new message has started, based on time since previous bit
    if ((ms - s->prev_ms) > ZG01_MAX_MS) {
        fsm_reset();
    }
    s->prev_ms = ms;

    // number of bits received is basically the "state"
    if (s->num_bits < 40) {
        // store it while it fits
        int idx = s->num_bits / 8;
        s->buffer[idx] = (s->buffer[idx] << 1) | data;
        // are we done yet?
        s->num_bits++;
        if (s->num_bits == 40) {
            return true;
        }
    }
    // else do nothing, wait until fsm is reset

    return false;
}

#include "zg01_fsm.h"

// max time between ZG01 bits, until a new frame is assumed to have started
#define ZG01_MAX_MS  3

// all of the state of the FSM
typedef struct {
    uint8_t *buffer;
    int num_bits;
    unsigned long prev_ms;
} fsm_t;

static fsm_t fsm;
static fsm_t *s = &fsm;

// resets the FSM
static void fsm_reset(void)
{
    s->num_bits = 0;
}

void zg01_init(uint8_t buffer[5])
{
    s->buffer = buffer;
    fsm_reset();
}

bool zg01_process(unsigned long ms, uint8_t data)
{
    // check if a new message has started, based on time since previous bit
    if ((ms - s->prev_ms) > ZG01_MAX_MS) {
        fsm_reset();
    }
    s->prev_ms = ms;

    // number of bits received is basically the "state"
    if (s->num_bits < 40) {
        // store it while it fits
        int idx = s->num_bits / 8;
        s->buffer[idx] = (s->buffer[idx] << 1) | data;
        // are we done yet?
        s->num_bits++;
        if (s->num_bits == 40) {
            return true;
        }
    }
    // else do nothing, wait until fsm is reset

    return false;
}

Fix timer overflow on 16-bit int (milliseconds is an unsigned long)


// ===============================
// Slots for long running Library Tasks
// Available under the 3-clause BSD License
// Written by: Kris Moore <kris@pcbsd.org> FEB 2016
// =================================
#include <WebSocket.h>
#define DEBUG 0

// Iohyve Fetch is done
void WebSocket::slotIohyveFetchDone(QString id, int retcode, QString log)
{

}

// Iohyve Fetch has output to read
void WebSocket::slotIohyveFetchProcessOutput(QString output)
{

}

// ===============================
// Slots for long running Library Tasks
// Available under the 3-clause BSD License
// Written by: Kris Moore <kris@pcbsd.org> FEB 2016
// =================================
#include <WebSocket.h>
#define DEBUG 0

// Iohyve Fetch is done
void WebSocket::slotIohyveFetchDone(QString id, int retcode, QString log)
{
  //qDebug() << "Fetch Done" << id << retcode << log;
}

// Iohyve Fetch has output to read
void WebSocket::slotIohyveFetchProcessOutput(QString output)
{
  //qDebug() << "Fetch Do" << output;
}

Add couple of debug statements

Add couple of debug statements


#include <string>
#include "grcrestarter.h"

// Old VB based NeuralNet.
double qtPushGridcoinDiagnosticData(std::string data);
int RestartClient();
bool CheckForUpgrade();
void UpgradeClient();
int DownloadBlocks();
int ReindexWallet();
int CreateRestorePoint();
// While transitioning to dotnet the NeuralNet implementation has been split
// into 3 implementations; Win32 with Qt, Win32 without Qt and the rest.
// After the transition both Win32 implementations can be removed.
namespace Restarter
{
    // Win32 with Qt enabled.
    double PushGridcoinDiagnosticData(std::string data)
    {
        return qtPushGridcoinDiagnosticData(data);
    }

    int RestartGridcoin()
    {
        return RestartClient();
    }

    bool IsUpgradeAvailable()
    {
        return IsUpgradeAvailable();
    }

    void UpgradeClient()
    {
        return UpgradeClient();
    }

    bool DownloadGridcoinBlocks()
    {
        return DownloadBlocks();
    }

    int ReindexGridcoinWallet()
    {
        return ReindexWallet();
    }

    int CreateGridcoinRestorePoint()
    {
        return CreateRestorePoint();
    }
}

#include <string>
#include "grcrestarter.h"

// Old VB based NeuralNet.
double qtPushGridcoinDiagnosticData(std::string data);
int RestartClient();
bool CheckForUpgrade();
void UpgradeClient();
int DownloadBlocks();
int ReindexWallet();
int CreateRestorePoint();
// While transitioning to dotnet the NeuralNet implementation has been split
// into 3 implementations; Win32 with Qt, Win32 without Qt and the rest.
// After the transition both Win32 implementations can be removed.
namespace Restarter
{
    // Win32 with Qt enabled.
    double PushGridcoinDiagnosticData(std::string data)
    {
        return qtPushGridcoinDiagnosticData(data);
    }

    int RestartGridcoin()
    {
        return RestartClient();
    }

    bool IsUpgradeAvailable()
    {
        return IsUpgradeAvailable();
    }

    void UpgradeClient()
    {
        return UpgradeClient();
    }

    int DownloadGridcoinBlocks()
    {
        return DownloadBlocks();
    }

    int ReindexGridcoinWallet()
    {
        return ReindexWallet();
    }

    int CreateGridcoinRestorePoint()
    {
        return CreateRestorePoint();
    }
}

Change invalid signature of DownloadGridcoinBlocks.


/*

This file is part of VROOM.

Copyright (c) 2015-2022, Julien Coupey.
All rights reserved (see LICENSE).

*/

#include "structures/vroom/break.h"
#include "utils/helpers.h"

namespace vroom {

Break::Break(Id id,
             const std::vector<TimeWindow>& tws,
             Duration service,
             const std::string& description)
  : id(id), tws(tws), service(service), description(description) {
  utils::check_tws(tws);
}

bool Break::is_valid_start(Duration time) const {
  bool valid = false;

  for (const auto& tw : tws) {
    if (tw.contains(time)) {
      valid = true;
      break;
    }
  }

  return valid;
}

} // namespace vroom

/*

This file is part of VROOM.

Copyright (c) 2015-2022, Julien Coupey.
All rights reserved (see LICENSE).

*/

#include "structures/vroom/break.h"
#include "utils/helpers.h"

namespace vroom {

Break::Break(Id id,
             const std::vector<TimeWindow>& tws,
             Duration service,
             const std::string& description)
  : id(id),
    tws(tws),
    service(DURATION_FACTOR * service),
    description(description) {
  utils::check_tws(tws);
}

bool Break::is_valid_start(Duration time) const {
  bool valid = false;

  for (const auto& tw : tws) {
    if (tw.contains(time)) {
      valid = true;
      break;
    }
  }

  return valid;
}

} // namespace vroom

Scale internal times for Break objects.

Scale internal times for Break objects.


/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

#include "csv/export.h"

using namespace flint;

namespace {

void usage()
{
	std::cerr << "usage: csv2isd INPUT OUTPUT" << std::endl;
}

} // namespace

int main(int argc, char *argv[])
{
	if (argc == 2) {
		usage();
		if ( std::strcmp(argv[1], "-h") == 0 || std::strcmp(argv[1], "--help") ) {
			return EXIT_SUCCESS;
		} else {
			return EXIT_FAILURE;
		}
	}
	if (argc != 3) {
		usage();
		return EXIT_FAILURE;
	}
	return (ExportIsdFromCsv(argv[1], argv[2])) ? EXIT_SUCCESS : EXIT_FAILURE;
}

/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

#include "csv/export.h"

using namespace flint;

namespace {

void usage()
{
	std::cerr << "usage: csv2isd INPUT OUTPUT" << std::endl;
}

} // namespace

int main(int argc, char *argv[])
{
	if (argc == 2) {
		usage();
		if ( std::strcmp(argv[1], "-h") == 0 || std::strcmp(argv[1], "--help") == 0 ) {
			return EXIT_SUCCESS;
		} else {
			return EXIT_FAILURE;
		}
	}
	if (argc != 3) {
		usage();
		return EXIT_FAILURE;
	}
	return (ExportIsdFromCsv(argv[1], argv[2])) ? EXIT_SUCCESS : EXIT_FAILURE;
}

Fix csv2isd to exit with 0 at --help

Fix csv2isd to exit with 0 at --help


/*
This file is part of Groho, a simulator for inter-planetary travel and warfare.
Copyright (c) 2020 by Kaushik Ghose. Some rights reserved, see LICENSE
*/

#include <exception>
#include <string>

#include "serialize.hpp"

namespace groho {

Serialize::Serialize(
    double dt, const std::vector<NAIFbody>& objects, fs::path path)
{
    if (fs::exists(path)) {
        if (!fs::is_directory(path)) {
            throw std::runtime_error("Output path must be directory");
        }
    } else {
        fs::create_directories(path);
    }

    history.reserve(objects.size());
    for (size_t i = 0; i < objects.size(); i++) {
        auto fname = path / (std::to_string(int(objects[i])) + "-pos.bin");
        history.emplace_back(dt, objects[i], fname);
    }
}

void Serialize::append(const v3d_vec_t& pos)
{
    for (size_t i = 0; i < history.size(); i++) {
        history[i].sample(pos[i]);
    }
}

}

/*
This file is part of Groho, a simulator for inter-planetary travel and warfare.
Copyright (c) 2020 by Kaushik Ghose. Some rights reserved, see LICENSE
*/

#include <exception>
#include <string>

#include "serialize.hpp"

namespace groho {

Serialize::Serialize(
    double dt, const std::vector<NAIFbody>& objects, fs::path path)
{
    if (fs::exists(path)) {
        if (!fs::is_directory(path)) {
            throw std::runtime_error("Output path must be directory");
        }
    } else {
        fs::create_directories(path);
    }

    history.reserve(objects.size());
    for (size_t i = 0; i < objects.size(); i++) {
        auto fname = path / ("pos" + std::to_string(int(objects[i])) + ".bin");
        history.emplace_back(dt, objects[i], fname);
    }
}

void Serialize::append(const v3d_vec_t& pos)
{
    for (size_t i = 0; i < history.size(); i++) {
        history[i].sample(pos[i]);
    }
}

}

Change naming scheme for files

Change naming scheme for files


#include <system/Locale.h>

#if defined(HX_WINDOWS)
#include <windows.h>
#elif defined(HX_LINUX)
#include <stdlib.h>
#include <string.h>
#include <clocale>
#endif

namespace lime {

	std::string* Locale::GetSystemLocale () {

		#if defined(HX_WINDOWS)

		char locale[8];
		int length = GetLocaleInfo (GetSystemDefaultUILanguage (), LOCALE_SISO639LANGNAME, locale, sizeof (locale));
		std::string* result = new std::string (locale);
		return result;

		#elif defined(HX_LINUX)

		const char* locale = getenv ("LANG");

		if (!locale) {

			locale = setlocale (LC_ALL, "");

		}

		if (locale) {

			std::string* result = new std::string (locale);
			return result;

		}

		return 0;

		#else

		return 0;

		#endif

	}

}

#include <system/Locale.h>

#if defined(HX_WINDOWS)
#include <windows.h>
#elif defined(HX_LINUX)
#include <stdlib.h>
#include <string.h>
#include <clocale>
#endif

namespace lime {

	std::string* Locale::GetSystemLocale () {

		#if defined(HX_WINDOWS)

		char language[5] = {0};
		char country[5] = {0};

		GetLocaleInfoA (LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, language, sizeof (language) / sizeof (char));
		GetLocaleInfoA (LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, country, sizeof (country) / sizeof (char));

		std::string* locale = new std::string (std::string (language) + "_" + std::string (country));
		return locale;

		#elif defined(HX_LINUX)

		const char* locale = getenv ("LANG");

		if (!locale) {

			locale = setlocale (LC_ALL, "");

		}

		if (locale) {

			std::string* result = new std::string (locale);
			return result;

		}

		return 0;

		#else

		return 0;

		#endif

	}

}

Update locale handling on Windows

Update locale handling on Windows


// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "unittest/gtest.hpp"

#include "arch/timing.hpp"
#include "concurrency/pmap.hpp"
#include "unittest/unittest_utils.hpp"
#include "utils.hpp"

namespace unittest {

int wait_array[2][10] = { { 1, 1, 2, 3, 5, 13, 20, 30, 40, 8 },
                          { 5, 3, 2, 40, 30, 20, 8, 13, 1, 1 } };

void walk_wait_times(int i) {
    ticks_t t = get_ticks();
    for (int j = 0; j < 10; ++j) {
        nap(wait_array[i][j]);
        const ticks_t t2 = get_ticks();
        const int64_t diff = static_cast<int64_t>(t2) - static_cast<int64_t>(t);
        // Asserts that we're off by less than two milliseconds.
        ASSERT_LT(llabs(diff - wait_array[i][j] * MILLION), 2 * MILLION);
        t = t2;
    }

}

TPTEST(TimerTest, TestApproximateWaitTimes) {
    pmap(2, walk_wait_times);
}

}  // namespace unittest

// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "unittest/gtest.hpp"

#include "arch/timing.hpp"
#include "concurrency/pmap.hpp"
#include "unittest/unittest_utils.hpp"
#include "utils.hpp"

namespace unittest {

int wait_array[2][10] = { { 1, 1, 2, 3, 5, 13, 20, 30, 40, 8 },
                          { 5, 3, 2, 40, 30, 20, 8, 13, 1, 1 } };

void walk_wait_times(int i) {
    ticks_t t = get_ticks();
    for (int j = 0; j < 10; ++j) {
        nap(wait_array[i][j]);
        const ticks_t t2 = get_ticks();
        const int64_t diff = static_cast<int64_t>(t2) - static_cast<int64_t>(t);
        // Asserts that we're off by less than 25% of the sleep time
        // or two milliseconds, whichever is larger.
        ASSERT_LT(llabs(diff - wait_array[i][j] * MILLION), std::max(diff / 4, 2 * MILLION));
        t = t2;
    }

}

TPTEST(TimerTest, TestApproximateWaitTimes) {
    pmap(2, walk_wait_times);
}

}  // namespace unittest

Decrease sensitivity of timer test.

Decrease sensitivity of timer test.


#include <QTest>
#include <QObject>

#include "uritests.h"

// This is all you need to run all the tests
int main(int argc, char *argv[])
{
    URITests test1;
    QTest::qExec(&test1);
}

#include <QTest>
#include <QObject>

#include "uritests.h"

// This is all you need to run all the tests
int main(int argc, char *argv[])
{
    bool fInvalid = false;

    URITests test1;
    if (QTest::qExec(&test1) != 0)
        fInvalid = true;

    return fInvalid;
}

Return !0 when qt tests fail.

Return !0 when qt tests fail.


#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>

#include <vector>

#include "flutter_window.h"
#include "run_loop.h"
#include "window_configuration.h"

int APIENTRY wWinMain(_In_ HINSTANCE instance,
                      _In_opt_ HINSTANCE prev,
                      _In_ wchar_t* command_line,
                      _In_ int show_command) {
  // Attach to console when present (e.g., 'flutter run') or create a
  // new console when running with a debugger.
  if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
    ::AllocConsole();
  }

  RunLoop run_loop;

  flutter::DartProject project(L"data");
#ifndef _DEBUG
  project.SetEngineSwitches({"--disable-dart-asserts"});
#endif

  FlutterWindow window(&run_loop, project);
  Win32Window::Point origin(kFlutterWindowOriginX, kFlutterWindowOriginY);
  Win32Window::Size size(kFlutterWindowWidth, kFlutterWindowHeight);
  if (!window.CreateAndShow(kFlutterWindowTitle, origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

  run_loop.Run();

  return EXIT_SUCCESS;
}

#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>

#include <vector>

#include "flutter_window.h"
#include "run_loop.h"
#include "window_configuration.h"

int APIENTRY wWinMain(_In_ HINSTANCE instance,
                      _In_opt_ HINSTANCE prev,
                      _In_ wchar_t* command_line,
                      _In_ int show_command) {
  // Attach to console when present (e.g., 'flutter run') or create a
  // new console when running with a debugger.
  if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
    ::AllocConsole();
  }

  // Initialize COM, so that it is available for use in the library and/or plugins.
  ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);

  RunLoop run_loop;

  flutter::DartProject project(L"data");
#ifndef _DEBUG
  project.SetEngineSwitches({"--disable-dart-asserts"});
#endif

  FlutterWindow window(&run_loop, project);
  Win32Window::Point origin(kFlutterWindowOriginX, kFlutterWindowOriginY);
  Win32Window::Size size(kFlutterWindowWidth, kFlutterWindowHeight);
  if (!window.CreateAndShow(kFlutterWindowTitle, origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

  run_loop.Run();

  ::CoUninitialize();
  return EXIT_SUCCESS;
}

Update Windows runner from template

Update Windows runner from template

Picks up the recently add CoInitialize fix.


#ifdef _WINDOWS

/*
 * NOTE: Some macros must be defined in project options of Visual Studio.
 *       - _CRT_SECURE_NO_WARNINGS
 *         To use strncpy().
 *       - NOMINMAX
 *         To use std::min(), std::max().
 */

#include <windows.h>

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
	switch (ul_reason_for_call) {
	case DLL_PROCESS_ATTACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}

#endif

#ifdef _WINDOWS

/*
 * NOTE: Some macros must be defined in project options of Visual Studio.
 *       - _CRT_SECURE_NO_WARNINGS
 *         To use strncpy().
 *       - NOMINMAX
 *         To use std::min(), std::max().
 * NOTE: Suppress some warnings of Visual Studio.
 *       - C4251
 */

#include <windows.h>

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
	switch (ul_reason_for_call) {
	case DLL_PROCESS_ATTACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}

#endif

Add comment about suppress the warning C4251 of Visual Studio.


// Copyright (c) 2011 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 "content/shell/shell_content_client.h"

#include "base/string_piece.h"

namespace content {

ShellContentClient::~ShellContentClient() {
}

void ShellContentClient::SetActiveURL(const GURL& url) {
}

void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) {
}

void ShellContentClient::AddPepperPlugins(
    std::vector<PepperPluginInfo>* plugins) {
}

bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) {
  return false;
}

bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) {
  return false;
}

std::string ShellContentClient::GetUserAgent(bool mimic_windows) const {
  return std::string();
}

string16 ShellContentClient::GetLocalizedString(int message_id) const {
  return string16();
}

base::StringPiece ShellContentClient::GetDataResource(int resource_id) const {
  return base::StringPiece();
}

#if defined(OS_WIN)
bool ShellContentClient::SandboxPlugin(CommandLine* command_line,
                                       sandbox::TargetPolicy* policy) {
  return false;
}
#endif

}  // namespace content

// Copyright (c) 2011 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 "content/shell/shell_content_client.h"

#include "base/string_piece.h"
#include "webkit/glue/user_agent.h"

namespace content {

ShellContentClient::~ShellContentClient() {
}

void ShellContentClient::SetActiveURL(const GURL& url) {
}

void ShellContentClient::SetGpuInfo(const GPUInfo& gpu_info) {
}

void ShellContentClient::AddPepperPlugins(
    std::vector<PepperPluginInfo>* plugins) {
}

bool ShellContentClient::CanSendWhileSwappedOut(const IPC::Message* msg) {
  return false;
}

bool ShellContentClient::CanHandleWhileSwappedOut(const IPC::Message& msg) {
  return false;
}

std::string ShellContentClient::GetUserAgent(bool mimic_windows) const {
  return webkit_glue::BuildUserAgentHelper(mimic_windows, "Chrome/15.16.17.18");
}

string16 ShellContentClient::GetLocalizedString(int message_id) const {
  return string16();
}

base::StringPiece ShellContentClient::GetDataResource(int resource_id) const {
  return base::StringPiece();
}

#if defined(OS_WIN)
bool ShellContentClient::SandboxPlugin(CommandLine* command_line,
                                       sandbox::TargetPolicy* policy) {
  return false;
}
#endif

}  // namespace content

Use Chrome's user agent string for content_shell, since some sites (i.e. Gmail) give a degraded experience otherwise.

BUG=90445
Review URL: http://codereview.chromium.org/7980044

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@102172 0039d316-1c4b-4281-b951-d872f2087c98


#include "pdfium_ruby.h"

void Init_pdfium_ruby (void) {
  VALUE rb_PDFium = rb_define_module("PDFium");

  // Define `Document` and `Page` classes
  Define_Document();
  Define_Page();
  Define_PageSet();
}

#include "pdfium_ruby.h"

extern "C"
void Init_pdfium_ruby (void) {
  // Define `PDFium` module as a namespace for all of our other objects
  VALUE rb_PDFium = rb_define_module("PDFium");

  // Define `Document` and `Page` classes
  Define_Document();
  //Define_Page();
  //Define_PageSet();
}

Fix main file's init function for C++, and comment out unimplemented functions.


// Copyright (c) 2016-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <bench/bench.h>
#include <bench/data.h>

#include <rpc/blockchain.h>
#include <streams.h>
#include <test/util/setup_common.h>
#include <validation.h>

#include <univalue.h>

static void BlockToJsonVerbose(benchmark::Bench& bench)
{
    TestingSetup test_setup{};

    CDataStream stream(benchmark::data::block413567, SER_NETWORK, PROTOCOL_VERSION);
    char a = '\0';
    stream.write(&a, 1); // Prevent compaction

    CBlock block;
    stream >> block;

    CBlockIndex blockindex;
    const uint256 blockHash = block.GetHash();
    blockindex.phashBlock = &blockHash;
    blockindex.nBits = 403014710;

    bench.run([&] {
        (void)blockToJSON(block, &blockindex, &blockindex, /*verbose*/ true);
    });
}

BENCHMARK(BlockToJsonVerbose);

// Copyright (c) 2016-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <bench/bench.h>
#include <bench/data.h>

#include <rpc/blockchain.h>
#include <streams.h>
#include <test/util/setup_common.h>
#include <validation.h>

#include <univalue.h>

namespace {

struct TestBlockAndIndex {
    TestingSetup test_setup{};
    CBlock block{};
    uint256 blockHash{};
    CBlockIndex blockindex{};

    TestBlockAndIndex()
    {
        CDataStream stream(benchmark::data::block413567, SER_NETWORK, PROTOCOL_VERSION);
        char a = '\0';
        stream.write(&a, 1); // Prevent compaction

        stream >> block;

        blockHash = block.GetHash();
        blockindex.phashBlock = &blockHash;
        blockindex.nBits = 403014710;
    }
};

} // namespace

static void BlockToJsonVerbose(benchmark::Bench& bench)
{
    TestBlockAndIndex data;
    bench.run([&] {
        auto univalue = blockToJSON(data.block, &data.blockindex, &data.blockindex, /*verbose*/ true);
        ankerl::nanobench::doNotOptimizeAway(univalue);
    });
}

BENCHMARK(BlockToJsonVerbose);

static void BlockToJsonVerboseWrite(benchmark::Bench& bench)
{
    TestBlockAndIndex data;
    auto univalue = blockToJSON(data.block, &data.blockindex, &data.blockindex, /*verbose*/ true);
    bench.run([&] {
        auto str = univalue.write();
        ankerl::nanobench::doNotOptimizeAway(str);
    });
}

BENCHMARK(BlockToJsonVerboseWrite);

Add benchmark to write JSON into a string

The benchmark BlockToJsonVerbose only tests generating (and destroying)
the JSON data structure, but serializing into a string is also a
performance critical aspect of the RPC calls.

Also, use ankerl::nanobench::doNotOptimizeAway to make sure the compiler
can't optimize the result of the calls away.


#include "theme-loader.h"
#include <QApplication>
#include <QDir>
#include <QFile>

ThemeLoader::ThemeLoader(QString path, QObject *parent)
	: QObject(parent), m_path(std::move(path))
{
	connect(&m_watcher, &QFileSystemWatcher::fileChanged, this, &ThemeLoader::themeFileChanged);
}

QStringList ThemeLoader::getAllThemes() const
{
	return QDir(m_path).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
}

bool ThemeLoader::setTheme(const QString &name)
{
	const QString dir = QString(m_path).replace('\\', '/') + name + "/";
	const QString cssFile = dir + "style.css";

	QFile f(cssFile);
	if (!f.open(QFile::ReadOnly | QFile::Text)) {
		return false;
	}

	QString css = f.readAll();
	f.close();

	// Replace urls relative paths by absolute ones
	css.replace("url(", "url(" + dir);

	// Update watcher if necessary
	if (m_currentTheme != name) {
		m_currentTheme = name;

		m_watcher.removePaths(m_watcher.files());
		m_watcher.addPath(cssFile);
	}

	qApp->setStyleSheet(css);
	return true;
}

void ThemeLoader::themeFileChanged()
{
	setTheme(m_currentTheme);
}

#include "theme-loader.h"
#include <QApplication>
#include <QDir>
#include <QFile>

ThemeLoader::ThemeLoader(QString path, QObject *parent)
	: QObject(parent), m_path(std::move(path))
{
	connect(&m_watcher, &QFileSystemWatcher::fileChanged, this, &ThemeLoader::themeFileChanged);
}

QStringList ThemeLoader::getAllThemes() const
{
	return QDir(m_path).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
}

bool ThemeLoader::setTheme(const QString &name)
{
	const QString dir = QString(m_path).replace('\\', '/') + name + "/";
	const QString cssFile = dir + "style.css";

	QFile f(cssFile);
	if (!f.open(QFile::ReadOnly | QFile::Text)) {
		return false;
	}

	QString css = f.readAll();
	f.close();

	// Replace urls relative paths by absolute ones
	css.replace("url(", "url(" + dir);

	// Update watcher if necessary
	if (m_currentTheme != name) {
		m_currentTheme = name;

		if (!m_watcher.files().isEmpty()) {
			m_watcher.removePaths(m_watcher.files());
		}
		m_watcher.addPath(cssFile);
	}

	qApp->setStyleSheet(css);
	return true;
}

void ThemeLoader::themeFileChanged()
{
	setTheme(m_currentTheme);
}

Fix warning on startup from theme watcher


#include "Rndm.h"

using namespace std;
Rndm::Rndm() : _mt(_rd())
{
}

Rndm & Rndm::rndm()
{
	static Rndm rndm;
	return rndm;
}

std::mt19937 & Rndm::mt()
{
	return Rndm::rndm()._mt;
}

int Rndm::number(int from, int to)
{
	uniform_int_distribution<int> num(from, to);
	return num(Rndm::mt());
}

#include "Rndm.h"

Rndm::Rndm() : _mt(_rd())
{
}

Rndm & Rndm::rndm()
{
	static Rndm rndm;
	return rndm;
}

std::mt19937 & Rndm::mt()
{
	return Rndm::rndm()._mt;
}

int Rndm::number(int from, int to)
{
	std::uniform_int_distribution<int> num(from, to);
	return num(Rndm::mt());
}

Remove use of std namespace

Remove use of std namespace


// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/node_debugger.h"

#include "base/command_line.h"
#include "libplatform/libplatform.h"

namespace atom {

NodeDebugger::NodeDebugger(node::Environment* env) : env_(env) {
}

NodeDebugger::~NodeDebugger() {
}

void NodeDebugger::Start() {
  auto inspector = env_->inspector_agent();
  if (inspector == nullptr)
    return;

  node::DebugOptions options;
  for (auto& arg : base::CommandLine::ForCurrentProcess()->argv())
    options.ParseOption(arg);

  if (options.inspector_enabled()) {
    // Use custom platform since the gin platform does not work correctly
    // with node's inspector agent
    platform_.reset(v8::platform::CreateDefaultPlatform());

    inspector->Start(platform_.get(), nullptr, options);
  }
}

}  // namespace atom

// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/node_debugger.h"

#include "base/command_line.h"
#include "base/strings/utf_string_conversions.h"
#include "libplatform/libplatform.h"

namespace atom {

NodeDebugger::NodeDebugger(node::Environment* env) : env_(env) {
}

NodeDebugger::~NodeDebugger() {
}

void NodeDebugger::Start() {
  auto inspector = env_->inspector_agent();
  if (inspector == nullptr)
    return;

  node::DebugOptions options;
  for (auto& arg : base::CommandLine::ForCurrentProcess()->argv()) {
#if defined(OS_WIN)
    options.ParseOption(base::UTF16ToUTF8(arg));
#else
    options.ParseOption(arg);
#endif
  }

  if (options.inspector_enabled()) {
    // Use custom platform since the gin platform does not work correctly
    // with node's inspector agent
    platform_.reset(v8::platform::CreateDefaultPlatform());

    inspector->Start(platform_.get(), nullptr, options);
  }
}

}  // namespace atom

Convert arg string to utf8 on Windows

Convert arg string to utf8 on Windows


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cms.h>

////////////////////////////////////////////////////////////////////////////////
void cms_initialize() {

}

////////////////////////////////////////////////////////////////////////////////
void cms_terminate() {

}

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cms.h>

#include <activemq/library/ActiveMQCPP.h>

////////////////////////////////////////////////////////////////////////////////
void cms_initialize() {
    activemq::library::ActiveMQCPP::initializeLibrary();
}

////////////////////////////////////////////////////////////////////////////////
void cms_terminate() {
    activemq::library::ActiveMQCPP::shutdownLibrary();
}

Add the code to init the ActiveMQ-CPP library and shut it down when finished.

git-svn-id: 0fb8a5a922afe2085ae9a967a0cf0864fe09ecff@1005248 13f79535-47bb-0310-9956-ffa450edef68


#include "threadpool.h"

ThreadPool::ThreadPool(size_t size)
{
    for (auto i=0; i<size; ++i) {
        workers.emplace_back([this] {
            for (;;) {
                std::unique_lock<std::mutex> lock(this->queue_mutex);
                while (!this->m_stop && this->tasks.empty())
                    this->condition.wait(lock);

                if (this->m_stop && this->tasks.empty())
                    return;

                std::function<void()> task(this->tasks.front());
                this->tasks.pop();
                lock.unlock();
                task();
            }
        });
    }
}

ThreadPool::~ThreadPool()
{
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        m_stop = true;
    }

    condition.notify_all();

    for (auto i=0; i<workers.size(); ++i)
        workers[i].join();
}

#include "threadpool.h"

ThreadPool::ThreadPool(size_t size)
{
    for (size_t i=0; i<size; ++i) {
        workers.emplace_back([this] {
            for (;;) {
                std::unique_lock<std::mutex> lock(this->queue_mutex);
                while (!this->m_stop && this->tasks.empty())
                    this->condition.wait(lock);

                if (this->m_stop && this->tasks.empty())
                    return;

                std::function<void()> task(this->tasks.front());
                this->tasks.pop();
                lock.unlock();
                task();
            }
        });
    }
}

ThreadPool::~ThreadPool()
{
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        m_stop = true;
    }

    condition.notify_all();

    for (auto i=0; i<workers.size(); ++i)
        workers[i].join();
}

Fix compilation warning caused by use of "auto"


#include "Sensor/UltrasoundSensor.h"
#include "Data/UltrasoundData.h"

UltrasoundSensor::UltrasoundSensor(string port, int baudrate) : Sensor("Ultrasound Sensor"), conn(std::make_shared<SerialPort>(port, baudrate)) {
}

UltrasoundSensor::~UltrasoundSensor() {
}

bool UltrasoundSensor::ping() {
	return conn->isConnected() == 1;
}

void UltrasoundSensor::fillData(SensorData& sensorData) {
	if (conn->isConnected()) {
		char data[256];
		int bytesRead = conn->read(data, 256);

		// Decode the incoming data
		R2Protocol::Packet params;
		std::vector<uint8_t> input(data, data + bytesRead);
		int32_t read;
		ptr<UltrasoundData> udata = std::make_shared<UltrasoundData>();
		while ((read = R2Protocol::decode(input, params)) >= 0) {
			if (params.source == "U1SENSOR") {
				udata->distance = std::atof((char *) params.data.data());
			}
			std::vector<uint8_t>(input.begin() + read, input.end()).swap(input);
		}
		sensorData["ULTRASOUND"] = udata;
		printf("Ultrasound: %f\n", udata->distance);
	}
}

#include "Sensor/UltrasoundSensor.h"
#include "Data/UltrasoundData.h"

UltrasoundSensor::UltrasoundSensor(string port, int baudrate) : Sensor("Ultrasound Sensor"), conn(std::make_shared<SerialPort>(port, baudrate)) {
}

UltrasoundSensor::~UltrasoundSensor() {
}

bool UltrasoundSensor::ping() {
	return conn->isConnected() == 1;
}

void UltrasoundSensor::fillData(SensorData& sensorData) {
	if (conn->isConnected()) {
		char data[256];
		int bytesRead = conn->read(data, 256);
		if (bytesRead <= 0) {
			return;
		}

		// Decode the incoming data
		R2Protocol::Packet params;
		std::vector<uint8_t> input(data, data + bytesRead);
		int32_t read;
		ptr<UltrasoundData> udata = std::make_shared<UltrasoundData>();
		while ((read = R2Protocol::decode(input, params)) >= 0) {
			if (params.source == "U1SENSOR") {
				udata->distance = std::atof((char *) params.data.data());
			}
			std::vector<uint8_t> newinput(input.begin() + read, input.end());
			newinput.swap(input);
		}
		sensorData["ULTRASOUND"] = udata;
		printf("Ultrasound: %f\n", udata->distance);
	}
}

Add check in ultrasound sensor when reading from the serial port


/*
 * File.cpp
 *
 *  Created on: Jun 24, 2015
 *      Author: gatanasov
 */

#include "File.h"
#include <sstream>

using namespace std;

namespace tns
{
	string File::ReadText(const string& filePath)
	{
		int len;
		bool isNew;
		const char *content = ReadText(filePath, len, isNew);

		string s(content, len);

		if(isNew)
		{
			delete[] content;
		}

		return s;
	}

	const char* File::ReadText(const string& filePath, int& charLength, bool& isNew)
	{
		FILE *file = fopen(filePath.c_str(), "rb");
		fseek(file, 0, SEEK_END);
		int len = ftell(file);

		if(charLength)
		{
			charLength = len;
		}

		bool exceedBuffer = len > BUFFER_SIZE;
		if(isNew)
		{
			isNew = exceedBuffer;
		}

		rewind(file);

		if(exceedBuffer)
		{
			char* newBuffer = new char[len];
			fread(newBuffer, 1, len, file);
			fclose(file);

			return newBuffer;
		}

		fread(Buffer, 1, len, file);
		fclose(file);

		return Buffer;
	}

	char* File::Buffer = new char[BUFFER_SIZE];
}

/*
 * File.cpp
 *
 *  Created on: Jun 24, 2015
 *      Author: gatanasov
 */

#include "File.h"
#include <sstream>

using namespace std;

namespace tns
{
	string File::ReadText(const string& filePath)
	{
		int len;
		bool isNew;
		const char *content = ReadText(filePath, len, isNew);

		string s(content, len);

		if(isNew)
		{
			delete[] content;
		}

		return s;
	}

	const char* File::ReadText(const string& filePath, int& charLength, bool& isNew)
	{
		FILE *file = fopen(filePath.c_str(), "rb");
		fseek(file, 0, SEEK_END);

		charLength = ftell(file);
		isNew = charLength > BUFFER_SIZE;

		rewind(file);

		if(isNew)
		{
			char* newBuffer = new char[charLength];
			fread(newBuffer, 1, charLength, file);
			fclose(file);

			return newBuffer;
		}

		fread(Buffer, 1, charLength, file);
		fclose(file);

		return Buffer;
	}

	char* File::Buffer = new char[BUFFER_SIZE];
}

Remove erroneous check for reference params.


#include <memory>

#include <miniMAT/checker/Checker.hpp>

#include <iostream>

namespace miniMAT {
    namespace checker {
        Checker::Checker(std::shared_ptr<std::map<std::string, Matrix>> vars,
                         std::shared_ptr<reporter::ErrorReporter> reporter) {
            this->vars = vars;
            this->reporter = reporter;
        }

        std::shared_ptr<ast::AST> Checker::check(std::shared_ptr<ast::AST> ast) {
            try {
                ast->VisitCheck(this->vars, this->reporter);
                return ast;
            } catch (std::string error) {
                reporter->AddCheckError(error);
                return nullptr;
            }
        }
    }
}

#include <memory>

#include <miniMAT/checker/Checker.hpp>

#include <iostream>

namespace miniMAT {
    namespace checker {
        Checker::Checker(std::shared_ptr<std::map<std::string, Matrix>> vars,
                         std::shared_ptr<reporter::ErrorReporter> reporter) {
            this->vars = vars;
            this->reporter = reporter;
        }

        std::shared_ptr<ast::AST> Checker::check(std::shared_ptr<ast::AST> ast) {
            try {
                ast->VisitCheck(this->vars, this->reporter);
                return ast;
            } catch (std::string& error) {
                reporter->AddCheckError(error);
                return nullptr;
            }
        }
    }
}

Change catch statement to catch by reference


#include <iostream>

#include "server.h"

Server::Server(unsigned short port) {
	// logging settings
	bottleserve.set_access_channels(websocketpp::log::alevel::all);
	bottleserve.clear_access_channels(websocketpp::log::alevel::frame_payload);

	bottleserve.init_asio();

	bottleserve.set_message_handler([this] (websocketpp::connection_hdl hdl, message_ptr msg) {
		bottleserve.send(hdl, msg->get_payload(), msg->get_opcode());
        std::cout << msg->get_raw_payload() << std::endl;
	});

	bottleserve.listen(port);
}

void Server::run() {
	bottleserve.start_accept();

	bottleserve.run();
}

#include <iostream>
#include <sstream>

#include "server.h"

using namespace std;

/*
 * Splits a string based on a delimiter character
 *
 * Won't split into more than 'max' strings. Returns the number of strings that were added
 */
template<typename Iter>
size_t split(const string& str, char val, size_t max, Iter out) {
    stringstream ss(str);
    string s;
    size_t len = 0;

    // I love the "goes to" operator (-->)
    while( max --> 0 ) {
        if(!getline(ss, s, max ? val : '\0')) {
            return len;
        }
        len++;
        *out++ = s;
    }
    return len;
}

bool valid_user(const string& user, const string& pass) {
    // TODO: Actually check the username and password here
    return user == "anon" || (user == "corny" && pass == "1234");
}

Server::Server(unsigned short port) {
    // logging settings
    bottleserve.set_access_channels(websocketpp::log::alevel::all);
    bottleserve.clear_access_channels(websocketpp::log::alevel::frame_payload);

    bottleserve.init_asio();

    bottleserve.set_message_handler([this] (websocketpp::connection_hdl hdl, message_ptr msg) {
        using namespace websocketpp;
        if(msg->get_opcode() != frame::opcode::text) {
            bottleserve.close(hdl, close::status::unsupported_data, "Only text data allowed");
            return;
        }
        const auto & line = msg->get_payload();

        array<string,3> login;
        if(login.size() != split(line, ' ', login.size(), login.begin())
           || login[0] != "login"
           || !valid_user(login[1], login[2])) {
            bottleserve.close(hdl, close::status::unsupported_data, "Invalid login");
            return;
        }

        // TODO: Create a connection

        bottleserve.send(hdl, msg->get_payload(), msg->get_opcode());
        cout << msg->get_opcode() << endl;
        cout << msg->get_raw_payload() << endl;
    });

    bottleserve.listen(port);
}

void Server::run() {
    bottleserve.start_accept();

    bottleserve.run();
}

Add a simple login feature

Add a simple login feature


// RUN: %clang_cc1 -fsyntax-only -std=c++0x -Wc++98-compat -verify %s

template<typename ...T>  // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic1 {};

template<template<typename> class ...T>  // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic2 {};

template<int ...I>  // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic3 {};

// RUN: %clang_cc1 -fsyntax-only -std=c++11 -Wc++98-compat -verify %s

template<typename ...T>  // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic1 {};

template<template<typename> class ...T>  // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic2 {};

template<int ...I>  // expected-warning {{variadic templates are incompatible with C++98}}
class Variadic3 {};

Convert newly-added test from -std=c++0x to -std=c++11.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@141904 91177308-0d34-0410-b5e6-96231b3b80d8


#include "libbbn-ni-r.h"

//global to hold on to session handle
NiFpga_Session session;
bool isOpen = false;

//Initialize FPGA on loading the library -- constructor hook in header
void init() {
  NiFpga_Status status = NiFpga_Initialize();
}

//Cleanup NI library -- destructor hook in header
void cleanup(){
  if (isOpen) {NiFpga_Close(session, 0);};
  NiFpga_Finalize();
}

BBN_NI_R_STATUS open_load_run(){
  NiFpga_Status status = NiFpga_Open(NiFpga_SimpleDigitizer_VI_Bitfile,
                                      NiFpga_SimpleDigitizer_VI_Signature,
                                      "RIO0", 0, &session);
  if (status == NiFpga_Status_Success){
    isOpen = true;
  }
  return status;
}

BBN_NI_R_STATUS set_numSamples(unsigned numSamples){
  return 0;
};
BBN_NI_R_STATUS get_numSamples(unsigned* numSamples){
  return 0;
};

BBN_NI_R_STATUS set_sampleInterval(unsigned sampleInterval){
  return 0;
};
BBN_NI_R_STATUS get_sampleInterval(unsigned* sampleInterval){
  return 0;
};

#include "libbbn-ni-r.h"

//global to hold on to session handle
NiFpga_Session session;
bool isOpen = false;

//Initialize FPGA on loading the library -- constructor hook in header
void init() {
  NiFpga_Status status = NiFpga_Initialize();
}

//Cleanup NI library -- destructor hook in header
void cleanup(){
  if (isOpen) {NiFpga_Close(session, 0);};
  NiFpga_Finalize();
}

BBN_NI_R_STATUS open_load_run(){
  NiFpga_Status status = NiFpga_Open("../" NiFpga_SimpleDigitizer_VI_Bitfile,
                                      NiFpga_SimpleDigitizer_VI_Signature,
                                      "RIO0", 0, &session);
  if (status == NiFpga_Status_Success){
    isOpen = true;
  }
  return status;
}

BBN_NI_R_STATUS set_numSamples(unsigned numSamples){
  return 0;
};
BBN_NI_R_STATUS get_numSamples(unsigned* numSamples){
  return 0;
};

BBN_NI_R_STATUS set_sampleInterval(unsigned sampleInterval){
  return 0;
};
BBN_NI_R_STATUS get_sampleInterval(unsigned* sampleInterval){
  return 0;
};

Fix relative location of bitfile

Fix relative location of bitfile


#include "PlainPrinter.h"

PlainPrinterAction::PlainPrinterAction(const llvm::StringRef &filename) :
  ASTAction<PlainPrinterAction>() {
  OutputFile = std::make_shared<std::fstream>();
  OutputFile->open(filename, std::fstream::out);
}

PlainPrinterAction::~PlainPrinterAction() {
  OutputFile->close();
}

std::fstream &PlainPrinterAction::getStream() {
  return *OutputFile;
}

PlainPrinterAction::PlainPrinterAction(const PlainPrinterAction &action) :
  ASTAction<PlainPrinterAction>(), OutputFile(action.OutputFile) { }

#include "PlainPrinter.h"

PlainPrinterAction::PlainPrinterAction(const llvm::StringRef &filename) :
  ASTAction<PlainPrinterAction>(),
  OutputFile(std::make_shared<std::fstream>()) {
  OutputFile->open(filename, std::fstream::out);
}

PlainPrinterAction::~PlainPrinterAction() {
  OutputFile->close();
}

std::fstream &PlainPrinterAction::getStream() {
  return *OutputFile;
}

PlainPrinterAction::PlainPrinterAction(const PlainPrinterAction &action) :
  ASTAction<PlainPrinterAction>(), OutputFile(action.OutputFile) { }

Change constructor to set OutputFile.

Change constructor to set OutputFile.


#include <ncurses.h>

#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../vick-move/src/move.hh"

void enter_insert_mode(contents& contents, boost::optional<int>) {
    char ch;
    while((ch = getch()) != _escape) {
        contents.cont[contents.y].insert(contents.x, 1, ch);
        mvf(contents);
        if(get_contents().refresh) {
            print_contents(get_contents());
        }
    }
}

void enter_replace_mode(contents& contents, boost::optional<int>) {
    char ch;
    while((ch = getch()) != _escape) {
        if(contents.x >= contents.cont[contents.y].size()) {
            contents.cont[contents.y].push_back(ch);
        } else {
            contents.cont[contents.y][contents.x] = ch;
        }
        if(get_contents().refresh) {
            print_contents(get_contents());
        }
    }
}

#include <ncurses.h>

#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../vick-move/src/move.hh"

void enter_insert_mode(contents& contents, boost::optional<int>) {
    char ch;
    contents.is_inserting = true;
    while((ch = getch()) != _escape) {
        contents.cont[contents.y].insert(contents.x, 1, ch);
        mvf(contents);
        if(get_contents().refresh) {
            print_contents(get_contents());
        }
    }
    contents.is_inserting = false;
}

void enter_replace_mode(contents& contents, boost::optional<int>) {
    char ch;
    contents.is_inserting = true;
    while((ch = getch()) != _escape) {
        if(contents.x >= contents.cont[contents.y].size()) {
            contents.cont[contents.y].push_back(ch);
        } else {
            contents.cont[contents.y][contents.x] = ch;
        }
        if(get_contents().refresh) {
            print_contents(get_contents());
        }
    }
    contents.is_inserting = false;
}

Edit ``contents.is_inserting`` in insert modes


#include "wvtftps.h"

int main()
{
    WvTFTPs tftps("/tftpboot", 30*1000);

    while (tftps.isok())
    {
	if (tftps.select(0))
	    tftps.callback();
    }
    wvcon->print("TFTPs is not okay; aborting.\n");
}

#include "wvtftps.h"

int main()
{
    WvTFTPs tftps("/tftpboot", 30, 30);

    while (tftps.isok())
    {
	if (tftps.select(0))
	    tftps.callback();
    }
    wvcon->print("TFTPs is not okay; aborting.\n");
}

Support for blksize option (RFC 2348).

Support for blksize option (RFC 2348).

git-svn-id: 4a4e6d3f3969003d0af9593019da3e8c357e24a8@300 6619c942-59fa-0310-bf43-a07aaa81d9ac


//===-- ManagedStatic.cpp - Static Global wrapper -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the ManagedStatic class and llvm_shutdown().
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/ManagedStatic.h"
#include <cassert>
using namespace llvm;

static const ManagedStaticBase *StaticList = 0;

void ManagedStaticBase::RegisterManagedStatic(void *ObjPtr,
                                              void (*Deleter)(void*)) const {
  assert(Ptr == 0 && DeleterFn == 0 && Next == 0 &&
         "Partially init static?");
  Ptr = ObjPtr;
  DeleterFn = Deleter;

  // Add to list of managed statics.
  Next = StaticList;
  StaticList = this;
}

void ManagedStaticBase::destroy() const {
  assert(Ptr && DeleterFn && "ManagedStatic not initialized correctly!");
  assert(StaticList == this &&
         "Not destroyed in reverse order of construction?");
  // Unlink from list.
  StaticList = Next;
  Next = 0;

  // Destroy memory.
  DeleterFn(Ptr);

  // Cleanup.
  Ptr = 0;
  DeleterFn = 0;
}

/// llvm_shutdown - Deallocate and destroy all ManagedStatic variables.
void llvm_shutdown() {
  while (StaticList)
    StaticList->destroy();
}

//===-- ManagedStatic.cpp - Static Global wrapper -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the ManagedStatic class and llvm_shutdown().
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/ManagedStatic.h"
#include <cassert>
using namespace llvm;

static const ManagedStaticBase *StaticList = 0;

void ManagedStaticBase::RegisterManagedStatic(void *ObjPtr,
                                              void (*Deleter)(void*)) const {
  assert(Ptr == 0 && DeleterFn == 0 && Next == 0 &&
         "Partially init static?");
  Ptr = ObjPtr;
  DeleterFn = Deleter;

  // Add to list of managed statics.
  Next = StaticList;
  StaticList = this;
}

void ManagedStaticBase::destroy() const {
  assert(Ptr && DeleterFn && "ManagedStatic not initialized correctly!");
  assert(StaticList == this &&
         "Not destroyed in reverse order of construction?");
  // Unlink from list.
  StaticList = Next;
  Next = 0;

  // Destroy memory.
  DeleterFn(Ptr);

  // Cleanup.
  Ptr = 0;
  DeleterFn = 0;
}

/// llvm_shutdown - Deallocate and destroy all ManagedStatic variables.
void llvm::llvm_shutdown() {
  while (StaticList)
    StaticList->destroy();
}

Define this in the correct n/s

Define this in the correct n/s

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@30671 91177308-0d34-0410-b5e6-96231b3b80d8


// Formatting library for C++ - Grisu tests
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.

#define FMT_USE_GRISU std::numeric_limits<double>::is_iec559
#include "fmt/format.h"
#include "gtest.h"

bool reported_skipped;

#undef TEST
#define TEST(test_fixture, test_name)        \
  void test_fixture##test_name();            \
  GTEST_TEST(test_fixture, test_name) {      \
    if (FMT_USE_GRISU) {                     \
      test_fixture##test_name();             \
    } else if (!reported_skipped) {          \
      reported_skipped = true;               \
      fmt::print("Skipping Grisu tests.\n"); \
    }                                        \
  }                                          \
  void test_fixture##test_name()

TEST(GrisuTest, NaN) {
  EXPECT_EQ("nan", fmt::format("{}", std::numeric_limits<double>::quiet_NaN()));
}

// Formatting library for C++ - Grisu tests
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.

#define FMT_USE_GRISU std::numeric_limits<double>::is_iec559
#include "fmt/format.h"
#include "gtest.h"

bool reported_skipped;

#undef TEST
#define TEST(test_fixture, test_name)        \
  void test_fixture##test_name();            \
  GTEST_TEST(test_fixture, test_name) {      \
    if (FMT_USE_GRISU) {                     \
      test_fixture##test_name();             \
    } else if (!reported_skipped) {          \
      reported_skipped = true;               \
      fmt::print("Skipping Grisu tests.\n"); \
    }                                        \
  }                                          \
  void test_fixture##test_name()

TEST(GrisuTest, NaN) {
  auto nan = std::numeric_limits<double>::quiet_NaN();
  EXPECT_EQ("nan", fmt::format("{}", nan));
  EXPECT_EQ("-nan", fmt::format("{}", -nan));
}

TEST(GrisuTest, Inf) {
  auto inf = std::numeric_limits<double>::infinity();
  EXPECT_EQ("inf", fmt::format("{}", inf));
  EXPECT_EQ("-inf", fmt::format("{}", -inf));
}

TEST(GrisuTest, Zero) {
  EXPECT_EQ("0", fmt::format("{}", 0.0));
}

Test formatting of special numbers

Test formatting of special numbers


//===-- main.c --------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

template <typename T>
class Foo
{
public:
    Foo () : object() {}
    Foo (T x) : object(x) {}
    T getObject() { return object; }
private:
    T object;
};

int main (int argc, char const *argv[])
{
    Foo<int> foo_x('a');
    Foo<wchar_t> foo_y(L'a');
    const wchar_t *mazeltov = L"מזל טוב";
    wchar_t *ws_NULL = nullptr;
    wchar_t *ws_empty = L"";
  	wchar_t array[200], * array_source = L"Hey, I'm a super wchar_t string, éõñž";
  	memcpy(array, array_source, 39 * sizeof(wchar_t));
    return 0; // Set break point at this line.
}

//===-- main.c --------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include <cstring>

template <typename T>
class Foo
{
public:
    Foo () : object() {}
    Foo (T x) : object(x) {}
    T getObject() { return object; }
private:
    T object;
};

int main (int argc, char const *argv[])
{
    Foo<int> foo_x('a');
    Foo<wchar_t> foo_y(L'a');
    const wchar_t *mazeltov = L"מזל טוב";
    wchar_t *ws_NULL = nullptr;
    wchar_t *ws_empty = L"";
  	wchar_t array[200], * array_source = L"Hey, I'm a super wchar_t string, éõñž";
  	memcpy(array, array_source, 39 * sizeof(wchar_t));
    return 0; // Set break point at this line.
}

Fix compile error in TestCxxWCharT on Linux

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@239830 91177308-0d34-0410-b5e6-96231b3b80d8


#include "Runtime.h"

#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IntrinsicInst.h>

namespace dev
{
namespace eth
{
namespace jit
{

Runtime::Runtime(RuntimeData* _data, Env* _env) :
	m_data(*_data),
	m_env(*_env),
	m_currJmpBuf(m_jmpBuf)
{}

bytes Runtime::getReturnData() const	// FIXME: Reconsider returning by copy
{
	// TODO: Handle large indexes
	auto offset = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataOffset]));
	auto size = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataSize]));

	assert(offset + size <= m_memory.size());
	// TODO: Handle invalid data access by returning empty ref
	auto dataBeg = m_memory.begin() + offset;
	return {dataBeg, dataBeg + size};
}

}
}
}

#include "Runtime.h"

#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IntrinsicInst.h>

namespace dev
{
namespace eth
{
namespace jit
{

Runtime::Runtime(RuntimeData* _data, Env* _env) :
	m_data(*_data),
	m_env(*_env),
	m_currJmpBuf(m_jmpBuf)
{}

bytes Runtime::getReturnData() const	// FIXME: Reconsider returning by copy
{
	// TODO: Handle large indexes
	auto offset = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataOffset]));
	auto size = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataSize]));

	assert(offset + size <= m_memory.size() || size == 0);
	if (offset + size > m_memory.size())
		return {};

	auto dataBeg = m_memory.begin() + offset;
	return {dataBeg, dataBeg + size};
}

}
}
}

Handle return memory of size 0 and large offset


// Test the handle_abort option.

// clang-format off
// RUN: %clangxx %s -o %t
// RUN:                              not --crash %run %t 2>&1 | FileCheck --check-prefix=CHECK0 %s
// RUN: %env_tool_opts=handle_abort=0 not --crash %run %t 2>&1 | FileCheck --check-prefix=CHECK0 %s
// RUN: %env_tool_opts=handle_abort=1 not         %run %t
// RUN: %env_tool_opts=handle_abort=1 not         %run %t 2>&1 | FileCheck --check-prefix=CHECK1 %s
// clang-format on

// FIXME: implement in other sanitizers.
// XFAIL: tsan

#include <assert.h>
#include <stdio.h>
#include <sanitizer/asan_interface.h>

void death() {
  fprintf(stderr, "DEATH CALLBACK\n");
}

int main(int argc, char **argv) {
  __sanitizer_set_death_callback(death);
  assert(argc == 100);
}

// CHECK0-NOT: Sanitizer:DEADLYSIGNAL
// CHECK1: ERROR: {{.*}}Sanitizer: ABRT
// CHECK1: {{#[0-9]+.* main .*assert\.cc}}:[[@LINE-5]]
// CHECK1: DEATH CALLBACK
// CHECK0-NOT: Sanitizer

// Test the handle_abort option.

// clang-format off
// RUN: %clangxx %s -o %t
// RUN:                              not --crash %run %t 2>&1 | FileCheck --check-prefix=CHECK0 %s
// RUN: %env_tool_opts=handle_abort=0 not --crash %run %t 2>&1 | FileCheck --check-prefix=CHECK0 %s
// RUN: %env_tool_opts=handle_abort=1 not         %run %t 2>&1 | FileCheck --check-prefix=CHECK1 %s
// clang-format on

// FIXME: implement in other sanitizers.
// XFAIL: tsan

#include <assert.h>
#include <stdio.h>
#include <sanitizer/asan_interface.h>

void death() {
  fprintf(stderr, "DEATH CALLBACK\n");
}

int main(int argc, char **argv) {
  __sanitizer_set_death_callback(death);
  assert(argc == 100);
}

// CHECK0-NOT: Sanitizer:DEADLYSIGNAL
// CHECK1: ERROR: {{.*}}Sanitizer: ABRT
// CHECK1-NEXT: {{ #0 }}
// CHECK1-NEXT: {{ #1 }}
// CHECK1: DEATH CALLBACK
// CHECK0-NOT: Sanitizer

[sanitizer] Simplify stack check in accert.cc
Somehow on arm bots stack does not include main.

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@318002 91177308-0d34-0410-b5e6-96231b3b80d8


#include <im_str/im_str.hpp>

#include <cstring>
#include <string>
#include <iostream>

int c_api_func(const char* str) {
	return std::strlen( str );
}

int main() {
	using namespace std::string_literals;

	mba::im_str str1 = "Hello ";

	auto greeting = mba::concat( str1, "World"s, "!" );

	std::cout << greeting << std::endl;

	std::cout << greeting.size() << " == " << c_api_func( greeting.c_str() ) << std::endl;
}

#include <im_str/im_str.hpp>

#include <cstring>
#include <string>
#include <iostream>

std::size_t c_api_func(const char* str) {
	return std::strlen( str );
}

int main() {
	using namespace std::string_literals;

	mba::im_str str1 = "Hello ";

	auto greeting = mba::concat( str1, "World"s, "!" );

	std::cout << greeting << std::endl;

	std::cout << greeting.size() << " == " << c_api_func( greeting.c_str() ) << std::endl;
}

Fix return type in c_api_func

[examples] Fix return type in c_api_func


#include "dukbind_validation.h"
#include <regex>

namespace dukbind
{
    namespace validation
    {
        static std::regex identifer_regex( "[a-zA-Z$_][a-zA-Z0-9$_]*" );

        bool IsValidIdentifier( const char * identifier )
        {
            return std::regex_match( identifier, identifer_regex );
        }
    }
}

#include "dukbind_validation.h"
#include <regex>

namespace dukbind
{
    namespace validation
    {
        const std::regex & getIndentifierRegex()
        {
            static std::regex identifer_regex( "[a-zA-Z$_][a-zA-Z0-9$_]*" );

            return identifer_regex;
        }

        bool IsValidIdentifier( const char * identifier )
        {
            return std::regex_match( identifier, getIndentifierRegex() );
        }
    }
}

Fix issue with static order creation

Fix issue with static order creation


#include "session.h"

#include <ncurses.h>

namespace ncurses
{
    std::shared_ptr < Panel > Session::panel;

    void Session::init ()
    {
        // Standard ncurses init methods
        initscr ();
        cbreak ();
        noecho ();
        start_color ();
        use_default_colors ();
        refresh ();

        // Initialize all possible color combinations, using a simple calculation
        // This enables us to change the colors in Window way comfortably than any
        // other solution
        for ( int fg = -1; fg < 8; fg++ )
        {
            for ( int bg = -1; bg < 8; bg++ )
            {
                init_pair ( 2 + fg + 8 * ( 1 + bg ), fg, bg );
            }
        }
    }

    void Session::end ()
    {
        endwin ();
    }

    void Session::update ()
    {
        char input = getch ();
        // This is only temporary
        int max_x, max_y;
        getmaxyx ( stdscr, max_y, max_x );
        std::shared_ptr < Window > window = std::make_shared < Window > ( 0, 0, max_x, max_y );

        if ( panel.get () != nullptr )
        {
            panel->update ( input, window );
        }
    }

    void Session::set_panel ( const std::shared_ptr < Panel >& panel_ )
    {
        panel = panel_;
    }

    std::shared_ptr < Panel > Session::get_panel ()
    {
        return panel;
    }
}

#include "session.h"

#include <ncurses.h>

namespace ncurses
{
    std::shared_ptr < Panel > Session::panel;

    void Session::init ()
    {
        // Standard ncurses init methods
        initscr ();
        // Update every 2.5 seconds
        halfdelay ( 25 );
        noecho ();
        start_color ();
        use_default_colors ();
        refresh ();

        // Initialize all possible color combinations, using a simple calculation
        // This enables us to change the colors in Window way comfortably than any
        // other solution
        for ( int fg = -1; fg < 8; fg++ )
        {
            for ( int bg = -1; bg < 8; bg++ )
            {
                init_pair ( 2 + fg + 8 * ( 1 + bg ), fg, bg );
            }
        }
    }

    void Session::end ()
    {
        endwin ();
    }

    void Session::update ()
    {
        char input = getch ();
        // This is only temporary
        int max_x, max_y;
        getmaxyx ( stdscr, max_y, max_x );
        std::shared_ptr < Window > window = std::make_shared < Window > ( 0, 0, max_x, max_y );

        if ( panel.get () != nullptr )
        {
            panel->update ( input, window );
        }
    }

    void Session::set_panel ( const std::shared_ptr < Panel >& panel_ )
    {
        panel = panel_;
    }

    std::shared_ptr < Panel > Session::get_panel ()
    {
        return panel;
    }
}

Implement automatic refreshing in ncurses::Session using halfdelay


#include "variant/usart_platform.hpp"

#include "hal.h"

// USART1 configuration
static const SerialConfig usart1_config = {
  115200,
  0,
  USART_CR2_STOP1_BITS | USART_CR2_LINEN,
  0
};

// USART3 configuration
static const SerialConfig usart3_config = {
  115200,
  0,
  USART_CR2_STOP1_BITS | USART_CR2_LINEN,
  0
};

USARTPlatform::USARTPlatform() {
  sdStart(&SD1, &usart1_config);
  sdStart(&SD3, &usart3_config);
  palSetPadMode(GPIOB, 6, PAL_MODE_ALTERNATE(7)); // USART1 TX
  palSetPadMode(GPIOB, 7, PAL_MODE_ALTERNATE(7)); // USART1 RX
  palSetPadMode(GPIOB, 10, PAL_MODE_ALTERNATE(7)); // USART3 TX
  palSetPadMode(GPIOB, 11, PAL_MODE_ALTERNATE(7)); // USART3 RX
}

chibios_rt::BaseSequentialStreamInterface& USARTPlatform::getPrimaryStream() {
  return reinterpret_cast<chibios_rt::BaseSequentialStreamInterface&>(SD1);
}

#include "variant/usart_platform.hpp"

#include "hal.h"

// USART1 configuration
static const SerialConfig usart1_config = {
  38400,
  0,
  USART_CR2_STOP1_BITS | USART_CR2_LINEN,
  0
};

// USART3 configuration
static const SerialConfig usart3_config = {
  38400,
  0,
  USART_CR2_STOP1_BITS | USART_CR2_LINEN,
  0
};

USARTPlatform::USARTPlatform() {
  sdStart(&SD1, &usart1_config);
  sdStart(&SD3, &usart3_config);
  palSetPadMode(GPIOB, 6, PAL_MODE_ALTERNATE(7)); // USART1 TX
  palSetPadMode(GPIOB, 7, PAL_MODE_ALTERNATE(7)); // USART1 RX
  palSetPadMode(GPIOB, 10, PAL_MODE_ALTERNATE(7)); // USART3 TX
  palSetPadMode(GPIOB, 11, PAL_MODE_ALTERNATE(7)); // USART3 RX
}

chibios_rt::BaseSequentialStreamInterface& USARTPlatform::getPrimaryStream() {
  return reinterpret_cast<chibios_rt::BaseSequentialStreamInterface&>(SD1);
}

Reconfigure zeus for 38400 baud operation on USART1 and 3.


// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Enchants/Aura.hpp>
#include <Rosetta/Models/Battlefield.hpp>
#include <Rosetta/Models/Player.hpp>

namespace RosettaStone
{
Aura::Aura(std::string&& enchantmentID, AuraType type)
    : m_enchantmentID(enchantmentID), m_type(type)
{
    // Do nothing
}

void Aura::Activate(Entity& owner)
{
    switch (m_type)
    {
        case AuraType::FIELD_EXCEPT_SOURCE:
        {
            for (auto& minion : owner.GetOwner().GetField().GetAllMinions())
            {
                if (minion == &owner)
                {
                    continue;
                }
            }
            break;
        }
    }
}
}  // namespace RosettaStone

// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Enchants/Aura.hpp>
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Models/Battlefield.hpp>
#include <Rosetta/Models/Player.hpp>

namespace RosettaStone
{
Aura::Aura(std::string&& enchantmentID, AuraType type)
    : m_enchantmentID(enchantmentID), m_type(type)
{
    // Do nothing
}

void Aura::Activate(Entity& owner)
{
    owner.GetOwner().GetGame()->auras.emplace_back(this);

    switch (m_type)
    {
        case AuraType::FIELD_EXCEPT_SOURCE:
        {
            owner.GetOwner().GetField().AddAura(this);
            break;
        }
    }
}
}  // namespace RosettaStone

feat(card-impl): Add code to add aura to game and battlefield


#include <regex>
#include <string>
int main() {
  const std::string str = "test0159";
  const std::regex re(
      "^[a-z]+[0-9]+$",
      std::regex_constants::extended | std::regex_constants::nosubs);
  return std::regex_search(str, re) ? 0 : -1;
}

#include <regex>
#include <string>
int main() {
  const std::string str = "test0159";
  std::regex re;
  re = std::regex("^[a-z]+[0-9]+$",
       std::regex_constants::extended | std::regex_constants::nosubs);
  return std::regex_search(str, re) ? 0 : -1;
}

Change std::regex detection test to detect bug in libstdc++.

libstdc++'s std::regex has (or had) a bug in std::regex::operator=(...) that
caused undefined behaviour. Clang will detect this and compile the function so
that it crashes at runtime. This patch tried to detect that bug during
configuration.


#include "vm.hpp"
#include "vm/object_utils.hpp"

#include "capi/capi.hpp"
#include "capi/include/ruby.h"

using namespace rubinius;
using namespace rubinius::capi;

extern "C" {
  VALUE rb_file_open(const char* name, const char* mode) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();
    VALUE n = env->get_handle(String::create(env->state(), name));
    VALUE m = env->get_handle(String::create(env->state(), mode));

    return rb_funcall(rb_cFile, rb_intern("open"), 2, n, m);
  }
}

#include "vm.hpp"
#include "vm/object_utils.hpp"

#include "capi/capi.hpp"
#include "capi/18/include/ruby.h"

using namespace rubinius;
using namespace rubinius::capi;

extern "C" {
  VALUE rb_file_open(const char* name, const char* mode) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();
    VALUE n = env->get_handle(String::create(env->state(), name));
    VALUE m = env->get_handle(String::create(env->state(), mode));

    return rb_funcall(rb_cFile, rb_intern("open"), 2, n, m);
  }
}

Fix wrong reference to header

Fix wrong reference to header


#include "../Swarm.h"
#include <Eigen/Core>
#include <pybind11/eigen.h>
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

namespace MetaOpt
{
namespace Python {

namespace py = pybind11;

void init_swarm(py::module &m) {

  py::class_<Swarm>(m, "Swarm")
      .def(py::init<const ParameterSpace &, const Parameters &, std::size_t,
                    const int>())
      .def("optimize", &Swarm::optimize)
      .def("getSolution", &Swarm::getBestSolution);
}
}
}

#include "../Swarm.h"
#include <Eigen/Core>
#include <pybind11/eigen.h>
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

namespace MetaOpt {
namespace Python {

namespace py = pybind11;

void init_swarm(py::module &m) {

  auto constructor = py::init<const ParameterSpace &, const Parameters &,
                              std::size_t, const int>();
  py::class_<Swarm>(m, "Swarm")
      .def(constructor, py::arg("parameter_space"), py::arg("hyper_params"),
           py::arg("num_particles") = 10, py::arg("seed") = -1)
      .def("optimize", &Swarm::optimize)
      .def("getBestSolution", &Swarm::getBestSolution)
      .def("getBestParameters", &Swarm::getBestParameters);
}
}
}

Add default parameters for constructor

Add default parameters for constructor


#include <algorithm>
#include <set>
using namespace std;

typedef set<int> si;
/* Get the divisors of a number */
si divisores(int n) {
    vi d;
    int r = sqrt(n);

    for(int i = 1; i <= r; i++) {
        if(n % i == 0) {
            d.insert(i);
            d.insert(n / i);
        }
    }
    return d;
}

int main() {
    si divi = divisores(10);
    for (set<int>::iterator it=divi.begin(); it!=divi.end(); ++it)
        printf("%d ", *it);
    printf("\n");
}

#include <algorithm>
#include <math.h>
#include <set>
#include <stdio.h>
using namespace std;

typedef set<int> si;
/* Get the divisors of a number */
si divisores(int n) {
    si d;
    int r = sqrt(n);

    for(int i = 1; i <= r; i++) {
        if(n % i == 0) {
            d.insert(i);
            d.insert(n / i);
        }
    }
    return d;
}

int main() {
    si divi = divisores(10);
    for (set<int>::iterator it=divi.begin(); it!=divi.end(); ++it)
        printf("%d ", *it);
    printf("\n");
}

Solve some silly problems with the algorithm.


#include "dependency_tree.hpp"

#include "osal.hpp"
#include "file_exist.hpp"
#include "resolver.hpp"
#include <algorithm>

Resolver *DependencyTree::addTarget(const std::string &fileName)
{
  auto &&res = tree.insert(std::make_pair(fileName, std::make_unique<Resolver>()));
  if (!res.second)
    throw std::runtime_error("Duplicated target: " + fileName);
  return res.first->second.get();
}

void DependencyTree::resolve()
{
  resolvedList.clear();
  for (auto &&target : tree)
    resolve(target.first);
}

// TODO run in parallel
void DependencyTree::resolve(const std::string &target)
{
  auto &&resolver = tree.find(target);
  if (resolver == std::end(tree))
  {
    resolvedList.insert(target);
    return;
  }
  time_t newestModificationTime = 0;
  for (auto &&dependency : resolver->second->dependencies)
  {
    resolve(dependency);
    newestModificationTime = std::max(getFileModification(dependency), newestModificationTime);
  }
  if (!isFileExist(target))
  {
    resolver->second->exec();
    resolvedList.insert(target);
    return;
  }
  auto time = getFileModification(target);
  if (time < newestModificationTime)
    resolver->second->exec();
  resolvedList.insert(target);
  return;
}

#include "dependency_tree.hpp"

#include "osal.hpp"
#include "file_exist.hpp"
#include "resolver.hpp"
#include <algorithm>

Resolver *DependencyTree::addTarget(const std::string &fileName)
{
  auto &&res = tree.insert(std::make_pair(fileName, std::make_unique<Resolver>()));
  if (!res.second)
    throw std::runtime_error("Duplicated target: " + fileName);
  return res.first->second.get();
}

void DependencyTree::resolve()
{
  resolvedList.clear();
  for (auto &&target : tree)
    resolve(target.first);
}

// TODO run in parallel
void DependencyTree::resolve(const std::string &target)
{
  if (resolvedList.find(target) != std::end(resolvedList))
    return;
  auto &&resolver = tree.find(target);
  if (resolver == std::end(tree))
  {
    resolvedList.insert(target);
    return;
  }
  time_t newestModificationTime = 0;
  for (auto &&dependency : resolver->second->dependencies)
  {
    resolve(dependency);
    newestModificationTime = std::max(getFileModification(dependency), newestModificationTime);
  }
  if (!isFileExist(target))
  {
    resolver->second->exec();
    resolvedList.insert(target);
    return;
  }
  auto time = getFileModification(target);
  if (time < newestModificationTime)
    resolver->second->exec();
  resolvedList.insert(target);
  return;
}

Fix multiple compilations for one file

Fix multiple compilations for one file


#ifndef PIPED_PROCESS_CPP
#define PIPED_PROCESS_CPP

#include<iostream>

class child_process_streambuf: public std::streambuf
{
public:
	virtual int underflow()
	{
	}
	virtual std::streamsize xsgetn(char* bufout,std::streamsize n)
	{

	}
	virtual std::streamsize xsputn(const char* bufin,std::streamsize n)
	{

	}
};

#endif

#include<iostream>
#include<streambuf>
#include<unistd.h>

#include<cstdio>
#include<cerrno>

#include<stdexcept>
#include<system_error>

class process_streambuf_base: public std::streambuf
{
protected:
	FILE* pipefile;
public:
	enum ReadWriteType
	{
		READ_ONLY=0,
		WRITE_ONLY
	};
	process_streambuf_base(const std::string& cmd,ReadWriteType rwflag)
	{
		static const char* typestring[2]={"re","we"};
		pipefile=popen(cmd.c_str(),typestring[(int)rwflag]);
		if(!pipefile)
		{
			throw std::system_error(errno,strerror(errno));
		}
	}
	virtual ~process_streambuf_base()
	{
		int pclose(pipefile);
	}
};

class process_readstreambuf: public process_streambuf_base
{
public:
	process_readstreambuf(const std::string& cmd):
		process_streambuf_base(cmd,READ_ONLY)
	{}
	virtual int underflow()
	{
		return fgetc(pipefile);
	}
	virtual std::streamsize xsgetn(char* bufout, streamsize n)
	{
		return fread(bufout,n,1,pipefile);
	}
};

class process_writestreambuf: public process_streambuf_base
{
public:
	process_writestreambuf(const std::string& cmd):
		process_streambuf_base(cmd,WRITE_ONLY)
	{}
	virtual int overflow(int c=EOF)
	{
		return fputc(pipefile);
	}
	virtual std::streamsize xsputn(const char* bufin, streamsize n)
	{
		return fwrite(bufin,n,1,pipefile);
	}
};

Add posix process popen streambufs

Add posix process popen streambufs