text:
// -*- mode: c++; indent-tabs-mode: nil; tab-width:2  -*-
// (c) 2007-2013 Ulrich Germann
#include <sstream>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <stdexcept>

#include <boost/pool/pool_alloc.hpp>

#include "tpt_tokenindex.h"
#include "ug_typedefs.h"

using namespace std;
namespace sapt
{

  TokenIndex::
  TokenIndex(string unkToken)
    : ridx(0), unkLabel(unkToken), unkId(1), numTokens(0)
    , startIdx(0), endIdx(0)
  {
    lock.reset(new boost::mutex());
  };

#if 0
  TokenIndex::
  TokenIndex(string fname, string unkToken,bool dyna)
    : ridx(0),unkLabel(unkToken)
  {
    this->open(fname,unkToken,dyna);
  };
#endif

  void
  TokenIndex::
  open(string fname, string unkToken,bool dyna)
  {
    if (access(fname.c_str(),F_OK))
      {
        ostringstream msg;
        msg << "TokenIndex::open: File '" << fname << "' does not exist.";
        throw std::runtime_error(msg.str().c_str());
      }

    file.open(fname);
    if (!file.is_open())
      {
        ostringstream msg;
        msg << "TokenIndex::open: Error opening file '" << fname << "'.";
        throw std::runtime_error(msg.str().c_str());
      }

    this->numTokens = *(reinterpret_cast<uint32_t const*>(file.data()));
    unkId = *(reinterpret_cast<id_type const*>(file.data()+4));

    startIdx = reinterpret_cast<Entry const*>(file.data()+4+sizeof(id_type));
    endIdx   = startIdx + numTokens;
    comp.base = reinterpret_cast<char const*>(endIdx);
    if (!unkToken.empty())
      {
        Entry const* bla = lower_bound(startIdx,endIdx,unkToken.c_str(),comp);
        unkId = ((bla < endIdx && unkToken == comp.base+bla->offset)
                 ? bla->id
                 : numTokens);
      }
    this->dynamic=dyna;
    if (dyna)
      {
        this->str2idExtra.reset(new map<string,id_type>());
        this->newWords.reset(new vector<string>());
      }
  }

  void
  TokenIndex::
  close()
  {
    file.close();
  }

  TokenIndex::
  CompFunc::
  CompFunc()
  {};

  bool
  TokenIndex::
  CompFunc::
  operator()(Entry const& A, char const* w)
  {
    return strcmp(base+A.offset,w) < 0;
  };

  id_type
  TokenIndex::
  operator[](char const* p) const
  {
    if (startIdx != endIdx)
      {
        Entry const* bla = lower_bound(startIdx,endIdx,p,comp);
        if (bla != endIdx && !strcmp(comp.base+bla->offset,p))
          return bla->id;
        if (!dynamic) return unkId;
      }
    else if (!dynamic) return strcmp(p,"NULL") && unkId;

    boost::lock_guard<boost::mutex> lk(*this->lock);
    // stuff below is new as of 2011-01-30, for dynamic adding of
    // unknown items IMPORTANT: numTokens is not currently not
    // changed, it is the number of PRE-EXISING TOKENS, not including
    // dynamically added Items
    // if (!str2idExtra)
    //   {
    //     this->str2idExtra.reset(new map<string,id_type>());
    //     this->newWords.reset(new vector<string>());
    //   }
    map<string,id_type>::value_type newItem(p,str2idExtra->size()+numTokens);
    pair<map<string,id_type>::iterator,bool> foo = str2idExtra->insert(newItem);
    if (foo.second) // it actually is a new item
      newWords->push_back(foo.first->first);
    return foo.first->second;
  }

  id_type
  TokenIndex::
  operator[](string const& w) const
  {
    return (*this)[w.c_str()];
  }

  vector<char const*>
  TokenIndex::
  reverseIndex() const
  {
    size_t numToks = endIdx-startIdx;

    // cout << "tokenindex has " << numToks << " tokens" << endl;

    vector<char const*> v(numToks,NULL);
    // v.reserve(endIdx-startIdx);
    for (Entry const* x = startIdx; x != endIdx; x++)
      {
	if (x->id >= v.size())
	  v.resize(x->id+1);
	v[x->id] = comp.base+x->offset;
      }
    // cout << "done reversing index " << endl;
    return v;
  }

  char const* const
  TokenIndex::
  operator[](id_type id) const
  {
    if (!ridx.size())
      {
        boost::lock_guard<boost::mutex> lk(*this->lock);
        // Someone else (multi-threading!) may have created the
        // reverse index in the meantime, so let's check again
        if (!ridx.size()) ridx = reverseIndex();
      }
    if (id < ridx.size())
      return ridx[id];

    boost::lock_guard<boost::mutex> lk(*this->lock);
    if (dynamic && id < ridx.size()+newWords->size())
      return (*newWords)[id-ridx.size()].c_str();
    return unkLabel.c_str();
  }

  void
  TokenIndex::
  iniReverseIndex()
  {
    if (!ridx.size())
      {
        boost::lock_guard<boost::mutex> lk(*this->lock);
        if (!ridx.size()) ridx = reverseIndex();
      }
  }

  char const* const
  TokenIndex::
  operator[](id_type id)
  {
    if (!ridx.size())
      {
        boost::lock_guard<boost::mutex> lk(*this->lock);
        if (!ridx.size()) ridx = reverseIndex();
      }
    if (id < ridx.size())
      return ridx[id];
    boost::lock_guard<boost::mutex> lk(*this->lock);
    if (dynamic && id < ridx.size()+newWords->size())
      return (*newWords)[id-ridx.size()].c_str();
    return unkLabel.c_str();
  }

  string
  TokenIndex::
  toString(vector<id_type> const& v)
  {
    if (!ridx.size())
      {
        boost::lock_guard<boost::mutex> lk(*this->lock);
        if (!ridx.size()) ridx = reverseIndex();
      }
    ostringstream buf;
    for (size_t i = 0; i < v.size(); i++)
      buf << (i ? " " : "") << (*this)[v[i]];
    return buf.str();
  }

  string
  TokenIndex::
  toString(vector<id_type> const& v) const
  {
    if (!ridx.size())
      {
        boost::lock_guard<boost::mutex> lk(*this->lock);
        if (!ridx.size()) ridx = reverseIndex();
      }
    ostringstream buf;
    for (size_t i = 0; i < v.size(); i++)
      buf << (i ? " " : "") << (*this)[v[i]];
    return buf.str();
  }

  string
  TokenIndex::
  toString(id_type const* start, id_type const* const stop)
  {
    if (!ridx.size())
      {
        boost::lock_guard<boost::mutex> lk(*this->lock);
        if (!ridx.size()) ridx = reverseIndex();
      }
    ostringstream buf;
    if (start < stop)
      buf << (*this)[*start];
    while (++start < stop)
      buf << " " << (*this)[*start];
    return buf.str();
  }

  string
  TokenIndex::
  toString(id_type const* start, id_type const* const stop) const
  {
    if (!ridx.size())
      {
        boost::lock_guard<boost::mutex> lk(*this->lock);
        if (!ridx.size()) ridx = reverseIndex();
      }
    ostringstream buf;
    if (start < stop)
      buf << (*this)[*start];
    while (++start < stop)
      buf << " " << (*this)[*start];
    return buf.str();
  }

  vector<id_type>
  TokenIndex::
  toIdSeq(string const& line) const
  {
    istringstream buf(line);
    string w;
    vector<id_type> retval;
    while (buf>>w)
      retval.push_back((*this)[w]);
    return retval;
  }

  /// Return false if line contains unknown tokens, true otherwise
  bool
  TokenIndex::
  fillIdSeq(string const& line, vector<id_type> & v) const
  {
    bool allgood = true; string w;
    v.clear();
    for (istringstream buf(line); buf>>w;)
      {
        v.push_back((*this)[w]);
        allgood = allgood && v.back() > 1;
      }
    return allgood;
  }

  id_type
  TokenIndex::
  getNumTokens() const
  {
    return numTokens;
  }

  id_type
  TokenIndex::
  getUnkId() const
  {
    return unkId;
  }

  char const* const
  TokenIndex::
  getUnkToken() const
  {
    return unkLabel.c_str();
    // return (*this)[unkId];
  }

  id_type
  TokenIndex::
  knownVocabSize() const
  {
    return numTokens;
  }

  id_type
  TokenIndex::
  ksize() const
  {
    return numTokens;
  }

  id_type
  TokenIndex::
  totalVocabSize() const
  { return tsize(); }

  id_type
  TokenIndex::
  tsize() const
  {
    return (newWords != NULL
            ? numTokens+newWords->size()
            : numTokens);
  }

  void
  write_tokenindex_to_disk(vector<pair<string,uint32_t> > const& tok,
                           string const& ofile, string const& unkToken)
  {
    typedef pair<uint32_t,id_type> IndexEntry; // offset and id

    // Write token strings to a buffer, keep track of offsets
    vector<IndexEntry> index(tok.size());
    ostringstream data;
    id_type unkId = tok.size();
    for (size_t i = 0; i < tok.size(); i++)
      {
        if (tok[i].first == unkToken)
          unkId = tok[i].second;
        index[i].first  = data.tellp();   // offset of string
        index[i].second = tok[i].second;  // respective ID
        data<<tok[i].first<<char(0);      // write string to buffer
      }

    // Now write the actual file
    ofstream out(ofile.c_str());
    uint32_t vsize = index.size(); // how many vocab items?
    out.write(reinterpret_cast<char*>(&vsize),4);
    out.write(reinterpret_cast<char*>(&unkId),sizeof(id_type));
    for (size_t i = 0; i < index.size(); i++)
      {
        out.write(reinterpret_cast<char*>(&index[i].first),4);
        out.write(reinterpret_cast<char*>(&index[i].second),sizeof(id_type));
      }
    out<<data.str();
  }

  void
  TokenIndex::
  write(string fname)
  {
    typedef pair<string,uint32_t>  Token;      // token and id
    vector<Token>       tok(totalVocabSize());
    for (id_type i = 0; i < tok.size(); ++i)
      tok[i] = Token((*this)[i],i);
    sort(tok.begin(),tok.end());
    write_tokenindex_to_disk(tok,fname,unkLabel);
  }

  bool
  TokenIndex::
  isDynamic() const
  {
    return dynamic;
  }

  bool
  TokenIndex::
  setDynamic(bool on)
  {
    bool ret = dynamic;
    if (on && this->str2idExtra == NULL)
      {
        this->str2idExtra.reset(new map<string,id_type>());
        this->newWords.reset(new vector<string>());
      }
    dynamic = on;
    if (on)
      {
	(*this)["NULL"];
	(*this)[unkLabel];
      }
    return ret;
  }

  void
  TokenIndex::
  setUnkLabel(string unk)
  {
    unkId = (*this)[unk];
    unkLabel = unk;
  }

}


text:
//===----------------------------------------------------------------------===//
//
// NAME         : apply
// SUMMARY      : Applies a list of removals to a graph.
// COPYRIGHT    : (c) 2108 Sean Donnellan. All Rights Reserved.
// LICENSE      : The MIT License (see LICENSE.txt for details)
// DESCRIPTION: : Using a list of edges to remove from a graph, this applies
//                the changes to the graph.
//
//===----------------------------------------------------------------------===//

#include <boost/algorithm/string/trim.hpp>

#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

// Read the edge removal list from input stream.
//
// The file is formatted as: Remove:Edge:<EdgeA>:<EdgeB>
//
// The output is formatted to be of the form: "<EdgeA>" -> "<EdgeB>";
//
// This matches the exact formatting of an edge line in the DOT files that
// these tools were originally written for, sans leading whitespace.
std::vector<std::string> read_removal_list(std::istream& input)
{
    const std::string removeDirective("Remove:Edge:");

    std::vector<std::string> removalList;
    for (std::string line; std::getline(input, line);)
    {
        if (line.compare(0, removeDirective.length(), removeDirective) == 0)
        {
            const auto split = line.find(':', removeDirective.length());
            removalList.push_back(
                "\"" +
                line.substr(removeDirective.length(),
                            split - removeDirective.length()) +
                "\" -> \"" + line.substr(split + 1) + "\";");
        }
        else
        {
            std::cerr << "Unknown directive." << line << std::endl;
        }
    }

    // Ensure its sorted so we can binary search on it.
    std::sort(removalList.begin(), removalList.end());
    return removalList;
}

void apply_removal_list(const std::vector<std::string>& removals,
                        std::istream& graph)
{
    // Algorithm:
    // - Read each line from the graph
    //   - Check if the line matches a line in the removal list.
    //   - If it doesn't write out the line.
    //
    // This only works because the script expects a strict dot/graphviv file
    // (i.e where the edges are a specific indentation and the node names are
    // quoted).
    std::cerr << "Edge to remove: " << removals.front() << std::endl;
    for (std::string line; std::getline(graph, line);)
    {
        auto trimmedLine = line;
        boost::algorithm::trim(trimmedLine);
        if (std::binary_search(removals.begin(), removals.end(), trimmedLine))
        {
            std::cerr << "Removed edge" << std::endl;
        }
        else
        {
            std::cout << line << std::endl;
        }
    }
}

int main(int argc, const char* argv[])
{
    std::istream* input = &std::cin;
    std::fstream inputFile;
    std::fstream removalFile;
    if (argc < 2)
    {
        std::cerr << "usage: " << argv[0] << " removal_file [dot file]"
                  << std::endl;
        return 1;
    }
    else if (argc == 2)
    {
        removalFile.open(argv[1], std::fstream::in);
        if (!removalFile)
        {
            std::cerr << "Failed to open file" << std::endl;
            return 1;
        }

        // The input stream already points to standard in.
    }
    else if (argc == 3)
    {
        removalFile.open(argv[1], std::fstream::in);
        if (!removalFile)
        {
            std::cerr << "Failed to open file" << std::endl;
            return 1;
        }

        inputFile.open(argv[2], std::fstream::in);
        if (!inputFile)
        {
            std::cerr << "Failed to open file" << std::endl;
            return 1;
        }
        input = &inputFile;
    }

    const auto removals = read_removal_list(removalFile);
    std::cerr << "There are " << removals.size() << " possible removals."
              << std::endl;
    apply_removal_list(removals, *input);
    return 0;
}

ext: cpp


text:
#include "storm/storage/prism/HidingComposition.h"

#include <boost/algorithm/string/join.hpp>

namespace storm {
    namespace prism {

        HidingComposition::HidingComposition(std::shared_ptr<Composition> const& sub, std::set<std::string> const& actionsToHide) : sub(sub), actionsToHide(actionsToHide) {
            // Intentionally left empty.
        }

        boost::any HidingComposition::accept(CompositionVisitor& visitor, boost::any const& data) const {
            return visitor.visit(*this, data);
        }

        Composition const& HidingComposition::getSubcomposition() const {
            return *sub;
        }

        std::set<std::string> const& HidingComposition::getActionsToHide() const {
            return actionsToHide;
        }

        void HidingComposition::writeToStream(std::ostream& stream) const {
            stream << "(" << *sub << ")" << " " << "{" << boost::join(actionsToHide, ", ") << "}";
        }

    }
}


text:
#include <gtest/gtest.h>

#include <boost/format.hpp>
#include <iostream>
#include <rxcpp/rx.hpp>

std::mutex lock;

void log(const std::string &msg) {
    std::unique_lock<std::mutex> l_lock(lock);
    std::cout << msg << std::endl;
}

TEST(test, test_1) {
    auto coordination = rxcpp::identity_current_thread();

    auto worker = coordination.create_coordinator().get_worker();
    auto start = coordination.now() + std::chrono::milliseconds(1);
    auto period = std::chrono::milliseconds(1);
    auto values = rxcpp::observable<>::interval(start, period)
                      .take(5)
                      .replay(2, coordination);

    worker.schedule([&](const rxcpp::schedulers::schedulable &) {
        values.subscribe(
            [](long v) {
                printf("#1 -- %Li : %ld\n", std::this_thread::get_id(), v);
            },
            []() { printf("#1 --- OnCompleted\n"); });
    });

    worker.schedule([&](const rxcpp::schedulers::schedulable &) {
        values.subscribe(
            [](long v) {
                printf("#2 -- %Li : %ld\n", std::this_thread::get_id(), v);
            },
            []() { printf("#2 --- OnCompleted\n"); });
    });

    // Start emitting

    worker.schedule(
        [&](const rxcpp::schedulers::schedulable &) { values.connect(); });

    // Add blocking subscription to see results

    values.as_blocking().subscribe();
}

ext: cc

max_stars_repo_name: yydcnjjw/my-krkrz

max_issues_repo_name: yydcnjjw/my-krkrz

max_forks_repo_name: yydcnjjw/my-krkrz


text:
/* -*- 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 "tr/translator.h"

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

#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "bc/index.h"
#include "bc/mounter.h"
#include "cas/dimension.h"
#include "compiler.h"
#include "db/driver.h"
#include "db/statement-driver.h"
#include "file.h"
#include "filter.h"
#include "filter/cutter.h"
#include "filter/writer.h"
#include "flint/bc.h"
#include "flint/ct.h"
#include "job.h"
#include "lo/layout.h"
#include "lo/layout_loader.h"
#include "load.h"
#include "reduction.h"
#include "run/spec.h"
#include "runtime/flow.h"
#include "task.h"
#include "task/config-reader.h"

namespace flint {
namespace tr {

Translator::Translator(const Layout *layout, int layer_size, Bytecode *bytecode,
					   std::ostream &os)
	: ct::DataFlowAnalyzer(layout, layer_size, bytecode)
	, os_(os)
{
}

namespace {

void PrintCall1(const bc::Call1 &c1, std::ostream &os)
{
	os << "\ttmp[" << c1.a() << "] = ";
	int a1 = c1.a1();
	switch (c1.op()) {
	case bc::Call1::kAbs:
		os << "fabs(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kArccos:
		os << "acos(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kArccosh:
		os << "acosh(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kArccot:
		os << "atan(1/tmp[" << a1 << "]);";
		break;
	case bc::Call1::kArccoth:
		os << "atanh(1/tmp[" << a1 << "]);";
		break;
	case bc::Call1::kArccsc:
		os << "asin(1/tmp[" << a1 << "]);";
		break;
	case bc::Call1::kArccsch:
		os << "asinh(1/tmp[" << a1 << "]);";
		break;
	case bc::Call1::kArcsec:
		os << "acos(1/tmp[" << a1 << "]);";
		break;
	case bc::Call1::kArcsech:
		os << "acosh(1/tmp[" << a1 << "]);";
		break;
	case bc::Call1::kArcsin:
		os << "asin(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kArcsinh:
		os << "asinh(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kArctan:
		os << "atan(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kArctanh:
		os << "atanh(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kCeiling:
		os << "ceil(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kCos:
		os << "cos(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kCosh:
		os << "cosh(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kCot:
		os << "cot(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kCoth:
		os << "1/tanh(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kCsc:
		os << "1/sin(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kCsch:
		os << "1/sinh(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kExp:
		os << "exp(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kFactorial:
		os << "assert(0);"; // TODO
		break;
	case bc::Call1::kFloor:
		os << "floor(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kLn:
		os << "log(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kLog10:
		os << "log10(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kMinus1:
		os << "-tmp[" << a1 << "];";
		break;
	case bc::Call1::kRoot1:
		os << "sqrt(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kSec:
		os << "1/cos(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kSech:
		os << "1/cosh(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kSin:
		os << "sin(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kSinh:
		os << "sinh(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kTan:
		os << "tan(tmp[" << a1 << "]);";
		break;
	case bc::Call1::kTanh:
		os << "tanh(tmp[" << a1 << "]);";
		break;
	}
	os << std::endl;
}

void PrintCall2(const bc::Call2 &c2, std::ostream &os)
{
	os << "\ttmp[" << c2.a() << "] = ";
	int a1 = c2.a1();
	int a2 = c2.a2();
	switch (c2.op()) {
	case bc::Call2::kDivide:
		os << "tmp[" << a1 << "] / tmp[" << a2 << "];";
		break;
	case bc::Call2::kEq:
		os << "(tmp[" << a1 << "] == tmp[" << a2 << "]);"; // FIXME
		break;
	case bc::Call2::kGeq:
		os << "(tmp[" << a1 << "] >= tmp[" << a2 << "]);";
		break;
	case bc::Call2::kGt:
		os << "(tmp[" << a1 << "] > tmp[" << a2 << "]);";
		break;
	case bc::Call2::kLeq:
		os << "(tmp[" << a1 << "] <= tmp[" << a2 << "]);";
		break;
	case bc::Call2::kLog:
		os << "log(tmp[" << a2 << "])/log(tmp[" << a1 << "]);";
		break;
	case bc::Call2::kLt:
		os << "(tmp[" << a1 << "] < tmp[" << a2 << "]);";
		break;
	case bc::Call2::kMax:
		os << "max(tmp[" << a1 << "], tmp[" << a2 << "]);";
		break;
	case bc::Call2::kMin:
		os << "min(tmp[" << a1 << "], tmp[" << a2 << "]);";
		break;
	case bc::Call2::kMinus2:
		os << "tmp[" << a1 << "] - tmp[" << a2 << "];";
		break;
	case bc::Call2::kModulo:
		os << "modulo(tmp[" << a1 << "], tmp[" << a2 << "]);";
		break;
	case bc::Call2::kNeq:
		os << "(tmp[" << a1 << "] != tmp[" << a2 << "]);"; // FIXME
		break;
	case bc::Call2::kPlus:
		os << "tmp[" << a1 << "] + tmp[" << a2 << "];";
		break;
	case bc::Call2::kPower:
		os << "pow(tmp[" << a1 << "], tmp[" << a2 << "]);";
		break;
	case bc::Call2::kRemainder:
		os << "fmod(tmp[" << a1 << "], tmp[" << a2 << "]);";
		break;
	case bc::Call2::kRoot2:
		os << "assert(0); /* TODO: kRoot2 */";
		std::cerr << "root with degree is not yet supported" << std::endl;
		break;
	case bc::Call2::kTimes:
		os << "tmp[" << a1 << "] * tmp[" << a2 << "];";
		break;
	}
	os << std::endl;
}

void PrintGen1(const bc::Gen1 &c1, std::ostream &os)
{
	(void)c1;
	os << "\tassert(0); /* TODO: Gen1 */" << std::endl;
}

void PrintGen2(const bc::Gen2 &c2, std::ostream &os)
{
	(void)c2;
	os << "\tassert(0); /* TODO: Gen2 */" << std::endl;
}

}

void Translator::PrintHeader(size_t layer_size,
							 double length, double step)
{
	static const unsigned char kHeaderSnippet[] = {
#include "tr/snippet/header.h"
	};
	for (auto c : kHeaderSnippet)
		os_.put(c);

	os_ << std::endl;
	os_ << "static const double length = " << length << ';' << std::endl;
	os_ << "static const double step = " << step << ';' << std::endl;
	os_ << std::endl;
	os_ << "static const int nol = " << GetNol() << ';' << std::endl;
	os_ << "static const size_t layer_size = " << layer_size << ';' << std::endl;
}

void Translator::PrintFunctions()
{
	static const unsigned char kFunctionSnippet[] = {
#include "tr/snippet/function.h"
	};
	os_ << std::endl;
	for (auto c : kFunctionSnippet)
		os_.put(c);

	int si = 0; // section index
	int bi = 0; // block index
	int ci = 0; // code index

	int nos = static_cast<int>(GetShv().size());
	while (si < nos) {
		const bc::SectionHeader &sh(GetShv().at(si++));

		boost::uuids::uuid uuid;
		std::memcpy(&uuid, sh.id().c_str(), uuid.size());
		os_ << std::endl;
		os_ << "/* section " << uuid << " */" << std::endl;

		int bie = bi + sh.nob();
		while (bi < bie) {
			os_ << std::endl;
			os_ << "static void block" << bi << "(int offset)" << std::endl;
			os_ << '{' << std::endl;
			const bc::BlockHeader &bh(GetBhv().at(bi));
			ci = code_offset_[bi++];
			int cib = ci;
			int cie = cib + bh.noc();

			os_ << "\tdouble tmp[" << bh.nod() << "];" << std::endl;
			os_ << std::endl;

			std::set<int> labels;
			while (ci < cie) {
				if (labels.count(ci - cib))
					os_ << "l" << (ci - cib) << ':' << std::endl;
				const bc::Code &code(GetCv().at(ci++));
				switch (code.type()) {
				case bc::Code::kBr:
					{
						os_ << "\tif (tmp[" << code.br().a() << "])" << std::endl;
						os_ << "\t\tgoto l" << code.br().p() << ';' << std::endl;
						labels.insert(code.br().p());
					}
					break;
				case bc::Code::kJmp:
					os_ << "\tgoto l" << code.jmp().p() << ';' << std::endl;
					labels.insert(code.jmp().p());
					break;
				case bc::Code::kCall1:
					PrintCall1(code.call1(), os_);
					break;
				case bc::Code::kCall2:
					PrintCall2(code.call2(), os_);
					break;
				case bc::Code::kLb:
					os_ << "\tassert(0);" << std::endl; // TODO
					break;
				case bc::Code::kLd:
					os_ << "\tassert(0);" << std::endl; // TODO
					break;
				case bc::Code::kGen1:
					PrintGen1(code.gen1(), os_);
					break;
				case bc::Code::kGen2:
					PrintGen2(code.gen2(), os_);
					break;
				case bc::Code::kLoad:
					{
						const bc::Load &load = code.load();
						switch (load.lo()) {
						case -1:
							os_ << "\ttmp[" << load.a() << "] = prev[offset+" << load.so() << "];" << std::endl;
							break;
						case -2:
							os_ << "\ttmp[" << load.a() << "] = data[" << load.so() << "];" << std::endl;
							break;
						default:
							os_ << "\ttmp[" << load.a() << "] = data[offset+" << load.so() << "+(layer_size*" << load.lo() << ")];" << std::endl;
							break;
						}
					}
					break;
				case bc::Code::kLoadi:
					os_ << "\ttmp[" << code.loadi().a() << "] = " << code.loadi().v() << ';' << std::endl;
					break;
				case bc::Code::kRet:
					os_ << "\treturn;" << std::endl;
					break;
				case bc::Code::kStore:
					{
						const bc::Store &store = code.store();
						os_ << "\tdata[offset+" << store.so() << "+(layer_size*" << store.lo() << ")] = tmp[" << store.a() << "];" << std::endl;
					}
					break;
				default:
					os_ << "\tassert(0);" << std::endl; // TODO
					break;
				}
			}
			os_ << '}' << std::endl;
		}
	}
}

void Translator::PrintReductionFunctions()
{
	os_ << std::endl;

	static const unsigned char kReductionSnippet[] = {
#include "tr/snippet/reduction.h"
	};
	for (auto c : kReductionSnippet)
		os_.put(c);

	int i = 0;
	for (const ExecutionUnit &eu : euv_) {
		if (eu.which() == 1) {
			os_ << std::endl;
			const ReductionUnit &ru = boost::get<ReductionUnit>(eu);
			os_ << "static const struct Reduction r" << i++ << " = {" << std::endl;
			switch (ru.reduction()) {
			case Reduction::kUnspecified:
				assert(false);
				break;
			case Reduction::kSum:
				os_ << "\treduce_sum," << std::endl;
				break;
			case Reduction::kMax:
				os_ << "\treduce_max," << std::endl;
				break;
			case Reduction::kMin:
				os_ << "\treduce_min," << std::endl;
				break;
			case Reduction::kMean:
				os_ << "\treduce_mean," << std::endl;
				break;
			case Reduction::kDegree:
				os_ << "\treduce_degree," << std::endl;
				break;
			}
			os_ << "\t" << ru.size() << ',' << std::endl;
			os_ << "\t" << ru.target_addr() << ',' << std::endl;
			size_t nsa = ru.source_addrs().size();
			os_ << "\t" << nsa << ',' << std::endl;
			os_ << "\t{";
			bool first = true;
			for (auto a : ru.source_addrs()) {
				if (first) {
					first = false;
				} else {
					os_ << ", ";
				}
				os_ << a;
			}
			os_ << "}" << std::endl;
			os_ << "};" << std::endl;
		}
	}
}

void Translator::PrintMain(const filter::Writer &writer)
{
	os_ << std::endl;
	writer.PrintCode(&os_);

	os_ << std::endl;
	static const unsigned char kMiscSnippet[] = {
#include "tr/snippet/misc.h"
	};
	for (auto c : kMiscSnippet)
		os_.put(c);

	os_ << std::endl;
	os_ << "int main(int argc, char *argv[])" << std::endl;
	os_ << '{' << std::endl;
	os_ << "\tif (argc == 0)" << std::endl;
	os_ << "\t\treturn EXIT_FAILURE;" << std::endl;
	os_ << "\tif (argc <= 1 || 3 <= argc) {" << std::endl;
	os_ << "\t\tusage(argv[0]);" << std::endl;
	os_ << "\t\treturn EXIT_FAILURE;" << std::endl;
	os_ << "\t}" << std::endl;
	os_ << "\tdata = calloc(nol * layer_size, sizeof(double));" << std::endl;
	os_ << "\tif (!data) {" << std::endl;
	os_ << "\t\tfprintf(stderr, \"calloc failed\\n\");" << std::endl;
	os_ << "\t\treturn EXIT_FAILURE;" << std::endl;
	os_ << "\t}" << std::endl;
	os_ << "\tprev = calloc(nol * layer_size, sizeof(double));" << std::endl;
	os_ << "\tif (!prev) {" << std::endl;
	os_ << "\t\tfprintf(stderr, \"calloc failed\\n\");" << std::endl;
	os_ << "\t\treturn EXIT_FAILURE;" << std::endl;
	os_ << "\t}" << std::endl;
	os_ << "\tfill_input();" << std::endl;
	os_ << "\tdata[" << kIndexEnd << "] = prev[" << kIndexEnd << "] = length;" << std::endl;
	os_ << "\tdata[" << kIndexDt << "] = prev[" << kIndexDt << "] = step;" << std::endl;
	os_ << "\tFILE *fp = fopen(argv[1], \"wb\");" << std::endl;
	os_ << "\tif (!fp) {" << std::endl;
	os_ << "\t\tperror(argv[1]);" << std::endl;
	os_ << "\t\treturn EXIT_FAILURE;" << std::endl;
	os_ << "\t}" << std::endl;
	os_ << "\tif (!fwrite(isdh, isdh_length, 1, fp))" << std::endl;
	os_ << "\t\treturn EXIT_FAILURE;" << std::endl;
	os_ << "\tif (!write_output(fp))" << std::endl;
	os_ << "\t\treturn EXIT_FAILURE;" << std::endl;
	os_ << "\tdo {" << std::endl;

	int i = 0;
	for (const ExecutionUnit &eu : euv_) {
		if (eu.which() == 0) {
			const CalculationUnit &cu = boost::get<CalculationUnit>(eu);
			int bi = cu.block_index();
			int offset = cu.offset();
			os_ << "\t\tblock" << bi << "("
				<< offset
				<< ");"
				<< std::endl;
		} else {
			os_ << "\t\tr" << i << ".reduce(&r" << i << ");" << std::endl;
			++i;
		}
	}

	os_ << "\t\tdata[" << kIndexTime << "] += prev[" << kIndexDt << "];" << std::endl;
	os_ << "\t\tif (!write_output(fp))" << std::endl;
	os_ << "\t\t\treturn EXIT_FAILURE;" << std::endl;
	os_ << "\t\tdouble last_time = data[" << kIndexTime << "];" << std::endl;
	os_ << "\t\tdouble *buf = data;" << std::endl;
	os_ << "\t\tdata = prev;" << std::endl;
	os_ << "\t\tprev = buf;" << std::endl;
	os_ << "\t\tdata[" << kIndexTime << "] = last_time;" << std::endl;
	os_ << "\t} while (data["
		<< kIndexTime
		<< "] < data["
		<< kIndexEnd
		<< "]);" << std::endl;
	os_ << "\tfclose(fp);" << std::endl;
	os_ << "\tfree(data);" << std::endl;
	os_ << "\tfree(prev);" << std::endl;
	os_ << "\treturn EXIT_SUCCESS;" << std::endl;
	os_ << '}' << std::endl;
}

}
}

max_stars_repo_name: Abhisheknishant/Flint

max_issues_repo_name: Abhisheknishant/Flint

max_forks_repo_name: Abhisheknishant/Flint


text:
/*
Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.

The MySQL Connector/C++ is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
MySQL Connectors. There are special exceptions to the terms and
conditions of the GPLv2 as it is applied to this software, see the
FLOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.

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; version 2 of the License.

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 <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <boost/scoped_array.hpp>

#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/warning.h>
#include "mysql_util.h"
#include "mysql_resultset.h"
#include "mysql_resultset_metadata.h"
#include "mysql_statement.h"

#include "nativeapi/native_connection_wrapper.h"
#include "nativeapi/native_resultset_wrapper.h"

#include "mysql_debug.h"

namespace sql
{
namespace mysql
{

/* {{{ MySQL_ResultSet::MySQL_ResultSet() -I- */
MySQL_ResultSet::MySQL_ResultSet(boost::shared_ptr< NativeAPI::NativeResultsetWrapper > res, boost::weak_ptr< NativeAPI::NativeConnectionWrapper > _proxy, sql::ResultSet::enum_type rset_type,
			MySQL_Statement * par, boost::shared_ptr< MySQL_DebugLogger > & l
		)
	: row(NULL), result(res), proxy(_proxy), row_position(0), was_null(false),
	  parent(par), logger(l), resultset_type(rset_type)
{
	CPP_ENTER("MySQL_ResultSet::MySQL_ResultSet");
	num_rows = result->num_rows();

	num_fields = result->num_fields();
	for (unsigned int i = 0; i < num_fields; ++i) {
#if A0
		std::cout << "Elements=" << field_name_to_index_map.size() << "\n";
#endif
		boost::scoped_array< char > upstring(sql::mysql::util::utf8_strup(getFieldMeta(i + 1)->name, 0));
		field_name_to_index_map[upstring.get()] = i;
	}
#if A0
	std::cout << "Elements=" << field_name_to_index_map.size() << "\n";
#endif
	rs_meta.reset(new MySQL_ResultSetMetaData(result, logger));
}
/* }}} */

/* {{{ MySQL_ResultSet::~MySQL_ResultSet() -I- */
MySQL_ResultSet::~MySQL_ResultSet()
{
	CPP_ENTER("MySQL_ResultSet::~MySQL_ResultSet");
}
/* }}} */

/* {{{ MySQL_ResultSet::absolute() -I- */
bool
MySQL_ResultSet::absolute(const int new_pos)
{
	CPP_ENTER("MySQL_ResultSet::absolute");
	checkValid();
	checkScrollable();
	if (new_pos > 0) {
		if (new_pos > (int) num_rows) {
			row_position = num_rows + 1; /* after last row */
		} else {
			row_position = (my_ulonglong) new_pos; /* the cast is inspected and is valid */
			seek();
			return true;
		}
	} else if (new_pos < 0) {
		if ((-new_pos) > (int) num_rows) {
			row_position = 0; /* before first new_pos */
		} else {
			row_position = num_rows - (-new_pos)  + 1;
			seek();
			return true;
		}
	} else {
		/* According to the JDBC book, absolute(0) means before the result set */
		row_position = 0;
		/* no seek() here, as we are not on data*/
		result->data_seek(0);
	}
	return (row_position > 0 && row_position < (num_rows + 1));
}
/* }}} */

/* {{{ MySQL_ResultSet::afterLast() -I- */
void
MySQL_ResultSet::afterLast()
{
	CPP_ENTER("MySQL_ResultSet::afterLast");
	checkValid();
	row_position = num_rows + 1;
}
/* }}} */

/* {{{ MySQL_ResultSet::beforeFirst() -I- */
void
MySQL_ResultSet::beforeFirst()
{
	CPP_ENTER("MySQL_ResultSet::beforeFirst");
	checkValid();
	checkScrollable();
	result->data_seek(0);
	row_position = 0;
}
/* }}} */

/* {{{ MySQL_ResultSet::cancelRowUpdates() -U- */
void
MySQL_ResultSet::cancelRowUpdates()
{
	CPP_ENTER("MySQL_ResultSet::cancelRowUpdates");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::cancelRowUpdates()");
}
/* }}} */

/* {{{ MySQL_ResultSet::checkScrollable() -I- */
void
MySQL_ResultSet::checkScrollable() const
{
	CPP_ENTER("MySQL_ResultSet::checkScrollable");
	CPP_INFO_FMT("this=%p", this);
	if (resultset_type == sql::ResultSet::TYPE_FORWARD_ONLY) {
		throw sql::NonScrollableException("Nonscrollable result set");
	}
}
/* }}} */

/* {{{ MySQL_ResultSet::isScrollable() -I- */
bool
MySQL_ResultSet::isScrollable() const
{
//	CPP_ENTER("MySQL_ResultSet::isScrollable");
//	CPP_INFO_FMT("this=%p", this);
	return (resultset_type != sql::ResultSet::TYPE_FORWARD_ONLY);
}
/* }}} */

/* {{{ MySQL_ResultSet::checkValid() -I- */
void
MySQL_ResultSet::checkValid() const
{
	CPP_ENTER("MySQL_ResultSet::checkValid");
	CPP_INFO_FMT("this=%p", this);
	if (isClosed()) {
		throw sql::InvalidInstanceException("ResultSet has been closed");
	}
}
/* }}} */

/* {{{ MySQL_ResultSet::clearWarnings() -U- */
void
MySQL_ResultSet::clearWarnings()
{
	CPP_ENTER("MySQL_ResultSet::clearWarnings");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::clearWarnings()");
}
/* }}} */

/* {{{ MySQL_ResultSet::close() -I- */
void
MySQL_ResultSet::close()
{
	CPP_ENTER("MySQL_ResultSet::close");
	checkValid();
	result.reset();
//	result->dispose();
}
/* }}} */

/* {{{ MySQL_ResultSet::findColumn() -I- */
uint32_t
MySQL_ResultSet::findColumn(const sql::SQLString& columnLabel) const
{
	CPP_ENTER("MySQL_ResultSet::findColumn");
	checkValid();
	boost::scoped_array< char > upstring(sql::mysql::util::utf8_strup(columnLabel.c_str(), 0));
#if A0
	std::cout << "Elements=" << field_name_to_index_map.size() << "\n";
	FieldNameIndexMap::const_iterator tmp_iter = field_name_to_index_map.begin();
	FieldNameIndexMap::const_iterator tmp_iter_end = field_name_to_index_map.end();
	for (;tmp_iter != tmp_iter_end; tmp_iter++) {
		std::cout << "[[" << tmp_iter->first << "]] second=[[" << tmp_iter->second << "]]\n";
	}
	sql::SQLString tmp(upstring.get());
	std::cout << "[" << tmp << "]\n";
#endif

	FieldNameIndexMap::const_iterator iter = field_name_to_index_map.find(sql::SQLString(upstring.get()));
	if (iter == field_name_to_index_map.end()) {
		return 0;
	}
	/* findColumn returns 1-based indexes */
	return iter->second + 1;
}
/* }}} */

/* {{{ MySQL_ResultSet::first() -I- */
bool
MySQL_ResultSet::first()
{
	CPP_ENTER("MySQL_ResultSet::first");
	checkValid();
	checkScrollable();
	if (num_rows) {
		row_position = 1;
		seek();
	}
	return num_rows != 0;
}
/* }}} */

/* {{{ MySQL_ResultSet::getBlob() -I- */
std::istream *
MySQL_ResultSet::getBlob(const uint32_t columnIndex) const
{
	CPP_ENTER("MySQL_ResultSet::getBlob(int)");
	/* isBeforeFirst checks for validity */
	if (isBeforeFirstOrAfterLast()) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getBoolean: can't fetch because not on result set");
	}
	return new std::istringstream(getString(columnIndex));
}
/* }}} */

/* {{{ MySQL_ResultSet::getBlob() -I- */
std::istream *
MySQL_ResultSet::getBlob(const sql::SQLString& columnLabel) const
{
	CPP_ENTER("MySQL_ResultSet::getBlob(string)");
	/* isBeforeFirst checks for validity */
	if (isBeforeFirstOrAfterLast()) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getBoolean: can't fetch because not on result set");
	}
	return new std::istringstream(getString(columnLabel));
}
/* }}} */

/* {{{ MySQL_ResultSet::getBoolean() -I- */
bool
MySQL_ResultSet::getBoolean(const uint32_t columnIndex) const
{
	CPP_ENTER("MySQL_ResultSet::getBoolean(int)");
	/* isBeforeFirst checks for validity */
	if (isBeforeFirstOrAfterLast()) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getBoolean: can't fetch because not on result set");
	}
	return getInt(columnIndex)? true:false;
}
/* }}} */

/* {{{ MySQL_ResultSet::getBoolean() -I- */
bool
MySQL_ResultSet::getBoolean(const sql::SQLString& columnLabel) const
{
	CPP_ENTER("MySQL_ResultSet::getBoolean(string)");
	/* isBeforeFirst checks for validity */
	if (isBeforeFirstOrAfterLast()) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getBoolean: can't fetch because not on result set");
	}
	return getInt(columnLabel)? true:false;
}
/* }}} */

/* {{{ MySQL_ResultSet::getConcurrency() -U- */
int
MySQL_ResultSet::getConcurrency()
{
	CPP_ENTER("MySQL_ResultSet::getConcurrency");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::getConcurrency()");
	return 0; // fool compilers
}
/* }}} */

/* {{{ MySQL_ResultSet::getCursorName() -U- */
SQLString
MySQL_ResultSet::getCursorName()
{
	CPP_ENTER("MySQL_ResultSet::getCursorName");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::getCursorName()");
	return ""; // fool compilers
}
/* }}} */

/* {{{ MySQL_ResultSet::getDouble() -I- */
long double
MySQL_ResultSet::getDouble(const uint32_t columnIndex) const
{
	CPP_ENTER("MySQL_ResultSet::getDouble(int)");

	/* isBeforeFirst checks for validity */
	if (isBeforeFirstOrAfterLast()) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getDouble: can't fetch because not on result set");
	}

	if (columnIndex == 0 || columnIndex > num_fields) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getDouble: invalid value of 'columnIndex'");
	}
	if (row[columnIndex - 1] == NULL) {
		was_null = true;
		return 0.0;
	}
	was_null = false;
	if (getFieldMeta(columnIndex)->type == MYSQL_TYPE_BIT) {
		return static_cast<long double>(getInt64(columnIndex));
	}
	return sql::mysql::util::strtold(row[columnIndex - 1], NULL);
}
/* }}} */

/* {{{ MySQL_ResultSet::getDouble() -I- */
long double
MySQL_ResultSet::getDouble(const sql::SQLString& columnLabel) const
{
	CPP_ENTER("MySQL_ResultSet::getDouble(string)");
	return getDouble(findColumn(columnLabel));
}
/* }}} */

/* {{{ MySQL_ResultSet::getFetchDirection() -U- */
int
MySQL_ResultSet::getFetchDirection()
{
	CPP_ENTER("MySQL_ResultSet::getFetchDirection");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::getFetchDirection()");
	return 0; // fool compilers
}
/* }}} */

/* {{{ MySQL_ResultSet::getFetchSize() -U- */
size_t
MySQL_ResultSet::getFetchSize()
{
	CPP_ENTER("MySQL_ResultSet::getFetchSize");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::getFetchSize()");
	return 0; // fool compilers
}
/* }}} */

/* {{{ MySQL_ResultSet::getFieldMeta() -U- */
MYSQL_FIELD * MySQL_ResultSet::getFieldMeta(unsigned int columnIndex) const
{
	return result->fetch_field_direct(columnIndex - 1);
}
/* }}} */

/* {{{ MySQL_ResultSet::getHoldability() -U- */
int
MySQL_ResultSet::getHoldability()
{
	CPP_ENTER("MySQL_ResultSet::getHoldability");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::getHoldability()");
	return 0; // fool compilers
}
/* }}} */

/* {{{ MySQL_ResultSet::getInt() -I- */
int32_t
MySQL_ResultSet::getInt(const uint32_t columnIndex) const
{
	CPP_ENTER("MySQL_ResultSet::getInt(int)");
	/* isBeforeFirst checks for validity */
	if (isBeforeFirstOrAfterLast()) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getInt: can't fetch because not on result set");
	}
	if (columnIndex == 0 || columnIndex > num_fields) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getInt: invalid value of 'columnIndex'");
	}
	CPP_INFO_FMT("%ssigned", (getFieldMeta(columnIndex)->flags & UNSIGNED_FLAG)? "un":"");
	if (getFieldMeta(columnIndex)->flags & UNSIGNED_FLAG) {
		return static_cast<uint32_t>(getInt64(columnIndex));
	}
	return static_cast<int32_t>(getInt64(columnIndex));
}
/* }}} */

/* {{{ MySQL_ResultSet::getInt() -I- */
int32_t
MySQL_ResultSet::getInt(const sql::SQLString& columnLabel) const
{
	CPP_ENTER("MySQL_ResultSet::getInt(string)");
	return getInt(findColumn(columnLabel));
}
/* }}} */

/* {{{ MySQL_ResultSet::getUInt() -I- */
uint32_t
MySQL_ResultSet::getUInt(const uint32_t columnIndex) const
{
	CPP_ENTER("MySQL_ResultSet::getUInt(int)");
	/* isBeforeFirst checks for validity */
	if (isBeforeFirstOrAfterLast()) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getUInt: can't fetch because not on result set");
	}
	if (columnIndex == 0 || columnIndex > num_fields) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getUInt: invalid value of 'columnIndex'");
	}
	CPP_INFO_FMT("%ssigned", (getFieldMeta(columnIndex)->flags & UNSIGNED_FLAG)? "un":"");
	return static_cast<uint32_t>(getUInt64(columnIndex));// & 0xffffffff;
}
/* }}} */

/* {{{ MySQL_ResultSet::getUInt() -I- */
uint32_t
MySQL_ResultSet::getUInt(const sql::SQLString& columnLabel) const
{
	CPP_ENTER("MySQL_ResultSet::getUInt(string)");
	return getUInt(findColumn(columnLabel));
}
/* }}} */

/* {{{ MySQL_ResultSet::getInt64() -I- */
int64_t
MySQL_ResultSet::getInt64(const uint32_t columnIndex) const
{
	CPP_ENTER("MySQL_ResultSet::getInt64(int)");

	/* isBeforeFirst checks for validity */
	if (isBeforeFirstOrAfterLast()) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getInt64: can't fetch because not on result set");
	}

	if (columnIndex == 0 || columnIndex > num_fields) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getInt64: invalid value of 'columnIndex'");
	}

	if (row[columnIndex - 1] == NULL) {
		was_null = true;
		return 0;
	}
	CPP_INFO_FMT("%ssigned", (getFieldMeta(columnIndex)->flags & UNSIGNED_FLAG)? "un":"");
	was_null = false;
	if (getFieldMeta(columnIndex)->type == MYSQL_TYPE_BIT) {
		uint64_t uval = 0;
		std::div_t length= std::div(getFieldMeta(columnIndex)->length, 8);
		if (length.rem) {
			++length.quot;
		}

		switch (length.quot) {
			case 8:uval = (uint64_t) bit_uint8korr(row[columnIndex - 1]);break;
			case 7:uval = (uint64_t) bit_uint7korr(row[columnIndex - 1]);break;
			case 6:uval = (uint64_t) bit_uint6korr(row[columnIndex - 1]);break;
			case 5:uval = (uint64_t) bit_uint5korr(row[columnIndex - 1]);break;
			case 4:uval = (uint64_t) bit_uint4korr(row[columnIndex - 1]);break;
			case 3:uval = (uint64_t) bit_uint3korr(row[columnIndex - 1]);break;
			case 2:uval = (uint64_t) bit_uint2korr(row[columnIndex - 1]);break;
			case 1:uval = (uint64_t) bit_uint1korr(row[columnIndex - 1]);break;
		}
		return uval;
	}

	if (getFieldMeta(columnIndex)->flags & UNSIGNED_FLAG) {
		return strtoull(row[columnIndex - 1], NULL, 10);
	}
	return strtoll(row[columnIndex - 1], NULL, 10);
}
/* }}} */

/* {{{ MySQL_ResultSet::getInt64() -I- */
int64_t
MySQL_ResultSet::getInt64(const sql::SQLString& columnLabel) const
{
	CPP_ENTER("MySQL_ResultSet::getInt64(string)");
	return getInt64(findColumn(columnLabel));
}
/* }}} */

/* {{{ MySQL_ResultSet::getUInt64() -I- */
uint64_t
MySQL_ResultSet::getUInt64(const uint32_t columnIndex) const
{
	CPP_ENTER("MySQL_ResultSet::getUInt64(int)");

	/* isBeforeFirst checks for validity */
	if (isBeforeFirstOrAfterLast()) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getUInt64: can't fetch because not on result set");
	}

	if (columnIndex == 0 || columnIndex > num_fields) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getUInt64: invalid value of 'columnIndex'");
	}

	if (row[columnIndex - 1] == NULL) {
		was_null = true;
		return 0;
	}
	CPP_INFO_FMT("%ssigned", (getFieldMeta(columnIndex)->flags & UNSIGNED_FLAG)? "un":"");
	was_null = false;
	if (getFieldMeta(columnIndex)->type == MYSQL_TYPE_BIT) {
		uint64_t uval = 0;
		std::div_t length= std::div(getFieldMeta(columnIndex)->length, 8);
		if (length.rem) {
			++length.quot;
		}
		switch (length.quot) {
			case 8:uval = (uint64_t) bit_uint8korr(row[columnIndex - 1]);break;
			case 7:uval = (uint64_t) bit_uint7korr(row[columnIndex - 1]);break;
			case 6:uval = (uint64_t) bit_uint6korr(row[columnIndex - 1]);break;
			case 5:uval = (uint64_t) bit_uint5korr(row[columnIndex - 1]);break;
			case 4:uval = (uint64_t) bit_uint4korr(row[columnIndex - 1]);break;
			case 3:uval = (uint64_t) bit_uint3korr(row[columnIndex - 1]);break;
			case 2:uval = (uint64_t) bit_uint2korr(row[columnIndex - 1]);break;
			case 1:uval = (uint64_t) bit_uint1korr(row[columnIndex - 1]);break;
		}
		return uval;
	}

	if (getFieldMeta(columnIndex)->flags & UNSIGNED_FLAG) {
		return strtoull(row[columnIndex - 1], NULL, 10);
	}
	return strtoll(row[columnIndex - 1], NULL, 10);
}
/* }}} */

/* {{{ MySQL_ResultSet::getUInt64() -I- */
uint64_t
MySQL_ResultSet::getUInt64(const sql::SQLString& columnLabel) const
{
	CPP_ENTER("MySQL_ResultSet::getUInt64(string)");
	return getUInt64(findColumn(columnLabel));
}
/* }}} */

/* {{{ MySQL_ResultSet::getMetaData() -I- */
sql::ResultSetMetaData *
MySQL_ResultSet::getMetaData() const
{
	CPP_ENTER("MySQL_ResultSet::getMetaData");
	checkValid();
	return rs_meta.get();
}
/* }}} */

/* {{{ MySQL_ResultSet::getRow() -I- */
size_t
MySQL_ResultSet::getRow() const
{
	CPP_ENTER("MySQL_ResultSet::getRow");
	checkValid();
	/* row_position is 0 based */
	return static_cast<size_t>(row_position);
}
/* }}} */

/* {{{ MySQL_ResultSet::getRowId() -U- */
sql::RowID *
MySQL_ResultSet::getRowId(uint32_t)
{
	CPP_ENTER("MySQL_ResultSet::getRowId");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::getRowId(uint32_t columnIndex)");
	return NULL; // fool compilers
}
/* }}} */

/* {{{ MySQL_ResultSet::getRowId() -U- */
sql::RowID *
MySQL_ResultSet::getRowId(const sql::SQLString &)
{
	CPP_ENTER("MySQL_ResultSet::getRowId");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::getRowId(const sql::SQLString & columnLabel)");
	return NULL; // fool compilers
}
/* }}} */

/* {{{ MySQL_ResultSet::getStatement() -I- */
const sql::Statement *
MySQL_ResultSet::getStatement() const
{
	CPP_ENTER("MySQL_ResultSet::getStatement");
	return parent;
}
/* }}} */

/* {{{ MySQL_ResultSet::getString() -I- */
SQLString
MySQL_ResultSet::getString(const uint32_t columnIndex) const
{
	CPP_ENTER("MySQL_ResultSet::getString(int)");
	CPP_INFO_FMT("this=%p column=%u", this, columnIndex);

	/* isBeforeFirst checks for validity */
	if (isBeforeFirstOrAfterLast()) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getString: can't fetch because not on result set");
	}

	if (columnIndex == 0 || columnIndex > num_fields) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getString: invalid value of 'columnIndex'");
	}

	if (row[columnIndex - 1] == NULL) {
		was_null = true;
		return "";
	}

	if (getFieldMeta(columnIndex)->type == MYSQL_TYPE_BIT) {
		char buf[30];
		snprintf(buf, sizeof(buf) - 1, "%llu", (unsigned long long) getUInt64(columnIndex));
		return sql::SQLString(buf);
	}

	size_t len = result->fetch_lengths()[columnIndex - 1];
	CPP_INFO_FMT("value=%*s",  len> 50? 50:len, row[columnIndex - 1]);
	was_null = false;
	return sql::SQLString(row[columnIndex - 1], len);
}
/* }}} */

/* {{{ MySQL_ResultSet::getString() -I- */
SQLString
MySQL_ResultSet::getString(const sql::SQLString& columnLabel) const
{
	CPP_ENTER("MySQL_ResultSet::getString(string)");
	return getString(findColumn(columnLabel));
}
/* }}} */

/* {{{ MySQL_ResultSet::getType() -I- */
sql::ResultSet::enum_type
MySQL_ResultSet::getType() const
{
	CPP_ENTER("MySQL_ResultSet::getType");
	checkValid();
	return resultset_type;
}
/* }}} */

/* {{{ MySQL_ResultSet::getWarnings() -U- */
void
MySQL_ResultSet::getWarnings()
{
	CPP_ENTER("MySQL_ResultSet::getWarnings");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::getWarnings()");
}
/* }}} */

/* {{{ MySQL_ResultSet::insertRow() -U- */
void
MySQL_ResultSet::insertRow()
{
	CPP_ENTER("MySQL_ResultSet::insertRow");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::insertRow()");
}
/* }}} */

/* {{{ MySQL_ResultSet::isAfterLast() -I- */
bool
MySQL_ResultSet::isAfterLast() const
{
	CPP_ENTER("MySQL_ResultSet::isAfterLast");
	checkValid();
	checkScrollable();
	return (row_position == num_rows + 1);
}
/* }}} */

/* {{{ MySQL_ResultSet::isBeforeFirst() -I- */
bool
MySQL_ResultSet::isBeforeFirst() const
{
	CPP_ENTER("MySQL_ResultSet::isBeforeFirst");
	checkValid();
	return (row_position == 0);
}
/* }}} */

/* {{{ MySQL_ResultSet::isClosed() -I- */
bool
MySQL_ResultSet::isClosed() const
{
	CPP_ENTER("MySQL_ResultSet::isClosed");
	return !result;
//	return !result->isValid();
}
/* }}} */

/* {{{ MySQL_ResultSet::isFirst() -I- */
bool
MySQL_ResultSet::isFirst() const
{
	CPP_ENTER("MySQL_ResultSet::isFirst");
	checkValid();
	return (row_position == 1);
}
/* }}} */

/* {{{ MySQL_ResultSet::isLast() -I- */
bool
MySQL_ResultSet::isLast() const
{
	CPP_ENTER("MySQL_ResultSet::isLast");
	checkValid();
	checkScrollable();
	return (row_position == num_rows);
}
/* }}} */

/* {{{ MySQL_ResultSet::isNull() -I- */
bool
MySQL_ResultSet::isNull(const uint32_t columnIndex) const
{
	CPP_ENTER("MySQL_ResultSet::isNull(int)");
	checkValid();

	if (columnIndex == 0 || columnIndex > num_fields) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::isNull: invalid value of 'columnIndex'");
	}
	/* isBeforeFirst checks for validity */
	if (isBeforeFirstOrAfterLast()) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::getDouble: can't fetch because not on result set");
	}
	return (row[columnIndex - 1] == NULL);
}
/* }}} */

/* {{{ MySQL_ResultSet::isNull() -I- */
bool
MySQL_ResultSet::isNull(const sql::SQLString& columnLabel) const
{
	CPP_ENTER("MySQL_ResultSet::isNull(string)");
	int32_t col_idx = findColumn(columnLabel);
	if (col_idx == 0) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::isNull: invalid value of 'columnLabel'");
	}
	return isNull(col_idx);
}
/* }}} */

/* {{{ MySQL_ResultSet::last() -I- */
bool
MySQL_ResultSet::last()
{
	CPP_ENTER("MySQL_ResultSet::last");
	checkValid();
	checkScrollable();
	if (num_rows) {
		row_position = num_rows;
		seek();
	}
	return num_rows != 0;
}
/* }}} */

/* {{{ MySQL_ResultSet::moveToCurrentRow() -U- */
void
MySQL_ResultSet::moveToCurrentRow()
{
	CPP_ENTER("MySQL_ResultSet::moveToCurrentRow");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::moveToCurrentRow()");
	checkScrollable();
}
/* }}} */

/* {{{ MySQL_ResultSet::moveToInsertRow() -U- */
void
MySQL_ResultSet::moveToInsertRow()
{
	CPP_ENTER("MySQL_ResultSet::moveToInsertRow");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::moveToInsertRow()");
	checkScrollable();
}
/* }}} */

/* {{{ MySQL_ResultSet::next() -I- */
bool
MySQL_ResultSet::next()
{
	CPP_ENTER("MySQL_ResultSet::next");
	checkValid();
	bool ret = false;
	if (isScrollable()) {
		if (isLast()) {
			afterLast();
		} else if (row_position < num_rows + 1) {
			row = result->fetch_row();
			boost::shared_ptr< NativeAPI::NativeConnectionWrapper > proxy_p = proxy.lock();
			if (!proxy_p) {
				throw sql::InvalidInstanceException("Connection has been closed");
			}

			if (row == NULL && (proxy_p->errNo() == 2013 ||
								proxy_p->errNo() == 2000)) {
				CPP_ERR_FMT("Error fetching next row %d:(%s) %s",
							proxy_p->errNo(), proxy_p->sqlstate().c_str(),
							proxy_p->error().c_str());
				sql::SQLException e(proxy_p->error(), proxy_p->sqlstate(), proxy_p->errNo());
				throw e;
			}
			++row_position;
			ret = (row != NULL);
		}
	} else {
		row = result->fetch_row();
		boost::shared_ptr< NativeAPI::NativeConnectionWrapper > proxy_p = proxy.lock();
		if (!proxy_p) {
			throw sql::InvalidInstanceException("Connection has been closed");
		}

		if (row == NULL && (proxy_p->errNo() == 2013 ||
							proxy_p->errNo() == 2000)) {
			CPP_ERR_FMT("Error fetching next row %d:(%s) %s",
						proxy_p->errNo(), proxy_p->sqlstate().c_str(),
						proxy_p->error().c_str());
			sql::SQLException e(proxy_p->error(), proxy_p->sqlstate(), proxy_p->errNo());
			throw e;
		}
		++row_position;
		ret = (row != NULL);
	}
	CPP_INFO_FMT("new_position=%llu num_rows=%llu", row_position, num_rows);
	return ret;
}
/* }}} */

/* {{{ MySQL_ResultSet::previous() -I- */
bool
MySQL_ResultSet::previous()
{
	CPP_ENTER("MySQL_ResultSet::previous");

	checkScrollable();
	/* isBeforeFirst checks for validity */
	if (isBeforeFirst()) {
		return false;
	} else if (isFirst()) {
		beforeFirst();
		return false;
	} else if (row_position > 1) {
		--row_position;
		seek();
		return true;
	}
	throw sql::SQLException("Impossible");
}
/* }}} */

/* {{{ MySQL_ResultSet::refreshRow() -U- */
void
MySQL_ResultSet::refreshRow()
{
	CPP_ENTER("MySQL_ResultSet::refreshRow");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::refreshRow()");
}
/* }}} */

/* {{{ MySQL_ResultSet::relative() -I- */
bool
MySQL_ResultSet::relative(const int rows)
{
	CPP_ENTER("MySQL_ResultSet::relative");
	checkValid();
	checkScrollable();
	if (rows != 0) {
		if ((row_position + rows) > num_rows || (row_position + rows) < 1) {
			row_position = rows > 0? num_rows + 1 : 0; /* after last or before first */
		} else {
			row_position += rows;
			seek();
		}
	}

	return (row_position > 0 && row_position <= num_rows);
}
/* }}} */

/* {{{ MySQL_ResultSet::rowDeleted() -U- */
bool
MySQL_ResultSet::rowDeleted()
{
	CPP_ENTER("MySQL_ResultSet::rowDeleted");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::rowDeleted()");
	return false; // fool compilers
}
/* }}} */

/* {{{ MySQL_ResultSet::rowInserted() -U- */
bool
MySQL_ResultSet::rowInserted()
{
	CPP_ENTER("MySQL_ResultSet::rowInserted");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::rowInserted()");
	return false; // fool compilers
}
/* }}} */

/* {{{ MySQL_ResultSet::rowUpdated() -U- */
bool
MySQL_ResultSet::rowUpdated()
{
	CPP_ENTER("MySQL_ResultSet::rowUpdated");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::rowUpdated()");
	return false; // fool compilers
}
/* }}} */

/* {{{ MySQL_ResultSet::rowsCount() -I- */
size_t
MySQL_ResultSet::rowsCount() const
{
	CPP_ENTER("MySQL_ResultSet::rowsCount");
	checkValid();
	checkScrollable();
	return static_cast<size_t>(result->num_rows());
}
/* }}} */

/* {{{ MySQL_ResultSet::setFetchSize() -U- */
void
MySQL_ResultSet::setFetchSize(size_t /* rows */)
{
	CPP_ENTER("MySQL_ResultSet::setFetchSize");
	checkValid();
	throw sql::MethodNotImplementedException("MySQL_ResultSet::setFetchSize()");
}
/* }}} */

/* {{{ MySQL_ResultSet::wasNull() -I- */
bool
MySQL_ResultSet::wasNull() const
{
	CPP_ENTER("MySQL_ResultSet::wasNull");
	checkValid();
	/* isBeforeFirst checks for validity */
	if (isBeforeFirstOrAfterLast()) {
		throw sql::InvalidArgumentException("MySQL_ResultSet::wasNull: can't fetch because not on result set");
	}
	return was_null;
}
/* }}} */

/* {{{ MySQL_ResultSet::isBeforeFirstOrAfterLast() -I- */
bool
MySQL_ResultSet::isBeforeFirstOrAfterLast() const
{
	CPP_ENTER("MySQL_ResultSet::isBeforeFirstOrAfterLast");
	checkValid();
	return (row_position == 0) || (isScrollable() && (row_position == num_rows + 1));
}
/* }}} */

/* {{{ MySQL_ResultSet::seek() -I- */
void
MySQL_ResultSet::seek()
{
	CPP_ENTER("MySQL_ResultSet::seek");
	checkScrollable();
	result->data_seek(row_position - 1);
	row = result->fetch_row();
}
/* }}} */

} /* namespace mysql */
} /* namespace sql */

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */

max_stars_repo_name: rikkotec/nodamysql

max_issues_repo_name: rikkotec/nodamysql

max_forks_repo_name: rikkotec/nodamysql


text: #include <boost/xpressive/regex_token_iterator.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino