text:
/*
  KeePass Password Safe - The Open-Source Password Manager
  Copyright (C) 2003-2021 Dominik Reichl <dominik.reichl@t-online.de>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "StdAfx.h"
#include "PopularPasswords.h"
#include <boost/static_assert.hpp>

std::vector<LPWSTR> CPopularPasswords::g_vMem;
std::vector<TppDictPtr> CPopularPasswords::g_vDicts;

CPopularPasswords::CPopularPasswords()
{
}

void CPopularPasswords::Clear()
{
	g_vDicts.clear();

	for(size_t i = 0; i < g_vMem.size(); ++i)
	{
		SAFE_DELETE_ARRAY(g_vMem[i]);
	}
	g_vMem.clear();
}

size_t CPopularPasswords::GetMaxLength()
{
	const size_t s = g_vDicts.size();
	if(s == 0) { ASSERT(FALSE); return 0; } // Should be initialized

	ASSERT(g_vDicts[s - 1].get() != NULL);
	ASSERT(g_vDicts[s - 1]->size() > 0);
	return (s - 1);
}

bool CPopularPasswords::ContainsLength(size_t uLen)
{
	if(uLen == 0) return false;
	if(uLen >= g_vDicts.size()) return false;

	const TppDictPtr& p = g_vDicts[uLen];
	ASSERT((p.get() == NULL) || (p->size() > 0));
	return (p.get() != NULL);
}

bool CPopularPasswords::IsPopular(LPCWSTR lpw, size_t* pdwDictSize)
{
	if(lpw == NULL) { ASSERT(FALSE); return false; }

	const size_t uLen = wcslen(lpw);
	if(uLen >= g_vDicts.size()) return false;

#ifdef _DEBUG
	for(size_t i = 0; i < uLen; ++i) { ASSERT(lpw[i] == towlower(lpw[i])); }
#endif

	const TppDictPtr& p = g_vDicts[uLen];
	if(p.get() == NULL) return false;

	if(pdwDictSize != NULL) *pdwDictSize = p->size();
	return (p->count(lpw) > 0);
}

void CPopularPasswords::Add(const UTF8_BYTE* pTextUTF8)
{
	if(pTextUTF8 == NULL) { ASSERT(FALSE); return; }

	BOOST_STATIC_ASSERT(sizeof(UTF8_BYTE) == sizeof(char));
	LPCSTR lpc = (LPCSTR)pTextUTF8;
	const int nUTF8Len = static_cast<int>(szlen(lpc));
	if(nUTF8Len <= 0) return;

	const int cchWBuf = nUTF8Len + 16;
	LPWSTR lpw = new WCHAR[cchWBuf];
	if(lpw == NULL) { ASSERT(FALSE); return; }
	ZeroMemory(lpw, cchWBuf * sizeof(WCHAR));

	const int r = MultiByteToWideChar(CP_UTF8, 0, lpc, nUTF8Len, lpw, cchWBuf - 8);
	ASSERT(r <= nUTF8Len);
	if((r == 0) || (lpw[0] == L'\0')) { ASSERT(FALSE); SAFE_DELETE_ARRAY(lpw); return; }

	size_t n = wcslen(lpw);
	ASSERT(n > 0);
	if(iswspace(lpw[n - 1]) == 0)
	{
		lpw[n] = L'\n';
		++n;
	}

	LPCWSTR lpWord = NULL;
	for(size_t i = 0; i < n; ++i)
	{
		lpw[i] = towlower(lpw[i]);

		if(iswspace(lpw[i]) != 0)
		{
			if(lpWord != NULL)
			{
				lpw[i] = L'\0'; // Terminate the word

				const size_t cc = wcslen(lpWord);
				if(cc >= g_vDicts.size()) g_vDicts.resize(cc + 1);

				TppDictPtr p = g_vDicts[cc];
				if(p.get() == NULL)
				{
					p = TppDictPtr(new TppDict());
					g_vDicts[cc] = p;
				}

				p->insert(lpWord);
				lpWord = NULL;
			}
		}
		else if(lpWord == NULL) lpWord = &lpw[i];
	}

	g_vMem.push_back(lpw);
}

void CPopularPasswords::AddResUTF8(LPCTSTR lpResName, LPCTSTR lpResType)
{
	if((lpResName == NULL) || (lpResType == NULL)) { ASSERT(FALSE); return; }

	HRSRC hRes = ::FindResource(NULL, lpResName, lpResType);
	if(hRes == NULL) { ASSERT(FALSE); return; }

	const DWORD dwSize = ::SizeofResource(NULL, hRes);
	if(dwSize == 0) { ASSERT(FALSE); return; }

	HGLOBAL hgData = ::LoadResource(NULL, hRes);
	if(hgData == NULL) { ASSERT(FALSE); return; }

	LPVOID lpData = ::LockResource(hgData);
	if(lpData == NULL) { ASSERT(FALSE); return; }

	std::vector<BYTE> v(dwSize + 4);
	ASSERT(v.size() == (dwSize + 4));
	memcpy(&v[0], lpData, dwSize);
	v[dwSize] = 0; v[dwSize + 1] = 0; v[dwSize + 2] = 0; v[dwSize + 3] = 0;

	BOOST_STATIC_ASSERT(sizeof(UTF8_BYTE) == sizeof(BYTE));
	CPopularPasswords::Add(&v[0]);
}

max_stars_repo_name: rrvt/KeePassLastPass

max_issues_repo_name: rrvt/KeePassLastPass

max_forks_repo_name: rrvt/KeePassLastPass


text:
#pragma once

#include <bacs/problem/importer.hpp>

#include <boost/noncopyable.hpp>
#include <boost/thread/tss.hpp>

namespace bacs {
namespace archive {

class importer : public bacs::problem::importer {
 public:
  explicit importer(const boost::property_tree::ptree &config);

  /// This function is thread safe.
  bacs::problem::Problem convert(const options &options_) override;

 private:
  const boost::property_tree::ptree m_config;
  boost::thread_specific_ptr<bacs::problem::importer_ptr> m_impl;
};

}  // namespace archive
}  // namespace bacs

ext: hpp


text:
/*
 * Copyright (c) 2017 Tuukka Norri
 * This code is licensed under MIT license (see LICENSE for details).
 */

#include <boost/format.hpp>
#include <sys/stat.h>
#include <vcf2multialign/fasta_reader.hh>
#include <vcf2multialign/read_single_fasta_seq.hh>
#include <vcf2multialign/vector_source.hh>

namespace v2m = vcf2multialign;

namespace {

	struct callback {
		v2m::vector_type *reference;
		size_t i{0};

		callback(v2m::vector_type &reference_):
			reference(&reference_)
		{
		}

		void handle_sequence(
			std::string const &identifier,
			std::unique_ptr <v2m::vector_type> &seq,
			size_t const &seq_length,
			v2m::vector_source <v2m::vector_type> &vs
		)
		{
			std::cerr << "read sequence of length " << seq_length << '.' << std::endl;

			// Use ADL.
			using std::swap;
			seq->resize(seq_length);
			swap(*reference, *seq);
			vs.put_vector(seq);
		}

		void finish() {}
	};
}

namespace vcf2multialign {

	// Read the contents of a FASTA file into a single sequence.
	void read_single_fasta_seq(file_istream &ref_fasta_stream, vector_type &reference)
	{
		typedef vector_source <vector_type> vector_source;
		typedef fasta_reader <vector_source, callback> fasta_reader;

		vector_source vs(1, false);

		{
			// Approximate the size of the reference from the size of the FASTA file.
			int const fd(ref_fasta_stream->handle());
			struct stat sb;
			auto const st(fstat(fd, &sb));
			if (0 != st)
			{
				auto const err_str(strerror(errno));
				auto const msg(boost::str(boost::format("Unable to stat the reference file: %s") % err_str));
				fail(msg.c_str());
			}

			// Preallocate space for the reference.
			std::cerr << "Preallocating a vector of size " << sb.st_size << "…";
			std::unique_ptr <vector_type> vec_ptr;
			vs.get_vector(vec_ptr);
			vec_ptr->reserve(sb.st_size);
			vs.put_vector(vec_ptr);
			std::cerr << " done." << std::endl;
		}

		callback cb(reference);
		fasta_reader reader;

		std::cerr << "Reading reference FASTA into memory… " << std::flush;
		reader.read_from_stream(ref_fasta_stream, vs, cb);
	}
}

ext: cc


text:
#include "ioserver/serialport/AsyncSerialEvent.h"

#include <boost/shared_ptr.hpp>
#include "ioserver/serialport/AsyncSerialPort.h"

namespace r7 {

AsyncSerialEvent::AsyncSerialEvent(boost::shared_ptr<AsyncSerialPort> serialPort, const Type type) :
    _serialPort(serialPort),
    _type(type),
    _data()
{
}

AsyncSerialEvent::AsyncSerialEvent(boost::shared_ptr<AsyncSerialPort> serialPort, const Type type, const std::vector<unsigned char> data) :
    _serialPort(serialPort),
    _type(type),
    _data(data)
{
}

AsyncSerialEvent::~AsyncSerialEvent(void)
{
}

const AsyncSerialEvent::Type AsyncSerialEvent::getType()
{
    return _type;
}

const boost::shared_ptr<AsyncSerialPort> AsyncSerialEvent::getSerialPort()
{
    return _serialPort;
}

const std::vector<unsigned char>& AsyncSerialEvent::getData() const
{
    return _data;
}

}

ext: cpp


text:
/*
 * Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include <boost/filesystem.hpp>
#include <locale>
#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#include <unistd.h> //gethostname
#include <algorithm>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <limits.h>
#include <fnmatch.h>
#include <fstream>
#include <boost/regex.hpp>

# include <pwd.h>
# include <sys/time.h>
# include <sys/socket.h>
# include <sys/types.h>
# include <arpa/inet.h>
#ifndef ANDROID
# include <ifaddrs.h>
#else
# include <dirent.h>
# include <linux/if_arp.h>
#endif

#if defined (__linux__)
# include <sys/prctl.h>
# include <sys/resource.h>
#endif

#if defined (__MACH__)
# include <mach/mach_init.h>
# include <mach/thread_info.h>
# include <mach/thread_act.h>
#endif

#ifdef __APPLE__
#include <libproc.h>
#endif

#include <pthread.h>
#include <qi/os.hpp>
#include <qi/log.hpp>
#include <qi/path.hpp>
#include "utils.hpp"

#include <mutex>

qiLogCategory("qi.os");

namespace qi {
  namespace os {

    FILE* fopen(const char *filename, const char *mode) {
      return ::fopen(filename, mode);

    }

    int stat(const char *filename, struct ::stat* status) {
      return ::stat(filename, status);
    }

    std::string getenv(const char *var) {
      char *res = ::getenv(var);
      if (res == NULL)
        return "";
      return std::string(res);
    }

    std::string pathsep() {
      return ":";
    }

    int setenv(const char *var, const char *value) {
      return ::setenv(var, value, 1);
    }

    int unsetenv(const char *var) {
      return ::unsetenv(var);
    }

    void sleep(unsigned int seconds) {
      // In case sleep was interrupted by a signal,
      // keep sleeping until we have slept the correct amount
      // of time.
      while (seconds != 0) {
        seconds = ::sleep(seconds);
      }
    }

    void msleep(unsigned int milliseconds) {
      // Not the same for usleep: it returns a non-zero
      // error code if it was interupted...
      usleep(milliseconds * 1000);
    }

    std::string home()
    {
#ifdef ANDROID
      return "/mnt/sdcard";
#endif
      std::string envHome = qi::os::getenv("HOME");
      if (envHome != "")
      {
        return boost::filesystem::path(envHome, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());
      }

      // $HOME environment variable not defined:
      char *lgn;
      struct passwd *pw;
      if ((lgn = getlogin()) != NULL && (pw = getpwnam(lgn)) != NULL)
      {
        return boost::filesystem::path(pw->pw_dir, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());
      }

      // Give up:
      return "";
    }

    std::string mktmpdir(const char *prefix)
    {
      std::string sprefix;
      std::string tmpdir;
      std::string path;
      int         i = 0;

      if (prefix)
        sprefix = prefix;

      bool isCreated = false;
      do
      {
        tmpdir = sprefix;
        tmpdir += randomstr(7);
        boost::filesystem::path pp(qi::os::tmp(), qi::unicodeFacet());
        pp.append(tmpdir, qi::unicodeFacet());
        path = pp.make_preferred().string(qi::unicodeFacet());
        ++i;

        try
        {
          isCreated = boost::filesystem::create_directory(pp.make_preferred());
        }
        catch (const boost::filesystem::filesystem_error &e)
        {
          qiLogDebug() << "Attempt " << i << " fail to create tmpdir! " << e.what();
        }
      }
      while (i < TMP_MAX && !isCreated);

      return path;
    }

    std::string tmp()
    {
      std::string temp = ::qi::os::getenv("TMPDIR");
      if (temp.empty())
        temp = "/tmp/";

      boost::filesystem::path p = boost::filesystem::path(temp, qi::unicodeFacet());

      return p.make_preferred().string(qi::unicodeFacet());
    }

#ifdef ANDROID
    std::string gethostname()
    {
      assert(0 && "qi::os::gethostname is not implemented for android, "
                  "use the JAVA API instead");
      return "";
    }
#else
    std::string gethostname()
    {
      long hostNameMax;
#ifdef HAVE_SC_HOST_NAME_MAX
      hostNameMax = sysconf(_SC_HOST_NAME_MAX) + 1;
#else
      hostNameMax = HOST_NAME_MAX + 1;
#endif
      char *szHostName = (char*) malloc(hostNameMax * sizeof(char));
      memset(szHostName, 0, hostNameMax);
      if (::gethostname(szHostName, hostNameMax) == 0) {
        std::string hostname(szHostName);
        free(szHostName);
        return hostname;
      }

      free(szHostName);
      return std::string();
    }
#endif

    int isatty(int fd)
    {
      return ::isatty(fd);
    }

    char* strdup(const char *src)
    {
      return ::strdup(src);
    }

    int snprintf(char *str, size_t size, const char *format, ...)
    {
      va_list list;
      va_start(list, format);
      int ret = vsnprintf(str, size, format, list);
      va_end(list);

      return ret;
    }

    unsigned short findAvailablePort(unsigned short port)
    {
      struct sockaddr_in name;
      name.sin_family = AF_INET;
      name.sin_addr.s_addr = htonl(INADDR_ANY);
      int sock = ::socket(AF_INET, SOCK_STREAM, 0);

      // cast ushort into int to check all ports between
      // [49152, 65535] (e.g. USHRT_MAX)
      unsigned short iPort = port != 0 ? port : static_cast<unsigned short>(49152);
      int unavailable = -1;

      do
      {
        name.sin_port = htons(iPort);
        unavailable = ::bind(sock, (struct sockaddr *)&name, sizeof(name));

        if (!unavailable)
        {
          unavailable = ::close(sock);
          if (!unavailable)
            break;
        }
        ++iPort;
      }
      while (static_cast<unsigned int>(iPort + 1) < USHRT_MAX);

      if (unavailable)
      {
        iPort = 0;
        qiLogError() << "Socket Cannot find available port, Last Error: " << unavailable;
      }
      qiLogDebug() << "Returning port: " << iPort;
      return iPort;
    }

#ifdef ANDROID
    std::map<std::string, std::vector<std::string> > hostIPAddrs(bool ipv6Addr)
    {
      std::map<std::string, std::vector<std::string> > res;
      std::vector<std::string> addrs;
      std::string interfacesDirectory = "/sys/class/net/";
      DIR *d;
      struct dirent *de;
      std::string interfaceName;
      uint32_t addr, flags;
      struct ifreq ifr;
      int ioctl_sock;
      static char buf[32];

      // Initialize test socket and open interfaces directory
      ioctl_sock = socket(AF_INET, SOCK_DGRAM, 0);
      if (ioctl_sock < 0 ||
         (d = opendir(interfacesDirectory.c_str())) == 0)
      {
        qiLogError() << "socket() failed: " << strerror(errno);
        close(ioctl_sock);
        return res;
      }

      // Foreach interface
      while ((de = readdir(d)))
      {

        // Get interface name and set it in ifreq struct
        interfaceName = de->d_name;

        if (interfaceName == "." || interfaceName == "..")
          continue;

        // set name in ifreq struct
        memset(&ifr, 0, sizeof(struct ifreq));
        strncpy(ifr.ifr_name, de->d_name, strlen(de->d_name) + 1);

        // Get interface IP address
        if (ioctl(ioctl_sock, SIOCGIFADDR, &ifr) < 0)
          continue;
        addr = ((struct sockaddr_in*) &ifr.ifr_addr)->sin_addr.s_addr;

        // Get interface flags
        if (ioctl(ioctl_sock, SIOCGIFFLAGS, &ifr) < 0)
          continue;
        flags = ifr.ifr_flags;

        // Check if interface is down
        if (!(flags & 1) || addr == 0)
          continue;

        // Set address in map
        addrs.clear();
        sprintf(buf,"%d.%d.%d.%d", addr & 255, ((addr >> 8) & 255), ((addr >> 16) & 255), (addr >> 24));
        addrs.push_back(buf);
        qiLogVerbose("qi.hostIPAddrs") << "New endpoints for " << interfaceName << ": " << buf;

        // set addrs in map
        res[interfaceName] = addrs;
      }

      closedir(d);
      close(ioctl_sock);
      return res;
    }
#else
    std::map<std::string, std::vector<std::string> > hostIPAddrs(bool ipv6Addr)
    {
      std::map<std::string, std::vector<std::string> > ifsMap;
      struct ifaddrs *ifAddrStruct = nullptr;
      struct ifaddrs *ifa = nullptr;
      void *tmpAddrPtr = nullptr;
      int ret = 0;

      static std::mutex mutex;
      std::lock_guard<std::mutex> lock(mutex);

      ret = getifaddrs(&ifAddrStruct);
      if (ret == -1) {
        qiLogError() << "getifaddrs failed: " << strerror(errno);
        return std::map<std::string, std::vector<std::string> >();
      }

      for (ifa = ifAddrStruct; ifa != 0; ifa = ifa->ifa_next)
      {
        if (!ifa->ifa_addr)
          continue;
        if (ifa->ifa_addr->sa_family == AF_INET && !ipv6Addr)
        {
          tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
          char addressBuffer[INET_ADDRSTRLEN];
          inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);

          ifsMap[ifa->ifa_name].push_back(addressBuffer);
        }
        else if (ifa->ifa_addr->sa_family == AF_INET6 && ipv6Addr)
        {
          tmpAddrPtr = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
          char addressBuffer[INET6_ADDRSTRLEN];
          inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
          ifsMap[ifa->ifa_name].push_back(addressBuffer);
        }
      }
      freeifaddrs(ifAddrStruct);
      return ifsMap;
     }
#endif

  void setCurrentThreadName(const std::string &name) {
#if defined (__linux__) && !defined(ANDROID)
    prctl(PR_SET_NAME, name.c_str(), 0, 0, 0);
#elif defined (__APPLE__)
    pthread_setname_np(name.c_str());
#elif defined (ANDROID)
    //no implementation under Android
#else
    //BSD, whatever...
    pthread_set_name_np(pthread_self(), name.c_str());
#endif
  }

    std::string currentThreadName() {
      char buffer[16] = {0};
#if defined(__linux__) && !defined(ANDROID)
      prctl(PR_GET_NAME, buffer, 0, 0);
#elif defined(__APPLE__)
      pthread_getname_np(pthread_self(), buffer, 16);
#elif defined (ANDROID)
      //no implementation under Android
#else
      // BSD
      pthread_get_name_np(pthread_self(), buffer);
#endif
      return std::string(buffer);
    }

    long numberOfCPUs()
    {
      return sysconf(_SC_NPROCESSORS_CONF);
    }

    //true on success
    bool setCurrentThreadCPUAffinity(const std::vector<int> &cpus) {
     #if defined (__linux__) && !defined(ANDROID)
      cpu_set_t cpu;
      pthread_t self = pthread_self();
      CPU_ZERO(&cpu);
      for (unsigned int i = 0; i < cpus.size(); ++i)
        CPU_SET(cpus[i], &cpu);
      int ret = 0;
      ret = pthread_setaffinity_np(self, sizeof(cpu_set_t), &cpu);
      return !ret;
     #endif
      return false;
    }

    static std::string readLink(const std::string &link)
    {
      boost::filesystem::path p(link, qi::unicodeFacet());

      try
      {
        while (boost::filesystem::exists(p))
        {
          if (boost::filesystem::is_symlink(p))
          {
            p = boost::filesystem::read_symlink(p);
          }
          else
          {
            std::string basename = p.parent_path().filename().string(qi::unicodeFacet());
            std::string filename = p.filename().string(qi::unicodeFacet());
            boost::filesystem::path res(basename, qi::unicodeFacet());
            res.append(filename, qi::unicodeFacet());
            return res.make_preferred().string(qi::unicodeFacet());
          }
        }
      }
      catch (const boost::filesystem::filesystem_error &e)
      {
        qiLogError() << "Cannot access path '" << link << "': " << e.what();
      }
      return std::string();
    }

    std::string timezone()
    {
      std::string link = readLink("/etc/timezone");
      if (link.empty())
        link = readLink("/etc/localtime");
      if (link.empty())
        qiLogError() << "Could not find timezone!";

      return link;
    }

    bool fnmatch(const std::string &pattern, const std::string &string)
    {
      return !::fnmatch(pattern.c_str(), string.c_str(), 0);
    }

    std::pair<int64_t, int64_t> cputime()
    {
      static const int64_t seq_to_usec = 1000000LL;
#ifdef __linux__
      // use clock_gettime, which does not split user and system time
      timespec ts;
      int res = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
      if (res < 0)
      {
        qiLogError() << "clock_gettime: " << strerror(errno);
        return std::make_pair(0, 0);
      }
      return std::make_pair(
        ts.tv_sec * seq_to_usec + ts.tv_nsec / 1000, 0);
#else
      thread_basic_info threadInfo;
      unsigned int count = THREAD_BASIC_INFO_COUNT;
      thread_info(mach_thread_self(), THREAD_BASIC_INFO, (thread_info_t)&threadInfo, &count);

      return std::make_pair(
        threadInfo.user_time.seconds * seq_to_usec + threadInfo.user_time.microseconds,
        threadInfo.system_time.seconds * seq_to_usec + threadInfo.system_time.microseconds
     );
#endif
    }

    size_t memoryUsage(unsigned int pid)
    {
      // linux version will be more accurate than mac, since mac is based on the resident size
#if defined(__linux__)
      // It's based on PSS (Proportionnal Set Size)
      // unshared pages + a fraction of each shared pages (proportionnal on how many processes are using the shared page)

      std::stringstream ss;
      ss << "/proc/" << pid << "/smaps";

      size_t totalPss = 0;
      std::ifstream smaps(ss.str().c_str(), std::ios_base::in | std::ios_base::binary);
      if (smaps)
      {
        boost::cmatch result;
        static boost::regex pssRegex("^Pss:[ ]+([0-9]+) kB$");
        for(std::string line; std::getline(smaps, line); )
        {
          if (boost::regex_match(line.c_str(), result, pssRegex))
          {
            size_t pss;
            std::istringstream iss(result[1]);
            iss >> pss;
            totalPss += pss;
          }
        }
      }
      else
      {
        qiLogWarning() << "cannot get memory usage for PID " << pid << ": process doesn't exist";
      }

      return totalPss;
#elif defined(__APPLE__)
      struct proc_taskinfo taskInfo;
      unsigned long ret = proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &taskInfo, sizeof(taskInfo));
      if (ret <= 0L)
      {
        qiLogWarning() << "cannot get memory usage for PID " << pid << ": " << strerror(errno);
        return 0;
      }
      else if (ret < sizeof(taskInfo))
      {
        qiLogWarning() << "cannot get memory usage for PID " << pid;
        return 0;
      }

      size_t size = (size_t) (taskInfo.pti_resident_size / 1024);
      return size;
#else
      qiLogWarning() << "memory usage unavailable for this platform";
      return 0;
#endif
    }
  }
}

max_stars_repo_name: arntanguy/libqi

max_issues_repo_name: arntanguy/libqi

max_forks_repo_name: arntanguy/libqi


text:
#include "fft.hpp"

#include "dynamic_grid.hpp"
#include "global.hpp"
#include "test_helpers.hpp"

#include <fftw3.h>
#include <vector>
#include <complex>
#include <cstdlib>

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(fft_tests)

BOOST_AUTO_TEST_CASE(check_roundtrip)
{

	std::vector<complex_t> data(64);
	for(int i=0; i < 64; ++i)
	{
		data[i] = rand_value();
	}

	BOOST_TEST_CHECKPOINT("checking 1d fft");

	auto copy = data;

	fft(copy, std::vector<int>({64}));
	ifft(copy, std::vector<int>({64}));

	for(int i=0; i < 64; ++i)
	{
		BOOST_CHECK_SMALL( std::abs(copy[i] - data[i]), 1e3*std::numeric_limits<double>::epsilon() );
	}

	BOOST_TEST_CHECKPOINT("checking 2d fft");

	copy = data;

	fft(copy, std::vector<int>({8,8}));
	ifft(copy, std::vector<int>({8,8}));
	for(int i=0; i < 64; ++i)
	{
		BOOST_CHECK_SMALL( std::abs(copy[i] - data[i]), 1e3*std::numeric_limits<double>::epsilon() );
	}

	BOOST_TEST_CHECKPOINT("checking 3d fft");

	copy = data;

	fft(copy, std::vector<int>({4, 4, 4}));
	ifft(copy, std::vector<int>({4, 4, 4}));
	for(int i=0; i < 64; ++i)
	{
		BOOST_CHECK_SMALL( std::abs(copy[i] - data[i]), 1e3*std::numeric_limits<double>::epsilon() );
	}
}

BOOST_AUTO_TEST_CASE(check_error_handling)
{

    std::vector<complex_t> data(35);
    for(int i=0; i < 35; ++i)
	{
		data[i] = rand_value();
	}

	auto copy = data;

	// throw because copy.size does not match expected size
	BOOST_CHECK_THROW(fft(copy, std::vector<int>({64})), std::invalid_argument);
	BOOST_CHECK_THROW(fft(copy, std::vector<int>({5,5})), std::invalid_argument);
	BOOST_CHECK_THROW(fft(copy, std::vector<int>({5,5,5})), std::invalid_argument);

	// check that copy is left unchanged by the preceding calls
	for(unsigned int i=0; i < data.size(); ++i)
	{
		BOOST_CHECK_EQUAL( copy[i], data[i] );
	}

	// same thing for ifft
	BOOST_CHECK_THROW(ifft(copy, std::vector<int>({64})), std::invalid_argument);
	BOOST_CHECK_THROW(ifft(copy, std::vector<int>({5,5})), std::invalid_argument);
	BOOST_CHECK_THROW(ifft(copy, std::vector<int>({5,5,5})), std::invalid_argument);
	// check that copy is left unchanged
	for(unsigned int i=0; i < data.size(); ++i)
	{
		BOOST_CHECK_EQUAL( copy[i], data[i] );
	}

	// check size argument fitting into int
	BOOST_CHECK_THROW( fft(copy, std::vector<int>({-1})), std::overflow_error );
	BOOST_CHECK_THROW( ifft(copy, std::vector<int>({-1})), std::overflow_error );
}

/// \todo grid_interface_test is obsolete
/// \todo iterator interface and DynamicGrid interface tests missing.
/*
BOOST_AUTO_TEST_CASE(grid_interface_test)
{

    std::vector<std::complex<double>> data(64);
    for(int i=0; i < 64; ++i)
	{
		data[i] = rand_value();
	}

	// 1d

	auto grid_dat = data;
    grid<decltype(data), 1> grid1d(64, grid_dat );

	auto copy = data;

	fft(grid1d);
	fft(1, copy, 64);
	for(int i=0; i < 64; ++i)
	{
		BOOST_CHECK_EQUAL( copy[i], grid_dat[i] );
	}

	ifft(grid1d);
	ifft(1, copy, 64);
	for(int i=0; i < 64; ++i)
	{
		BOOST_CHECK_EQUAL( copy[i], grid_dat[i] );
	}

	// 3d
    grid<decltype(data), 3> grid3d(4, grid_dat );

	fft(grid3d);
	fft(3, copy, 4);
	for(int i=0; i < 64; ++i)
	{
		BOOST_CHECK_EQUAL( copy[i], grid_dat[i] );
	}

	ifft(grid3d);
	ifft(3, copy, 4);
	for(int i=0; i < 64; ++i)
	{
		BOOST_CHECK_EQUAL( copy[i], grid_dat[i] );
	}
}*/

BOOST_AUTO_TEST_CASE( fftw_wisdom_check )
{
	// try fft without wisdom
	fftw_forget_wisdom();
	fftw_cleanup();

	std::vector<std::complex<double>> data(64);
	for( auto& d : data )
		d = rand_value();

	auto copy = data;

	// fft without wisdom
	fft( data, std::vector<int>({64}) );
	// fft with wisdom
	fft( copy, std::vector<int>({64}) );

	for(unsigned i = 0; i < data.size(); ++i)
	{
		BOOST_CHECK_SMALL( std::abs(data[i] - copy[i]), 1e-10 );
	}

	// check inverse
	fftw_cleanup();
	ifft( data, std::vector<int>({64}) );
	ifft( copy, std::vector<int>({64}) );
	for(unsigned i = 0; i < data.size(); ++i)
		BOOST_CHECK_SMALL( std::abs(data[i] - copy[i]), 1e-10 );

}

/// \todo maybe add another check that actually checks values for a know case.

BOOST_AUTO_TEST_SUITE_END()


text:
/*
 *
 *
 *
 *
 *
 */

#include <vector>
#include "../../src/sfof.hpp"
#include "../../src/exceptions.hpp"

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE MasterTestSuite
#include <boost/test/unit_test.hpp>
#include <boost/test/parameterized_test.hpp>

#include <iostream>

using namespace boost::unit_test;

BOOST_AUTO_TEST_SUITE (Master_test_suite)

/*
 * set up basic test for elementary methods and routines
 */

/*
 * ASTRO class
 */

//void test_Astro()
BOOST_AUTO_TEST_CASE( test_Astro )
{
  Astro astro;
  BOOST_TEST_MESSAGE("entering case for Astro");
  BOOST_CHECK( astro.find_bin(1.0, 1.0, 1.0) == 0 );
  BOOST_CHECK_THROW( astro.find_bin(1.0, 2.0, 1.0) == 0, BadArgumentException);   // out-of-range values should be handled

  /* .. */

}

//void test_Options_and_Galaxies()
BOOST_AUTO_TEST_CASE( test_Options_and_Galaxies )
{
  int i;
  Option opt;
  std::vector<Galaxy> gals;

  double version_number = 1.0;

  BOOST_TEST_MESSAGE("entering case for Options and Galaxy");

  opt.read_opts(framework::master_test_suite().argc, framework::master_test_suite().argv, version_number);

  BOOST_CHECK( opt.link_r != 0);
  BOOST_CHECK( opt.fof_mode == "phot");
  BOOST_CHECK( opt.z_bin_size > 0);
  BOOST_CHECK_MESSAGE( opt.input_file.length() != 0, opt.input_file);

  /* .. */

  Fileio fileio;
  if (opt.fof_mode == "spec")
    fileio.set_up(1, 2, 3, 4);
  else
    fileio.set_up(1, 2, 3, 4, 5);
  if(opt.input_mode == "ascii")
    fileio.read_ascii(opt.input_file, opt.fof_mode, opt.z_min, opt.z_max, opt.z_err_max, gals);
  else if(opt.input_mode == "fits")
    fileio.read_fits(opt.input_file, opt.fof_mode, opt.z_min, opt.z_max, opt.z_err_max, gals);

  BOOST_CHECK( gals.size() > 0);

  std::vector<int> nums;
  for (int i = 0; i < gals.size(); i++)
  nums.push_back(gals[i].num);

  sort(nums.begin(), nums.end());

  for (i = 0; (nums[i]!= nums[i+1]) && (i < nums.size()-1); i++)
    ;

  BOOST_CHECK( i == nums.size()-1 );

}

BOOST_AUTO_TEST_SUITE_END ()

// test_suite* init_unit_test_suite(int argc, char *argv[])
// {

//   // test_suite* ts1 = BOOST_TEST_SUITE( "simple functions" );
//   // ts1->add( BOOST_TEST_CASE( &test_Astro ) );
//   // ts1->add( BOOST_TEST_CASE( &test_Options_and_Galaxies ) );

//   framework::master_test_suite().p_name.value = "Master Unit test";
//   framework::master_test_suite().add( BOOST_TEST_CASE( &test_Astro ) );
//   framework::master_test_suite().add( BOOST_TEST_CASE( &test_Options_and_Galaxies ) );

// }

max_stars_repo_name: sfarrens/sfof

max_issues_repo_name: umikanero/sfof

max_forks_repo_name: umikanero/sfof


text:
// Copyright (c) 2014-2020, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
//    conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
//    of conditions and the following disclaimer in the documentation and/or other
//    materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
//    used to endorse or promote products derived from this software without specific
//    prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <boost/range/adaptor/reversed.hpp>

#include "string_tools.h"
#include "blockchain_db.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "profile_tools.h"
#include "ringct/rctOps.h"

#include "lmdb/db_lmdb.h"

#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "blockchain.db"

using epee::string_tools::pod_to_hex;

namespace cryptonote
{

bool matches_category(relay_method method, relay_category category) noexcept
{
  switch (category)
  {
    default:
      return false;
    case relay_category::all:
      return true;
    case relay_category::relayable:
      return method != relay_method::none;
    case relay_category::broadcasted:
    case relay_category::legacy:
      break;
  }
  // check for "broadcasted" or "legacy" methods:
  switch (method)
  {
    default:
    case relay_method::local:
    case relay_method::forward:
    case relay_method::stem:
      return false;
    case relay_method::block:
    case relay_method::fluff:
      return true;
    case relay_method::none:
      break;
  }
  return category == relay_category::legacy;
}

void txpool_tx_meta_t::set_relay_method(relay_method method) noexcept
{
  kept_by_block = 0;
  do_not_relay = 0;
  is_local = 0;
  is_forwarding = 0;
  dandelionpp_stem = 0;

  switch (method)
  {
    case relay_method::none:
      do_not_relay = 1;
      break;
    case relay_method::local:
      is_local = 1;
      break;
    case relay_method::forward:
      is_forwarding = 1;
      break;
    case relay_method::stem:
      dandelionpp_stem = 1;
      break;
    case relay_method::block:
      kept_by_block = 1;
      break;
    default:
    case relay_method::fluff:
      break;
  }
}

relay_method txpool_tx_meta_t::get_relay_method() const noexcept
{
  const uint8_t state =
    uint8_t(kept_by_block) +
    (uint8_t(do_not_relay) << 1) +
    (uint8_t(is_local) << 2) +
    (uint8_t(is_forwarding) << 3) +
    (uint8_t(dandelionpp_stem) << 4);

  switch (state)
  {
    default: // error case
    case 0:
      break;
    case 1:
      return relay_method::block;
    case 2:
      return relay_method::none;
    case 4:
      return relay_method::local;
    case 8:
      return relay_method::forward;
    case 16:
      return relay_method::stem;
  };
  return relay_method::fluff;
}

bool txpool_tx_meta_t::upgrade_relay_method(relay_method method) noexcept
{
  static_assert(relay_method::none < relay_method::local, "bad relay_method value");
  static_assert(relay_method::local < relay_method::forward, "bad relay_method value");
  static_assert(relay_method::forward < relay_method::stem, "bad relay_method value");
  static_assert(relay_method::stem < relay_method::fluff, "bad relay_method value");
  static_assert(relay_method::fluff < relay_method::block, "bad relay_method value");

  if (get_relay_method() < method)
  {
    set_relay_method(method);
    return true;
  }
  return false;
}

BlockchainDB *new_db()
{
  return new BlockchainLMDB();
}

void BlockchainDB::init_options(boost::program_options::options_description& desc)
{
}

void BlockchainDB::set_hard_fork(HardFork* hf)
{
  m_hardfork = hf;
}

bool BlockchainDB::is_open() const
{
  return m_open;
}

block BlockchainDB::get_block_from_height(const uint64_t& height) const
{
  blobdata bd = get_block_blob_from_height(height);
  const block b=parse_block_from_blob(bd);

  return b;
}

block BlockchainDB::get_block(const crypto::hash& h) const
{
  blobdata bd = get_block_blob(h);
  const block b=parse_block_from_blob(bd);

  return b;
}

void BlockchainDB::reset_stats()
{
  time_blk_hash = 0;
  time_tx_exists = 0;
  time_add_block1 = 0;
  time_add_transaction = 0;
  time_commit1 = 0;
}

void BlockchainDB::show_stats()
{
  LOG_PRINT_L1(ENDL
    << "*********************************"
    << ENDL
    << "time_blk_hash: " << time_blk_hash << "ms"
    << ENDL
    << "time_tx_exists: " << time_tx_exists << "ms"
    << ENDL
    << "time_add_block1: " << time_add_block1 << "ms"
    << ENDL
    << "time_add_transaction: " << time_add_transaction << "ms"
    << ENDL
    << "time_commit1: " << time_commit1 << "ms"
    << ENDL
    << "*********************************"
    << ENDL
  );
}

bool BlockchainDB::txpool_tx_matches_category(const crypto::hash& tx_hash, relay_category category)
{
  try
  {
    txpool_tx_meta_t meta{};
    if (!get_txpool_tx_meta(tx_hash, meta))
    {
      MERROR("Failed to get tx meta from txpool");
      return false;
    }
    return meta.matches(category);
  }
  catch (const std::exception &e)
  {
    MERROR("Failed to get tx meta from txpool: " << e.what());
  }
  return false;
}

}  // namespace cryptonote

max_stars_repo_name: flywithfang/dfa

max_issues_repo_name: flywithfang/dfa

max_forks_repo_name: flywithfang/dfa


text:
#include <boost/ut.hpp>
#include "GridLine.hpp"

namespace {

using namespace boost::ut;
using namespace std::string_literals;

struct Tex : BaseTexture
{
    std::string s;
    Tex(const std::string &s): s{s} {}
    static PtrT n(const std::string &s) { return PtrT{new Tex(s)}; }
};

suite s = [] {
    auto generator = [](const auto &t) { return Tex::n(t.text); };
    auto no_generator = [](const auto &) { return Tex::n("*"); };

    auto dump = [](GridLine &tc) {
        std::string buf;
        auto action = [&](const GridLine::Chunk &t) {
            buf += t.text;
        };
        tc.ForEach(action);
        return buf;
    };

    auto dump2 = [](GridLine &tc) {
        std::string buf;
        auto action = [&](const GridLine::Chunk &t) {
            buf += static_cast<Tex*>(t.texture.get())->s;
        };
        tc.ForEach(action);
        return buf;
    };

    "GridLine"_test = [&] {
        "foreach"_test = [&] {
            GridLine c;
            auto s = c.GetScanner(0);

            expect(s.EnsureNext(GridLine::Chunk(0, 1, 0, "He"), generator));
            expect(s.EnsureNext(GridLine::Chunk(2, 1, 0, "llo"), generator));
            expect(s.EnsureNext(GridLine::Chunk(3, 1, 0, " world"), generator));

            expect(eq("Hello world"s, dump(c)));
            expect(eq("Hello world"s, dump2(c)));
        };

        "scan"_test = [&] {
            GridLine c;
            {
                auto s = c.GetScanner(0);
                expect(s.EnsureNext(GridLine::Chunk(0, 1, 0, "He"), generator));
                expect(s.EnsureNext(GridLine::Chunk(2, 1, 0, "llo"), generator));
                expect(s.EnsureNext(GridLine::Chunk(3, 1, 0, " world"), generator));
            }

            {
                auto s = c.GetScanner(0);
                expect(!s.EnsureNext(GridLine::Chunk(0, 1, 0, "He"), no_generator));
                expect(s.EnsureNext(GridLine::Chunk(2, 1, 0, "llo "), generator));
                expect(s.EnsureNext(GridLine::Chunk(3, 1, 0, "again"), generator));
            }
            expect(eq("Hello again"s, dump(c)));
            expect(eq("Hello again"s, dump2(c)));
        };

        "update"_test = [&] {
            GridLine c;
            {
                auto s = c.GetScanner(0);
                expect(s.EnsureNext(GridLine::Chunk(0, 1, 0, "T"), generator));
                expect(s.EnsureNext(GridLine::Chunk(1, 1, 0, "e"), generator));
                expect(s.EnsureNext(GridLine::Chunk(2, 1, 0, "s"), generator));
                expect(s.EnsureNext(GridLine::Chunk(3, 1, 0, "t"), generator));
                expect(s.EnsureNext(GridLine::Chunk(4, 1, 0, "2"), generator));
            }
            {
                auto s = c.GetScanner(0);
                expect(s.EnsureNext(GridLine::Chunk(0, 1, 0, "B"), generator));
                expect(!s.EnsureNext(GridLine::Chunk(1, 1, 0, "e"), no_generator));
                expect(!s.EnsureNext(GridLine::Chunk(3, 1, 0, "t"), no_generator));
            }
            expect(eq("Bet"s, dump(c)));
            expect(eq("Bet"s, dump2(c)));
        };

        "move"_test = [&] {
            GridLine c1;
            {
                auto s = c1.GetScanner(0);
                expect(s.EnsureNext(GridLine::Chunk(0, 1, 0, "T"), generator));
                expect(s.EnsureNext(GridLine::Chunk(2, 1, 0, "e"), generator));
                expect(s.EnsureNext(GridLine::Chunk(4, 1, 0, "s"), generator));
                expect(s.EnsureNext(GridLine::Chunk(6, 1, 0, "t"), generator));
                expect(s.EnsureNext(GridLine::Chunk(8, 1, 0, "2"), generator));
            }
            GridLine c2;
            {
                auto s = c2.GetScanner(0);
                expect(s.EnsureNext(GridLine::Chunk(1, 1, 0, "Q"), generator));
                expect(s.EnsureNext(GridLine::Chunk(3, 1, 0, "W"), generator));
                expect(s.EnsureNext(GridLine::Chunk(5, 1, 0, "E"), generator));
                expect(s.EnsureNext(GridLine::Chunk(7, 1, 0, "R"), generator));
            }

            c1.MoveFrom(c2, 2, 7, 0xffffffff);
            expect(eq("TeWsEt2"s, dump(c1)));
            expect(eq("TeWsEt2"s, dump2(c1)));
            expect(eq("QR"s, dump(c2)));
            expect(eq("QR"s, dump2(c2)));
        };

        "shift"_test = [&] {
            GridLine c;
            {
                auto s = c.GetScanner(0);
                expect(s.EnsureNext(GridLine::Chunk(0, 2, 0, "He"), generator));
                expect(s.EnsureNext(GridLine::Chunk(2, 1, 0, " "), generator));
                expect(s.EnsureNext(GridLine::Chunk(3, 3, 0, "llo"), generator));
            }
            expect(eq("He llo"s, dump(c)));
            expect(eq("He llo"s, dump2(c)));

            {
                auto s = c.GetScanner(0);
                expect(!s.EnsureNext(GridLine::Chunk(0, 2, 0, "He"), no_generator));
                expect(!s.EnsureNext(GridLine::Chunk(2, 3, 0, "llo"), no_generator));
            }
            expect(eq("Hello"s, dump(c)));
            expect(eq("Hello"s, dump2(c)));
        };
    };

    "GridLine::ChunkWrapper"_test = [&] {
        using WrapperT = GridLine::ChunkWrapper<&BaseTexture::IncRef>;
        GridLine::Chunk c{0, 1, 0, "test"};
        c.texture = generator(c);
        expect(!c.texture->IsAlive());
        expect(!c.texture->IsVisible());

        "wrapper"_test = [&] {
            {
                WrapperT w{c};
                expect(c.texture->IsAlive());
                expect(!c.texture->IsVisible());
            }
            expect(!c.texture->IsAlive());
            expect(!c.texture->IsVisible());
        };

        "wrapper-copy"_test = [&] {
            {
                WrapperT w{c};
                {
                    WrapperT w2{w};
                    expect(c.texture->IsAlive());
                    expect(!c.texture->IsVisible());
                }
                expect(c.texture->IsAlive());
                expect(!c.texture->IsVisible());
            }

            expect(!c.texture->IsAlive());
            expect(!c.texture->IsVisible());
        };

        "wrapper-assign"_test = [&] {
            {
                WrapperT w{c};
                {
                    WrapperT w2{w};
                    w = w2;
                    expect(c.texture->IsAlive());
                    expect(!c.texture->IsVisible());
                }
                expect(c.texture->IsAlive());
                expect(!c.texture->IsVisible());
            }

            expect(!c.texture->IsAlive());
            expect(!c.texture->IsVisible());
        };

        using ShowT = GridLine::ChunkWrapper<&BaseTexture::SetVisible>;

        "show-copy"_test = [&] {
            {
                WrapperT w{c};
                {
                    ShowT w2{w};
                    expect(c.texture->IsAlive());
                    expect(c.texture->IsVisible());
                }
                expect(c.texture->IsAlive());
                expect(!c.texture->IsVisible());
            }

            expect(!c.texture->IsAlive());
            expect(!c.texture->IsVisible());
        };
    };
};

} //namespace;

max_issues_repo_name: sakhnik/nvim-ui


text:
#include "stdafx.h"
#include "ReorgCorrectionsSubProcessor.h"
#include <CodeCorrectionLib/Proposal/ReplaceCorrectionProposal.h>
#include "JavaCorrectionProcessor.h"
#include <JCDT_Lib/internal/problem/ErrorInfo.h>
#include <CodeAssistLib/impl/AssistInfo.h>
#include <CodeCorrectionLib/core/ProblemPosition.h>
#include <CodeCorrectionLib/Proposal/MultipleReplaceCorrectionProposal.h>
#include <JCDT_Lib/internal/util/stringex.h>
#include <JavaModelLib/compiler/BuildMsgInfo.h>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <JavaModelLib/internal/core/JavaModel.h>
#include <JavaModelLib/internal/core/OriginalJavaProject.h>
#include <CodeCorrectionLib/core/ASTResolving.h>
#include <CodeCorrectionLib/Proposal/RenameCUCompletionProposal.h>
#include <CodeCorrectionLib/Proposal/ChangeTypeNameCorrectionProposal.h>
#include <CodeCorrectionLib/core/CorrectionAssistASTVisitor.h>
#include <JCDT_Lib/internal/semantic/semantic.h>
#include <JCDT_Lib/internal/lookup/ExpandedMethodTable.h>
#include <JCDT_Lib/internal/lookup/MethodShadowSymbol.h>
#include <JCDT_Lib/internal/lookup/unitfilesymbol.h>
#include "ImportEditCtrl.h"
#include <JavaModelLib/internal/lookup/NameLookup.h>
#include <JavaModelLib/internal/core/IType.h>
#include <JavaModelLib/internal/core/IMethod.h>
#include <CodeCorrectionLib/Proposal/NewMethodCompletionProposal.h>
#include <CodeCorrectionLib/Proposal/MultipleNewMethodCorrectionProposal.h>
#include <JavaModelLib/compiler/DefaultProblem.h>
namespace Jikes { // Open namespace Jikes block

	namespace Correction {
		void ReorgCorrectionsSubProcessor::getWrongTypeNameProposals(ProblemPosition* problemPos, std::vector<CorrectionProposal*>& proposals)
		{

			if (!problemPos || !problemPos->cur_info || !problemPos->layer_pos)
				return;

			auto& _info = *(problemPos->cur_info);
			ASTResolving* resolving = new ASTResolving(_info.line, _info.column, problemPos->pJm, problemPos->layer_pos->proj, _info.doc_path);

			auto   typeNames = resolving->GetTypeNames();
			delete resolving;
			if (typeNames.empty())
				return;

			RenameCUCompletionProposal* reNameProposal = new RenameCUCompletionProposal(typeNames[0],
				problemPos->layer_pos->proj, problemPos->layer_pos->projectPos.pkg);
			reNameProposal->oldFileName = problemPos->layer_pos->projectPos.name;
			reNameProposal->path = _info.doc_path;
			reNameProposal->fDisplayString = L"rename the file to "  + typeNames[0];

			reNameProposal->icon_type = CorrectionProposal::CHANGE_ICON;
			proposals.push_back(reNameProposal);

			auto proposal = new ChangeTypeNameCorrectionProposal(problemPos->layer_pos->proj, problemPos->layer_pos->projectPos.pkg, typeNames[typeNames.size() -1]);

			proposal->newName = problemPos->layer_pos->projectPos.name;
			proposal->fDisplayString = L"Change type name to " + proposal->newName;
			proposal->icon_type = CorrectionProposal::CHANGE_ICON;
			proposals.push_back(proposal);

		}
		//
		// Pass 4: Process the field declarations at the top level of the types
		//
		void CompleteSymbolTable(ProblemPosition* problemPos, ASTResolving* resolving ,std::vector<CorrectionProposal*>& proposals)
		{
			if (!problemPos || !resolving || !resolving->lexFile || !resolving->visitor || !resolving->visitor->astNode)
				return;

			auto semantic = resolving->lexFile->semantic;

			if (!semantic)
				return;

			auto class_body = reinterpret_cast<TypeDeclaration *>(resolving->visitor->astNode)->class_body;
			if (!class_body || !class_body->owner)
				return;

			auto  unit = resolving->lexFile->compilation_unit;
			if (!unit)
				return;

			TypeSymbol* this_type = class_body->owner->symbol;

			if (!this_type)
				return;

			if (!this_type->expanded_method_table)
				semantic->ComputeMethodsClosure(this_type, class_body->identifier_token);

			if (!this_type->super || this_type->Bad())
				return;

			if (this_type->ACC_ABSTRACT())
				return;
			// We already checked that this class does not declare abstract
			// methods. Now see that there are no unimplemented abstract
			// methods in any of the superclasses or superinterfaces. Exploit
			// the fact that the method table is built with the first element
			// being from a superclass; all conflicts are inherited from
			// interfaces and are necessarily abstract.
			ExpandedMethodTable* expanded_table = this_type->expanded_method_table;

			if (!expanded_table)
				return;

			auto lex = resolving->lexFile->lex_stream;
			ImportEditCtrl* importEditCtrl = new ImportEditCtrl(lex,unit);

			int line_no;
			int column_no;
			auto tempNum = class_body->NumMethods();

			if(tempNum){

				auto methodAst = class_body->Method(tempNum - 1);
				if (!methodAst)
					return;

				auto rightToken = methodAst->RightToken();
				if (!rightToken)
					return;

				auto end_loc = rightToken->EndLocation();
				line_no = lex->LineFromPos(end_loc);
				column_no = lex->RightColumnFromPos(end_loc) + 1;

			}
			else{
				auto end_loc = class_body->right_brace_token->EndLocation();
				line_no = lex->LineFromPos(end_loc);
				column_no = lex->RightColumnFromPos(end_loc);
			}

			auto pJm = problemPos->pJm;
			if (!pJm || !problemPos->layer_pos || !this_type->file_symbol)
				return;

			wstring projectName = problemPos->layer_pos->proj;
			auto project = pJm->getJavaProject(projectName);
			JavaModel::NameLookup* namel_lookup_ = nullptr;

			auto _fileName = this_type->file_symbol->getNameString();

			if (project){
				namel_lookup_ = project->getNameLookup();
				if (namel_lookup_)
					namel_lookup_->beginToOccupy();

			}

			auto length = expanded_table->symbol_pool.Length();
			auto multiple_replace_correction = new MultipleNewMethodCorrectionProposal();
			for (auto i = 0; i < length; i++) {
				MethodSymbol* method = expanded_table->symbol_pool[i]->method_symbol;
				if (method && method->ACC_ABSTRACT())
				{
					TypeSymbol* containing_type = method->containing_type;
					if (containing_type == this_type)
						continue;

					auto  numFormalParameters = method->NumFormalParameters();

					vector<wstring> parameterNames;
					wstring containPkgName = containing_type->ContainingPackageName();
					boost::replace_all(containPkgName, L"/", L".");

					auto typeInJavaModel = namel_lookup_->findType(containing_type->sourceName('.'), containPkgName, false, JavaModel::NameLookup::ACCEPT_CLASSES | JavaModel::NameLookup::ACCEPT_INTERFACES);
					wstring selector = method->getNameString();
					if (typeInJavaModel)
					{

						vector<wstring>  parameterTypes;
						for (auto k = 0; k < numFormalParameters; k++) {
							auto  type = method->FormalParameter(k)->Type();
							wstring  compoundName = type->getCompoundName();
							boost::replace_all(compoundName, L"/", L".");
							parameterTypes.push_back(compoundName);
						}

						auto methodInJavaModel =  typeInJavaModel->getMethod(selector, parameterTypes);
						if(methodInJavaModel){
							methodInJavaModel->getNameRange();
							parameterNames = methodInJavaModel->getParameterNames();
						}
					}

					if(parameterNames.empty()){
						for (auto k = 0; k < numFormalParameters; k++) {
							Jikes::wstringex temp;
							temp.format(L"parameter_%d", k);
							parameterNames.push_back(temp);
						}
					}

					auto newMethod = new NewMethodCompletionProposal(_fileName, projectName, containPkgName);
					newMethod->access->SetFlags(*method);
					newMethod->selector = selector;
					newMethod->constructor = false;
					newMethod->paramenterNames = parameterNames;
					newMethod->isInterface = this_type->ACC_INTERFACE();
					newMethod->left_line_no = line_no;
					newMethod->left_column_no = column_no;
					newMethod->right_line_no = line_no;
					newMethod->right_column_no = column_no;

					for (auto l = 0; l < numFormalParameters; ++l) {
						TypeSymbol* arg_type = method->FormalParameter(l)->Type();
						if (!arg_type || arg_type->Bad()) {
							newMethod->formal_parameterTypes.push_back(L"Object");
						}
						else {
							auto typeName = arg_type->getNameString();
							newMethod->formal_parameterTypes.push_back(typeName);
							wstring coumpoundName = arg_type->getCompoundName();
							boost::replace_all(coumpoundName, L"/", L".");
							if (importEditCtrl->AddImportEdit(coumpoundName)) {
								auto proposal = new ReplaceCorrectionProposal(importEditCtrl->packageLineNo, 1, importEditCtrl->packageLineNo, 0);
								proposal->fReplacementString = L"import " + coumpoundName + L";\n";
								multiple_replace_correction->proposals.push_back(proposal);

							}
						}
					}
					auto returnTypeSymbol = method->Type();
					if(!returnTypeSymbol || returnTypeSymbol->Bad()){
						newMethod->returnTypeName = L"Object";
					}
					else{
						auto typeName = returnTypeSymbol->getNameString();
						newMethod->returnTypeName = typeName;
						wstring coumpoundName = returnTypeSymbol->getCompoundName();
						boost::replace_all(coumpoundName, L"/", L".");
						if (importEditCtrl->AddImportEdit(coumpoundName)) {
							auto proposal = new ReplaceCorrectionProposal(importEditCtrl->packageLineNo, 1, importEditCtrl->packageLineNo, 0);
							proposal->fReplacementString = L"import " + coumpoundName + L";\n";
							multiple_replace_correction->proposals.push_back(proposal);
						}
					}
					multiple_replace_correction->method_proposals.push_back(newMethod);
				}
			}

			if (namel_lookup_)
				namel_lookup_->endToOccupy();

			if(multiple_replace_correction->method_proposals.size()){
				proposals.push_back(multiple_replace_correction);
				multiple_replace_correction->fDisplayString = L"Generate the missing method";
			}
			else{
				delete multiple_replace_correction;
			}
			delete importEditCtrl;
		}

		void ReorgCorrectionsSubProcessor::get_NON_ABSTRACT_TYPE_INHERITS_ABSTRACT_METHOD_Proposals(ProblemPosition* problemPos,
			std::vector<CorrectionProposal*>& proposals)
		{

			if (!problemPos || !problemPos->cur_info)
				return;

			auto& _info = *(problemPos->cur_info);
			ASTResolving* resolving = new ASTResolving(_info.line, _info.column, problemPos->pJm, problemPos->layer_pos->proj, _info.doc_path);
			if (!resolving->findSelectedNode()) {
				delete resolving;
				return;
			}

			auto visitor = resolving->visitor;
			if (visitor && visitor->astNode) {
				switch (visitor->completNodeType)
				{
				case CorrectionAssistASTVisitor::CompletionOnTypeIdentifier:
				{
					resolving->BindingProcess();
					CompleteSymbolTable(problemPos ,resolving, proposals);

				}
				break;

				default:
					break;

				}
			}
			delete resolving;

		}

		void ReorgCorrectionsSubProcessor::getWrongPackageDeclNameProposals(ProblemPosition* problemPos, std::vector<CorrectionProposal*>& proposals)
		{

		}

		void ReorgCorrectionsSubProcessor::removeImportStatementProposals(
			ProblemPosition* problemPos, std::vector<CorrectionProposal*>& proposals)
		{
			if (!problemPos || !problemPos->pJm || !problemPos->layer_pos)
				return;
			Jikes::CodeAssist::AssistInfo* info = problemPos->cur_info;
			if (!info ||! info->extraData || !info->extraData->semanticError)
				return;

			auto java_project = problemPos->pJm->getJavaProject(problemPos->layer_pos->proj);
			if (!java_project)
				return;
			java_project->beginToOccupy();
			boost::shared_ptr<Jikes::JavaModel::BuildProblem > old_problem = java_project->problems[problemPos->cur_info->doc_path];
			java_project->endToOccupy();

			auto extraError = info->extraData->semanticError;

			auto replaceItem = new  ReplaceCorrectionProposal(
				extraError->left_line_no,
				extraError->left_column_no,
				extraError->right_line_no,
				extraError->right_column_no);

			replaceItem->icon_type = CorrectionProposal::REMOVE_ICON;
			replaceItem->fDisplayString = L"Remove unused import";

			proposals.push_back(replaceItem);

			auto& _data = old_problem->data;
			auto size = _data.size();
			vector<JavaModel::DefaultProblem*> unusedImport;
			for (int i = 0; i < size; i++){
				auto error = _data[i];
				if (!error)
					continue;
				auto errorInfo = reinterpret_cast<JavaModel::DefaultProblem*>(error);
				if (!JavaCorrectionProcessor::UnusedImportProblem(errorInfo->id))
					continue;
				unusedImport.emplace_back(errorInfo);
			}

			if (unusedImport.size() > 1)
			{
				auto proposal = new MultipleReplaceCorrectionProposal();
				Jikes::wstringex format;
				format.format(L"fix %d problem in the same category in file", unusedImport.size());
				proposal->fDisplayString = format;
				for (auto it : unusedImport)
				{
					replaceItem = new  ReplaceCorrectionProposal(
						it->getLeftColumnNo(),
						it->getLeftColumnNo(),
						it->getRightLineNo(),
						it->getRightColumnNo());

					proposal->proposals.push_back(replaceItem);
				}
				proposals.push_back(replaceItem);
			}

		}

		void ReorgCorrectionsSubProcessor::getMethodOverLoadProposals(ProblemPosition* problemPos, std::vector<CorrectionProposal*>& proposals)
		{
			if (!problemPos || !problemPos->cur_info || !problemPos->layer_pos)
				return;

			auto& _info = *(problemPos->cur_info);
			ASTResolving* resolving = new ASTResolving(_info.line, _info.column, problemPos->pJm, problemPos->layer_pos->proj, _info.doc_path);
			if(!resolving->findSelectedNode())
			{
				delete resolving;

			}
		}
	} // Close namespace Correction block

} // Close namespace Jikes block

max_stars_repo_name: kuafuwang/JCDT

max_issues_repo_name: kuafuwang/JCDT

max_forks_repo_name: kuafuwang/JCDT


text:
#include <v4r/features/global_alexnet_cnn_estimator.h>

#include <stdio.h>  // for snprintf
#include <string>
#include <vector>

#include <boost/algorithm/string.hpp>
#include <google/protobuf/text_format.h>

#include <caffe/blob.hpp>
#include <caffe/common.hpp>
//#include <caffe/proto/caffe.pb.h>
#include <caffe/util/db.hpp>
#include <caffe/util/io.hpp>
#include <caffe/layer.hpp>
#include <caffe/layers/memory_data_layer.hpp>
#include <caffe/net.hpp>

#include <v4r/common/img_utils.h>
#include <v4r/common/pcl_opencv.h>

using caffe::Blob;
using caffe::Caffe;
using caffe::Datum;
using caffe::Net;
using std::string;
namespace db = caffe::db;

namespace v4r
{

template<typename PointT, typename Dtype>
void
CNN_Feat_Extractor<PointT, Dtype>::WrapInputLayer(std::vector<cv::Mat>* input_channels)
{
    caffe::Blob<float>* input_layer = net_->input_blobs()[0];

    int width = input_layer->width();
    int height = input_layer->height();
    Dtype* input_data = input_layer->mutable_cpu_data();
    for (int i = 0; i < input_layer->channels(); ++i)
    {
        cv::Mat channel(height, width, CV_32FC1, input_data);
        input_channels->push_back(channel);
        input_data += width * height;
    }
}

template<typename PointT, typename Dtype>
void
CNN_Feat_Extractor<PointT, Dtype>::Preprocess(const cv::Mat& img, std::vector<cv::Mat>* input_channels) {
    /* Convert the input image to the input image format of the network. */
    cv::Mat sample;
    if (img.channels() == 3 && num_channels_ == 1)
        cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);
    else if (img.channels() == 4 && num_channels_ == 1)
        cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
    else if (img.channels() == 4 && num_channels_ == 3)
        cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
    else if (img.channels() == 1 && num_channels_ == 3)
        cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
    else
        sample = img;

    cv::Mat sample_resized;
    if (sample.size() != input_geometry_)
        cv::resize(sample, sample_resized, input_geometry_);
    else
        sample_resized = sample;

    cv::Mat sample_float;
    if (num_channels_ == 3)
        sample_resized.convertTo(sample_float, CV_32FC3);
    else
        sample_resized.convertTo(sample_float, CV_32FC1);

    cv::Mat sample_normalized;
    cv::subtract(sample_float, mean_, sample_normalized);

    /* This operation will write the separate BGR planes directly to the
   * input layer of the network because it is wrapped by the cv::Mat
   * objects in input_channels. */
    cv::split(sample_normalized, *input_channels);

    CHECK(reinterpret_cast<Dtype*>(input_channels->at(0).data)
          == net_->input_blobs()[0]->cpu_data())
            << "Input channels are not wrapping the input layer of the network.";
}

/* Load the mean file in binaryproto format. */
template<typename PointT, typename Dtype>
void
CNN_Feat_Extractor<PointT, Dtype>::SetMean(const std::string& mean_file)
{
    caffe::BlobProto blob_proto;
    ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);

    /* Convert from BlobProto to Blob<float> */
    Blob<float> mean_blob;
    mean_blob.FromProto(blob_proto);
    CHECK_EQ(mean_blob.channels(), num_channels_)
            << "Number of channels of mean file doesn't match input layer.";

    /* The format of the mean file is planar 32-bit float BGR or grayscale. */
    std::vector<cv::Mat> channels;
    float* data = mean_blob.mutable_cpu_data();
    for (int i = 0; i < num_channels_; i++)
    {
        /* Extract an individual channel. */
        cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
        channels.push_back(channel);
        data += mean_blob.height() * mean_blob.width();
    }

    /* Merge the separate channels into a single image. */
    cv::Mat mean;
    cv::merge(channels, mean);

    /* Compute the global mean pixel value and create a mean image
   * filled with this value. */
    cv::Scalar channel_mean = cv::mean(mean);
    mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);
}

template<typename PointT, typename Dtype>
int
CNN_Feat_Extractor<PointT, Dtype>::init(){

  if (strcmp(param_.device_name_.c_str(), "GPU") == 0)
  {
    Caffe::SetDevice(param_.device_id_);
    Caffe::set_mode(Caffe::GPU);
  }
  else
    Caffe::set_mode(Caffe::CPU);

  net_.reset(new Net<Dtype>(param_.feature_extraction_proto_, caffe::TEST));
  net_->CopyTrainedLayersFrom(param_.pretrained_binary_proto_);

  caffe::Blob<Dtype>* input_layer = net_->input_blobs()[0];
  num_channels_ = input_layer->channels();
  CHECK(num_channels_ == 3 || num_channels_ == 1) << "Input layer should have 1 or 3 channels.";
  input_geometry_ = cv::Size(input_layer->width(), input_layer->height());

  /* Load the binaryproto mean file. */
  SetMean(param_.input_mean_file_);
  return 0;
}

template<typename PointT, typename Dtype>
bool
CNN_Feat_Extractor<PointT, Dtype>::compute (const cv::Mat &img, Eigen::MatrixXf &signature)
{
    if(!init_)
    {
        init();
        init_ = true;
    }

    Blob<Dtype>* input_layer = net_->input_blobs()[0];
    input_layer->Reshape(1, num_channels_,
                         input_geometry_.height, input_geometry_.width);
    /* Forward dimension change to all layers. */
    net_->Reshape();

    std::vector<cv::Mat> input_channels;
    WrapInputLayer(&input_channels);

    Preprocess(img, &input_channels);

    net_->Forward();

    /* Copy the output layer to a std::vector */
//    Blob<float>* output_layer = net_->output_blobs()[0];
    boost::shared_ptr<Blob<Dtype> > output_layer = net_->blob_by_name(param_.output_layer_name_);
    const float* begin = output_layer->cpu_data();
    const float* end = begin + output_layer->channels();
    std::vector<float> sign_f = std::vector<float>(begin, end);

    signature = Eigen::MatrixXf (1, sign_f.size());

    for(size_t i=0; i<sign_f.size(); i++)
        signature(0,i) = sign_f[i];

    indices_.clear();
    cloud_.reset();
    return true;
}

template<typename PointT, typename Dtype>
bool
CNN_Feat_Extractor<PointT, Dtype>::compute (Eigen::MatrixXf &signature)
{
    CHECK( cloud_ && cloud_->isOrganized() && !cloud_->points.empty() && !indices_.empty());
    PCLOpenCVConverter<PointT> pcl_opencv_converter;
    pcl_opencv_converter.setInputCloud(cloud_);
    pcl_opencv_converter.setIndices(indices_);
    pcl_opencv_converter.setBackgroundColor( param_.background_color_(0), param_.background_color_(1), param_.background_color_(2) );
    pcl_opencv_converter.setRemoveBackground( param_.remove_background_ );
    cv::Mat img = pcl_opencv_converter.getRGBImage();
    cv::Rect roi = pcl_opencv_converter.getROI();
    cv::Mat img_cropped = cropImage(img, roi, param_.margin_, true);

    std::cerr << "Closing operation not implemented right now!" << std::endl;   ///TODO: re-implement closing operation to avoid sharp transitions from noisy measurements

    compute(img_cropped, signature);
    indices_.clear();
    return true;
}
    template class V4R_EXPORTS CNN_Feat_Extractor<pcl::PointXYZRGB>;
}


text:
#include <ozo/query_builder.h>

#include <boost/hana/size.hpp>

#include <limits>

#include <gtest/gtest.h>
#include <gmock/gmock.h>

namespace {

namespace hana = boost::hana;

TEST(detail_to_string, with_0_returns_0_s) {
    using namespace hana::literals;
    EXPECT_EQ(ozo::detail::to_string(hana::size_c<0>), "0"_s);
}

TEST(detail_to_string, with_one_digit_number_returns_string_with_same_digit) {
    using namespace hana::literals;
    EXPECT_EQ(ozo::detail::to_string(hana::size_c<7>), "7"_s);
}

TEST(detail_to_string, with_two_digits_number_returns_string_with_digits_in_same_order) {
    using namespace hana::literals;
    EXPECT_EQ(ozo::detail::to_string(hana::size_c<42>), "42"_s);
}

TEST(query_builder_text, with_one_text_element_returns_input) {
    using namespace ozo::literals;
    using namespace hana::literals;
    EXPECT_EQ("SELECT 1"_SQL.text(), "SELECT 1"_s);
}

TEST(query_builder_text, with_two_text_elements_returns_concatenation) {
    using namespace ozo::literals;
    using namespace hana::literals;
    EXPECT_EQ(("SELECT 1"_SQL + " + 1"_SQL).text(), "SELECT 1 + 1"_s);
}

TEST(query_builder_text, with_text_and_int32_param_elements_returns_text_with_placeholder_for_param) {
    using namespace ozo::literals;
    using namespace hana::literals;
    EXPECT_EQ(("SELECT "_SQL + std::int32_t(42)).text(), "SELECT $1"_s);
}

TEST(query_builder_text, with_text_and_two_int32_params_elements_returns_text_with_placeholders_for_each_param) {
    using namespace ozo::literals;
    using namespace hana::literals;
    EXPECT_EQ(("SELECT "_SQL + std::int32_t(42) + " + "_SQL + std::int32_t(42)).text(), "SELECT $1 + $2"_s);
}

TEST(query_builder_text, with_std_string_text_returns_string_text) {
    EXPECT_EQ(ozo::make_query_builder(hana::make_tuple(ozo::make_query_text(std::string("SELECT 1")))).text(), "SELECT 1");
}

TEST(query_builder_text, with_std_string_text_and_params_returns_string_text_with_with_placeholders_for_each_param) {
    EXPECT_EQ((ozo::make_query_text(std::string("SELECT ")) + std::int32_t(42)
                + ozo::make_query_text(std::string(" + ")) + std::int32_t(42)).text(), "SELECT $1 + $2");
}

TEST(query_builder_params, with_one_text_element_returns_empty_tuple) {
    using namespace ozo::literals;
    EXPECT_EQ("SELECT 1"_SQL.params(), hana::tuple<>());
}

TEST(query_builder_params, with_text_and_int32_param_elements_returns_tuple_with_one_value) {
    using namespace ozo::literals;
    EXPECT_EQ(("SELECT "_SQL + std::int32_t(42)).params(), hana::make_tuple(std::int32_t(42)));
}

TEST(query_builder_params, with_text_and_not_null_pointer_param_elements_returns_tuple_with_one_value) {
    using namespace ozo::literals;
    const auto ptr = std::make_unique<std::int32_t>(42);
    const auto params = ("SELECT "_SQL + ptr.get()).params();
    EXPECT_EQ(*params[hana::size_c<0>], std::int32_t(42));
}

} // namespace

namespace ozo::tests {

struct some_type {
    std::size_t size() const {
        return 1000;
    }
};

} // namespace ozo::tests

OZO_PG_DEFINE_CUSTOM_TYPE(ozo::tests::some_type, "some_type")

namespace {

using namespace ozo::tests;

TEST(query_builder_build, with_one_text_element_returns_query_with_text_equal_to_input) {
    using namespace ozo::literals;
    EXPECT_EQ(std::string_view(hana::to<const char*>("SELECT 1"_SQL.build().text)),
        "SELECT 1");
}

TEST(query_builder_build, with_one_text_element_returns_query_without_params) {
    using namespace ozo::literals;
    EXPECT_EQ("SELECT 1"_SQL.build().params, hana::tuple<>());
}

TEST(query_builder_build, with_text_and_int32_param_elements_return_query_with_1_param) {
    using namespace ozo::literals;
    EXPECT_EQ(("SELECT "_SQL + std::int32_t(42)).build().params, hana::make_tuple(42));
}

TEST(query_builder_build, with_text_and_reference_wrapper_param_element_returns_query_with_1_param) {
    using namespace ozo::literals;
    const auto value = 42.13f;
    EXPECT_EQ(("SELECT "_SQL + std::cref(value)).build().params, hana::make_tuple(std::cref(value)));
}

TEST(query_builder_build, with_text_and_ref_to_not_null_std_unique_ptr_param_element_returns_query_with_1_param) {
    using namespace ozo::literals;
    const auto ptr = std::make_unique<float>(42.13f);
    const auto params = ("SELECT "_SQL + std::cref(ptr)).build().params;
    EXPECT_EQ(decltype(hana::size(params))::value, 1u);
}

TEST(query_builder_build, with_text_and_not_null_std_shared_ptr_param_element_returns_query_with_1_param) {
    using namespace ozo::literals;
    const auto ptr = std::make_shared<float>(42.13f);
    const auto params = ("SELECT "_SQL + ptr).build().params;
    EXPECT_EQ(decltype(hana::size(params))::value, 1u);
}

TEST(query_builder_build, with_text_and_custom_type_param_element_returns_query_with_1_param) {
    using namespace ozo::literals;
    const auto params = ("SELECT "_SQL + some_type {}).build().params;
    EXPECT_EQ(decltype(hana::size(params))::value, 1u);
}

using namespace ozo::literals;
using namespace hana::literals;

constexpr auto query = "SELECT "_SQL + 42 + " + "_SQL + 13;

static_assert(query.text() == "SELECT $1 + $2"_s,
              "query_builder should generate text in compile time");

static_assert(query.params() == hana::tuple<int, int>(42, 13),
              "query_builder should generate params in compile time");

} // namespace

max_stars_repo_name: georgthegreat/ozo

max_issues_repo_name: georgthegreat/ozo

max_forks_repo_name: georgthegreat/ozo


text:
/*
 *
 * Copyright (c) 2002, 2003 Kresimir Fresl, Toon Knapen and Karl Meerbergen
 *
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * KF acknowledges the support of the Faculty of Civil Engineering,
 * University of Zagreb, Croatia.
 *
 */

#ifndef BOOST_NUMERIC_BINDINGS_TRAITS_H
#define BOOST_NUMERIC_BINDINGS_TRAITS_H

#include <boost/numeric/bindings/traits/vector_traits.hpp>
#include <boost/numeric/bindings/traits/matrix_traits.hpp>

#endif

max_stars_repo_name: diku-dk/PROX

max_issues_repo_name: jdsika/holy

max_forks_repo_name: jdsika/holy


text:
// Copyright 2021 Peter Dimov
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt

#include <boost/describe/detail/config.hpp>

#if !defined(BOOST_DESCRIBE_CXX14)

#error "Describe requires C++14"

#endif // !defined(BOOST_DESCRIBE_CXX14)


text:
//
// OpenTissue, A toolbox for physical based simulation and animation.
// Copyright (C) 2007 Department of Computer Science, University of Copenhagen
//
#include <OpenTissue/configuration.h>

#include <OpenTissue/core/math/math_basic_types.h>
#include <OpenTissue/core/geometry/geometry_barycentric.h>

#define BOOST_AUTO_TEST_MAIN
#include <OpenTissue/utility/utility_push_boost_filter.h>
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>
#include <OpenTissue/utility/utility_pop_boost_filter.h>

BOOST_AUTO_TEST_SUITE(opentissue_geometry_util_compute_distance_to_triangle);

BOOST_AUTO_TEST_CASE(inside_simplex_testing)
{
  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;
  typedef math_types::vector3_type                         V;
  typedef math_types::real_type                            T;

  V const a = V( 0.0, 0.0, 0.0);
  V const b = V(-1.0, 0.0, 0.0);
  V const c = V( 0.0, 1.0, 0.0);
  V const d = V( -2.0, -2.0, 1.0);

  // Test barycentric coordinates of a point lying on an edge
  {
    for(size_t i = 0;i<100;++i)
    {
      T WA = i*0.01;
      T WB = 1.0 - WA;
      V const p = WA*a + WB*b;
      T wa = 10.0;
      T wb = 10.0;
      OpenTissue::geometry::barycentric_geometric( a, b, p, wa, wb );
      BOOST_CHECK_CLOSE(wa, WA, 0.01 );
      BOOST_CHECK_CLOSE(wb, WB, 0.01 );
    }
  }
  // Test barycentric coordinates of a point lying on a triangle
  {
    for(size_t i = 1;i<10;++i)
    for(size_t j = 1;j<10;++j)
    for(size_t k = 1;k<10;++k)
    {
      T WA = i*0.1;
      T WB = j*0.1;
      T WC = k*0.1;
      T W = WA + WB + WC;
      WA /= W;
      WB /= W;
      WC /= W;
      V const p = WA*a + WB*b + WC*c;
      T wa = 10.0;
      T wb = 10.0;
      T wc = 10.0;
      // geometric method
      OpenTissue::geometry::barycentric_geometric( a, b, c, p, wa, wb, wc );
      BOOST_CHECK_CLOSE(wa, WA, 0.01 );
      BOOST_CHECK_CLOSE(wb, WB, 0.01 );
      BOOST_CHECK_CLOSE(wc, WC, 0.01 );

      wa = 10.0;
      wb = 10.0;
      wc = 10.0;
      // algebraic method
      OpenTissue::geometry::barycentric_algebraic( a, b, c, p, wa, wb, wc );
      BOOST_CHECK_CLOSE(wa, WA, 0.01 );
      BOOST_CHECK_CLOSE(wb, WB, 0.01 );
      BOOST_CHECK_CLOSE(wc, WC, 0.01 );

    }
  }
  // Test barycentric coordinates of a point lying in a tetrahedron
  {
    for(size_t i = 1;i<10;++i)
    for(size_t j = 1;j<10;++j)
    for(size_t k = 1;k<10;++k)
    for(size_t m = 1;m<10;++m)
    {
      T WA = i*0.1;
      T WB = j*0.1;
      T WC = k*0.1;
      T WD = m*0.1;
      T W = WA + WB + WC + WD;
      WA /= W;
      WB /= W;
      WC /= W;
      WD /= W;
      V const p = WA*a + WB*b + WC*c+ WD*d;
      T wa = 10.0;
      T wb = 10.0;
      T wc = 10.0;
      T wd = 10.0;
      // Geometric method
      OpenTissue::geometry::barycentric_geometric( a, b, c, d, p, wa, wb, wc, wd );
      BOOST_CHECK_CLOSE(wa, WA, 0.01 );
      BOOST_CHECK_CLOSE(wb, WB, 0.01 );
      BOOST_CHECK_CLOSE(wc, WC, 0.01 );
      BOOST_CHECK_CLOSE(wd, WD, 0.01 );

      wa = 10.0;
      wb = 10.0;
      wc = 10.0;
      wd = 10.0;
      // algebraic method
      OpenTissue::geometry::barycentric_algebraic( a, b, c, d, p, wa, wb, wc, wd );
      BOOST_CHECK_CLOSE(wa, WA, 0.01 );
      BOOST_CHECK_CLOSE(wb, WB, 0.01 );
      BOOST_CHECK_CLOSE(wc, WC, 0.01 );
      BOOST_CHECK_CLOSE(wd, WD, 0.01 );
    }
  }

}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: ricortiz/OpenTissue

max_issues_repo_name: ricortiz/OpenTissue

max_forks_repo_name: ricortiz/OpenTissue


text:
/**
 ** Copyright (c) 2014 Illumina, Inc.
 **
 ** This file is part of Illumina's Enhanced Artificial Genome Engine (EAGLE),
 ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file)
 **
 ** \description Component to read/write text files (specific protocols to be derived from here).
 **
 ** \author Mauricio Varea
 **/

#include <algorithm>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>

#include "io/Text.hh"
#include "common/Exceptions.hh"
#include "common/Logger.hh"

namespace eagle
{
namespace io
{

DsvReader::DsvReader(const std::vector<boost::filesystem::path> &pathList)
: pathList_(pathList)
, thisPath_(pathList_.begin())
, lineCount_(0)
{
    if (pathList.size() > 0)
    {
        openFirstFile();
    }
}

DsvReader::DsvReader(const boost::filesystem::path &path)
: pathList_(std::vector<boost::filesystem::path>(1,path))
, thisPath_(pathList_.begin())
, lineCount_(0)
{
    openFirstFile();
}

void DsvReader::openFirstFile()
{
    open(thisPath_->string().c_str());
    if (!is_open())
    {
        BOOST_THROW_EXCEPTION(eagle::common::IoException(errno, (boost::format("Failed to open file %s for reading") % *thisPath_).str()));
    }
}

bool DsvReader::openNextFile()
{
    close();
    if (pathList_.end() != thisPath_)
    {
        ++thisPath_;
    }
    if (pathList_.end() != thisPath_)
    {
        open(thisPath_->string().c_str());
        lineCount_ = 0;
    }
    return is_open();
}

std::string DsvReader::getNextLine(char comment)
{
    std::string line;
    do {
        std::getline(*this,line);
        while (fail())
        {
            if (openNextFile())
            {
                std::getline(*this,line);
            }
            else
            {
                EAGLE_WARNING_IF( pathList_.end() != thisPath_,
                                  (boost::format("Could not read beyond %s:%lu") % *(thisPath_ - 1) % lineCount_ ).str() );
                return "";
            }
        }
        ++lineCount_;
    } while (line.empty() || comment == line[0]);
    return line;
}

void DsvWriter::open(unsigned int i)
{
    close();
    if (i >= pathList_.size())
    {
        BOOST_THROW_EXCEPTION(common::PreConditionException( (boost::format("Tried to open stream #%d, but only %d files were provided")
                                                           % (i + 1) % pathList_.size()).str()) );
    }
    thisPath_ = pathList_.begin() + i;
    if ( boost::filesystem::exists(*thisPath_) )
    {
        if (overwrite_)
        {
            EAGLE_WARNING( "Overwriting " << *thisPath_ << " due to the --force switch." );
        } else {
            BOOST_THROW_EXCEPTION(common::IoException(errno, (boost::format("Cannot write to %s: File already exists!") % *thisPath_).str()));
        }
    }
    std::ofstream::open(thisPath_->string().c_str(),std::ios_base::out | std::ios_base::trunc);
    if (!std::ofstream::is_open())
    {
        BOOST_THROW_EXCEPTION(eagle::common::IoException(errno, (boost::format("Failed to open file %s for writing") % *thisPath_).str()));
    }
}

} // namespace io
} // namespace eagle

max_stars_repo_name: sequencing/EAGLE

max_issues_repo_name: sequencing/EAGLE

max_forks_repo_name: sequencing/EAGLE


text:
#include "common/string_util.h"
#include "cryptonote_config.h"
#include "cryptonote_basic/hardfork.h"
#include "common/oxen.h"
#include "epee/int-util.h"
#include <oxenc/endian.h>
#include <limits>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <cfenv>

#include "oxen_economy.h"
#include "service_node_rules.h"

using cryptonote::hf;

namespace service_nodes {

uint64_t get_staking_requirement(cryptonote::network_type nettype, hf hardfork)
{
  assert(hardfork >= hf::hf16_pulse);
  return nettype == cryptonote::network_type::MAINNET
    ? oxen::STAKING_REQUIREMENT
    : oxen::STAKING_REQUIREMENT_TESTNET;
}

// TODO(oxen): Move to oxen_economy, this will also need access to oxen::exp2
uint64_t get_staking_requirement(cryptonote::network_type nettype, uint64_t height)
{
  if (nettype != cryptonote::network_type::MAINNET)
      return oxen::STAKING_REQUIREMENT_TESTNET;

  if (is_hard_fork_at_least(nettype, hf::hf16_pulse, height))
    return oxen::STAKING_REQUIREMENT;

  if (is_hard_fork_at_least(nettype, hf::hf13_enforce_checkpoints, height))
  {
    constexpr int64_t heights[] = {
        385824,
        429024,
        472224,
        515424,
        558624,
        601824,
        645024,
    };

    constexpr int64_t lsr[] = {
        20458'380815527,
        19332'319724305,
        18438'564443912,
        17729'190407764,
        17166'159862153,
        16719'282221956,
        16364'595203882,
    };

    assert(static_cast<int64_t>(height) >= heights[0]);
    constexpr uint64_t LAST_HEIGHT      = heights[oxen::array_count(heights) - 1];
    constexpr uint64_t LAST_REQUIREMENT = lsr    [oxen::array_count(lsr) - 1];
    if (height >= LAST_HEIGHT)
        return LAST_REQUIREMENT;

    size_t i = 0;
    for (size_t index = 1; index < oxen::array_count(heights); index++)
    {
      if (heights[index] > static_cast<int64_t>(height))
      {
        i = (index - 1);
        break;
      }
    }

    int64_t H      = height;
    int64_t result = lsr[i] + (H - heights[i]) * ((lsr[i + 1] - lsr[i]) / (heights[i + 1] - heights[i]));
    return static_cast<uint64_t>(result);
  }

  uint64_t hardfork_height = 101250;
  if (height < hardfork_height) height = hardfork_height;

  uint64_t height_adjusted = height - hardfork_height;
  uint64_t base = 0, variable = 0;
  std::fesetround(FE_TONEAREST);
  if (is_hard_fork_at_least(nettype, hf::hf11_infinite_staking, height))
  {
    base     = 15000 * oxen::COIN;
    variable = (25007.0 * oxen::COIN) / oxen::exp2(height_adjusted/129600.0);
  }
  else
  {
    base      = 10000 * oxen::COIN;
    variable  = (35000.0 * oxen::COIN) / oxen::exp2(height_adjusted/129600.0);
  }

  uint64_t result = base + variable;
  return result;
}

uint64_t portions_to_amount(uint64_t portions, uint64_t staking_requirement)
{
  return mul128_div64(staking_requirement, portions, cryptonote::old::STAKING_PORTIONS);
}

bool check_service_node_portions(hf hf_version, const std::vector<std::pair<cryptonote::account_public_address, uint64_t>>& portions)
{
  // When checking portion we always use HF18 rules, even on HF19, because a registration actually
  // generated under HF19+ won't get here.
  if (hf_version == hf::hf19_reward_batching)
    hf_version = hf::hf18;
  else if (hf_version > hf::hf19_reward_batching)
  {
    LOG_PRINT_L1("Registration tx rejected: portions-based registrations not permitted after HF19");
    return false;
  }
  if (portions.size() > oxen::MAX_CONTRIBUTORS_V1) {
    LOG_PRINT_L1("Registration tx rejected: too many contributors (" << portions.size() << " > " << oxen::MAX_CONTRIBUTORS_V1 << ")");
    return false;
  }

  uint64_t reserved = 0;
  uint64_t remaining = cryptonote::old::STAKING_PORTIONS;
  for (size_t i = 0; i < portions.size(); ++i)
  {

    const uint64_t min_portions = get_min_node_contribution(hf_version, cryptonote::old::STAKING_PORTIONS, reserved, i);
    if (portions[i].second < min_portions) {
      LOG_PRINT_L1("Registration tx rejected: portion " << i << " too small (" << portions[i].second << " < " << min_portions << ")");
      return false;
    }
    if (portions[i].second > remaining) {
      LOG_PRINT_L1("Registration tx rejected: portion " << i << " exceeds available portions");
      return false;
    }

    reserved += portions[i].second;
    remaining -= portions[i].second;
  }

  return true;
}

bool check_service_node_stakes(hf hf_version, cryptonote::network_type nettype, uint64_t staking_requirement, const std::vector<std::pair<cryptonote::account_public_address, uint64_t>>& stakes)
{
  if (hf_version < hf::hf19_reward_batching) {
    LOG_PRINT_L1("Registration tx rejected: amount-based registrations not accepted before HF19");
    return false; // OXEN-based registrations not accepted before HF19
  }
  if (stakes.size() > oxen::MAX_CONTRIBUTORS_HF19) {
    LOG_PRINT_L1("Registration tx rejected: too many contributors (" << stakes.size() << " > " << oxen::MAX_CONTRIBUTORS_HF19 << ")");
    return false;
  }

  const auto operator_requirement = nettype == cryptonote::network_type::MAINNET
    ? oxen::MINIMUM_OPERATOR_CONTRIBUTION
    : oxen::MINIMUM_OPERATOR_CONTRIBUTION_TESTNET;

  uint64_t reserved = 0;
  uint64_t remaining = staking_requirement;
  for (size_t i = 0; i < stakes.size(); i++) {
    const uint64_t min_stake = i == 0 ? operator_requirement : get_min_node_contribution(hf_version, staking_requirement, reserved, i);

    if (stakes[i].second < min_stake) {
      LOG_PRINT_L1("Registration tx rejected: stake " << i << " too small (" << stakes[i].second << " < " << min_stake << ")");
      return false;
    }
    if (stakes[i].second > remaining) {
      LOG_PRINT_L1("Registration tx rejected: stake " << i << " (" << stakes[i].second << ") exceeds available remaining stake (" << remaining << ")");
      return false;
    }

    reserved += stakes[i].second;
    remaining -= stakes[i].second;
  }

  return true;
}

crypto::hash generate_request_stake_unlock_hash(uint32_t nonce)
{
  static_assert(sizeof(crypto::hash) == 8 * sizeof(uint32_t) && alignof(crypto::hash) >= alignof(uint32_t));
  crypto::hash result;
  oxenc::host_to_little_inplace(nonce);
  for (size_t i = 0; i < 8; i++)
    reinterpret_cast<uint32_t*>(result.data)[i] = nonce;
  return result;
}

uint64_t get_locked_key_image_unlock_height(cryptonote::network_type nettype, uint64_t node_register_height, uint64_t curr_height)
{
  uint64_t blocks_to_lock = staking_num_lock_blocks(nettype);
  uint64_t result         = curr_height + (blocks_to_lock / 2);
  return result;
}

static uint64_t get_min_node_contribution_pre_v11(uint64_t staking_requirement, uint64_t total_reserved)
{
  return std::min(staking_requirement - total_reserved, staking_requirement / oxen::MAX_CONTRIBUTORS_V1);
}

uint64_t get_max_node_contribution(hf version, uint64_t staking_requirement, uint64_t total_reserved)
{
  if (version >= hf::hf16_pulse)
    return (staking_requirement - total_reserved) * cryptonote::MAXIMUM_ACCEPTABLE_STAKE::num
      / cryptonote::MAXIMUM_ACCEPTABLE_STAKE::den;
  return std::numeric_limits<uint64_t>::max();
}

uint64_t get_min_node_contribution(hf version, uint64_t staking_requirement, uint64_t total_reserved, size_t num_contributions)
{
  if (version < hf::hf11_infinite_staking)
    return get_min_node_contribution_pre_v11(staking_requirement, total_reserved);

  const uint64_t needed = staking_requirement - total_reserved;

  const size_t max_contributors = version >= hf::hf19_reward_batching ? oxen::MAX_CONTRIBUTORS_HF19 : oxen::MAX_CONTRIBUTORS_V1;
  if (max_contributors <= num_contributions) return UINT64_MAX;

  const size_t num_contributions_remaining_avail = max_contributors - num_contributions;
  return needed / num_contributions_remaining_avail;
}

uint64_t get_min_node_contribution_in_portions(hf version, uint64_t staking_requirement, uint64_t total_reserved, size_t num_contributions)
{
  uint64_t atomic_amount = get_min_node_contribution(version, staking_requirement, total_reserved, num_contributions);
  uint64_t result        = (atomic_amount == UINT64_MAX) ? UINT64_MAX : (get_portions_to_make_amount(staking_requirement, atomic_amount));
  return result;
}

uint64_t get_portions_to_make_amount(uint64_t staking_requirement, uint64_t amount, uint64_t max_portions)
{
  uint64_t lo, hi, resulthi, resultlo;
  lo = mul128(amount, max_portions, &hi);
  if (lo > UINT64_MAX - (staking_requirement - 1))
    hi++;
  lo += staking_requirement-1;
  div128_64(hi, lo, staking_requirement, &resulthi, &resultlo);
  return resultlo;
}

static bool get_portions_from_percent(double cur_percent, uint64_t& portions) {
  if(cur_percent < 0.0 || cur_percent > 100.0) return false;

  // Fix for truncation issue when operator cut = 100 for a pool Service Node.
  if (cur_percent == 100.0)
  {
    portions = cryptonote::old::STAKING_PORTIONS;
  }
  else
  {
    portions = (cur_percent / 100.0) * (double)cryptonote::old::STAKING_PORTIONS;
  }

  return true;
}

std::optional<double> parse_fee_percent(std::string_view fee)
{
  if (tools::ends_with(fee, "%"))
    fee.remove_suffix(1);

  double percent;
  try {
    percent = boost::lexical_cast<double>(fee);
  } catch(...) {
    return std::nullopt;
  }

  if (percent < 0 || percent > 100)
    return std::nullopt;

  return percent;
}

bool get_portions_from_percent_str(std::string cut_str, uint64_t& portions) {

  if (auto pct = parse_fee_percent(cut_str))
    return get_portions_from_percent(*pct, portions);

  return false;
}

} // namespace service_nodes

max_stars_repo_name: loki-project/loki

max_issues_repo_name: loki-project/loki

max_forks_repo_name: loki-project/loki


text:
#include "UniversalRobots.hpp"

#include <rw/common/PropertyMap.hpp>
#include <rw/loaders/xml/XMLPropertyLoader.hpp>
#include <rw/loaders/WorkCellLoader.hpp>
#include <boost/bind.hpp>

using namespace rwhw;
using namespace rw::common;
using namespace rw::loaders;
using namespace rw::models;
using namespace rw::kinematics;

int main(int argc, char **argv)
{
	if (argc <= 2) {
		std::cout<<"Usage: ursafe <workcell> <propertyfile.prop.xml>"<<std::endl;
		return 0;
	}

	WorkCell::Ptr workcell = WorkCellLoader::load(argv[1]);
	if (workcell == NULL) {
		std::cout<<"Unable to load workcell: "<<argv[1]<<std::endl;
		return 0;
	}

	PropertyMap properties = XMLPropertyLoader::load(argv[2]);

	if (!properties.has("Name")) {
		std::cout<<"No property named 'Name' found in property file"<<std::endl;
		return 0;
	}

	std::string deviceName = properties.get<std::string>("Name");
	Device::Ptr dev = workcell->findDevice(deviceName);
	if (dev == NULL) {
		std::cout<<"Unable to find device "<<deviceName<<" in work cell"<<std::endl;
		return 0;
	}

	ros::init(argc, argv, properties.get<std::string>("Name").c_str());

	std::string host = properties.get<std::string>("NetFTHost");
	int updateRate = properties.get<int>("NetFTUpdateRate");

	std::string calibfile = properties.get<std::string>("NetFTCalibrationFile");
	std::cout<<"Calibration File = "<<calibfile<<std::endl;
	NetFTLogging netft(host);

	FTCompensation ftCompensation(dev, workcell->getDefaultState(), calibfile);

    UniversalRobots ur(workcell, properties, updateRate, &netft, &ftCompensation);

    ur.run();

//  while (ros::ok())
//  {
//    /**
//     * This is a message object. You stuff it with data, and then publish it.
//     */
//    sensor_data msg;
//
//    std::stringstream ss;
//    ss << "hello";// << count;
//    msg.name = ss.str();
//
//    ROS_INFO("%s", msg.name.c_str());
//
//    /**
//     * The publish() function is how you send messages. The parameter
//     * is the message object. The type of this object must agree with the type
//     * given as a template parameter to the advertise<>() call, as was done
//     * in the constructor above.
//     */
//    chatter_pub.publish(msg);
//
//    ros::spinOnce();
//
//    loop_rate.sleep();
//    ++count;
//  }

    return 0;
}