<commit_before>#include <fstream>
#include <future>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <set>

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

#include <cryptopp/adler32.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>

#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>

#include <gumbo.h>

#include <uriparser/Uri.h>

#include "csd.hpp"

using namespace std;
using namespace CryptoPP;

class UriParseFailure : public runtime_error {
    public:

    UriParseFailure(int error_code)
        : runtime_error("uri parsing error code: " + to_string(error_code)) {
    }
};

class Uri {
    // FIXME: pick a sane lib here and package it where needed
    // sane looking libs:
    // - https://github.com/datacratic/google-url
    // - https://github.com/chmike/CxxUrl
    // FIXME: this implemenation with uriparser probably doesn't support
    // anything other than most common formats.
    // Unsupported includes: explicit ports, file access, probably
    // localized uris
    public:
    const string str;
    Uri(string url) : str(url) {
        state.uri = &uri;

        if (uriParseUriA(&state, str.c_str()) != URI_SUCCESS) {
            throw new UriParseFailure(state.errorCode);
        }

        scheme = _mkstr(uri.scheme);
        port   = _mkstr(uri.portText);
        host   = _mkstr(uri.hostText);
        is_abs = uri.absolutePath;
        is_prl = boost::starts_with(str, "//");

        uriFreeUriMembersA(&uri);
    }

    string get_absolute(string base) {
        return get_absolute(Uri(base));
    }
    /**
     * \param[in] base uri of the page to resolve relative links against.
     *   eg.: Uri("foo").get_absolute("http://example.com") == "http://example.com/foo"
     */
    string get_absolute(const Uri base) const {
        // TODO: cover by unit tests
        if (!scheme.empty()) {
            return str;
        }

        if (!is_abs) {
            return base.str + "/" + str;
        }

        if (is_prl) {
            // FIXME: scheme-relative-file-URL not implemented.
            // The path-absolute-non-Windows-file-URL doesn't make sense
            // to me.
            return base.scheme + ":" + str;
        }

        if (host.empty()) {
            return base.scheme + "://" + base.host + str;
        }

        throw runtime_error("Failed to absolutize " + str + " with base "
            + base.str);
    }

    private:
    UriParserStateA state;
    UriUriA uri;
    string host;
    string port;
    string scheme;
    /**
     * True if the URL starts with a '/', false otherwise (including
     * starting with scheme)
     */
    bool is_abs;

    /**
     * True if uri is Protocol Relative Link
     * https://url.spec.whatwg.org/#syntax-url-scheme-relative
     */
    bool is_prl;

    string _mkstr(UriTextRangeA x) const {
        if (x.first == NULL || x.afterLast == NULL) {
            return string();
            // TODO: maybe check if only one of those is NULL?
        }

        return string(x.first, x.afterLast);
    }
};

/**
 * Parses file references from HTML document.
 * TODO: Probably can handle only HTML5 now.
 */
class Html5Parser {
    public:

    /** URLs parsed from the given document
     */
    set<string> urls;

    /**
     * \param[in] page HTML document
     * \param[in] url  URL of the document. Used for resolving relative
     *    links.
     */
    Html5Parser (const string page, string url)
    : base_url(url) {
        output = gumbo_parse(page.c_str());
        parse(output->root);
        gumbo_destroy_output(&kGumboDefaultOptions, output);
        munge();
    }

    private:

    GumboOutput* output;
    string base_url;
    vector<Uri> relative_urls;

    /**
     * Parses raw urls from the given HTML document
     */
    void parse(GumboNode *node) {
        if (node->type != GUMBO_NODE_ELEMENT) {
            return;
        }

        parse_a(node);
        // TODO: Add more tag parsers

        GumboVector* children = &node->v.element.children;
        for (unsigned int i = 0; i < children->length; ++i) {
            parse(static_cast<GumboNode*>(children->data[i]));
        }
    }

    void parse_a(GumboNode *node) {
        if (node->v.element.tag != GUMBO_TAG_A) {
            return;
        }

        GumboAttribute* href;
        if ((href = gumbo_get_attribute(&node->v.element.attributes, "href"))) {
            relative_urls.push_back(Uri(href->value));
        }
    }

    /**
     * Resolves the relative links to absolute.
     *
     */
    void munge() {
        for (const auto &x : relative_urls) {
            urls.insert(x.get_absolute(Uri(base_url)));
        }
    }
};

File::File(const string url) : url(url), data(File::download_url(url)),
    adler32hex(File::mk_hash())
{}

string File::mk_hash() const {
    Adler32 hash;
    string hex;
    StringSource ss(data, true,
        new HashFilter(hash,
            new HexEncoder(new StringSink( hex ))
        )
    );

    return hex;
}

bool File::size_cmp(File x, File y) {
    return x.data.size() < y.data.size();
}

string File::download_url(const string url) const {
    stringstream out;

    curlpp::Cleanup cleanup;
    curlpp::Easy request;

    request.setOpt(new curlpp::options::Url(url));
    request.setOpt(new curlpp::options::WriteStream(&out));
    request.setOpt(new curlpp::options::FollowLocation(true));

    request.perform();

    return out.str();
}

OriginUrl::OriginUrl(const string url) : File(url), urls(parse_urls()) {}

vector<File> OriginUrl::fetch_files() {
    vector<future<File>> futures;

    for (const auto &x : urls) {
        auto f(std::async([] (string url) -> File
            { return File(url); }, x));
        futures.push_back(move(f));
    }

    vector<File> files;

    while (futures.size() > 0 ) {
        for(unsigned int i = 0; i < futures.size(); i++) {
            if (futures[i].valid()) {
                files.push_back(futures[i].get());
                futures.erase(futures.begin() + i);
            }
        }
    }

    return files;
}

set<string> OriginUrl::parse_urls() const {
    return Html5Parser(data, url).urls;
}
<commit_msg>Add more tag parsers<commit_after>#include <fstream>
#include <future>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <set>

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

#include <cryptopp/adler32.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>

#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>

#include <gumbo.h>

#include <uriparser/Uri.h>

#include "csd.hpp"

using namespace std;
using namespace CryptoPP;

class UriParseFailure : public runtime_error {
    public:

    UriParseFailure(int error_code)
        : runtime_error("uri parsing error code: " + to_string(error_code)) {
    }
};

class Uri {
    // FIXME: pick a sane lib here and package it where needed
    // sane looking libs:
    // - https://github.com/datacratic/google-url
    // - https://github.com/chmike/CxxUrl
    // FIXME: this implemenation with uriparser probably doesn't support
    // anything other than most common formats.
    // Unsupported includes: explicit ports, file access, probably
    // localized uris
    public:
    const string str;
    Uri(string url) : str(url) {
        state.uri = &uri;

        if (uriParseUriA(&state, str.c_str()) != URI_SUCCESS) {
            throw new UriParseFailure(state.errorCode);
        }

        scheme = _mkstr(uri.scheme);
        port   = _mkstr(uri.portText);
        host   = _mkstr(uri.hostText);
        is_abs = uri.absolutePath;
        is_prl = boost::starts_with(str, "//");

        uriFreeUriMembersA(&uri);
    }

    string get_absolute(string base) {
        return get_absolute(Uri(base));
    }
    /**
     * \param[in] base uri of the page to resolve relative links against.
     *   eg.: Uri("foo").get_absolute("http://example.com") == "http://example.com/foo"
     */
    string get_absolute(const Uri base) const {
        // TODO: cover by unit tests
        if (!scheme.empty()) {
            return str;
        }

        if (!is_abs) {
            return base.str + "/" + str;
        }

        if (is_prl) {
            // FIXME: scheme-relative-file-URL not implemented.
            // The path-absolute-non-Windows-file-URL doesn't make sense
            // to me.
            return base.scheme + ":" + str;
        }

        if (host.empty()) {
            return base.scheme + "://" + base.host + str;
        }

        throw runtime_error("Failed to absolutize " + str + " with base "
            + base.str);
    }

    private:
    UriParserStateA state;
    UriUriA uri;
    string host;
    string port;
    string scheme;
    /**
     * True if the URL starts with a '/', false otherwise (including
     * starting with scheme)
     */
    bool is_abs;

    /**
     * True if uri is Protocol Relative Link
     * https://url.spec.whatwg.org/#syntax-url-scheme-relative
     */
    bool is_prl;

    string _mkstr(UriTextRangeA x) const {
        if (x.first == NULL || x.afterLast == NULL) {
            return string();
            // TODO: maybe check if only one of those is NULL?
        }

        return string(x.first, x.afterLast);
    }
};

/**
 * Parses file references from HTML document.
 * TODO: Probably can handle only HTML5 now.
 */
class Html5Parser {
    public:

    /** URLs parsed from the given document
     */
    set<string> urls;

    /**
     * \param[in] page HTML document
     * \param[in] url  URL of the document. Used for resolving relative
     *    links.
     */
    Html5Parser (const string page, string url)
    : base_url(url) {
        output = gumbo_parse(page.c_str());
        parse(output->root);
        gumbo_destroy_output(&kGumboDefaultOptions, output);
        munge();
    }

    private:

    GumboOutput* output;
    string base_url;
    vector<Uri> relative_urls;

    /**
     * Parses raw urls from the given HTML document
     */
    void parse(GumboNode *node) {
        if (node->type != GUMBO_NODE_ELEMENT) {
            return;
        }

        parse_attr(node, GUMBO_TAG_A, "href");
        parse_attr(node, GUMBO_TAG_IMG, "src");
        parse_attr(node, GUMBO_TAG_LINK, "href");
        parse_attr(node, GUMBO_TAG_SCRIPT, "src");
        // TODO: probably missed some, check with html5 spec
        // FIXME: handle base tag

        GumboVector* children = &node->v.element.children;
        for (unsigned int i = 0; i < children->length; ++i) {
            parse(static_cast<GumboNode*>(children->data[i]));
        }
    }

    void parse_attr(GumboNode *node, const GumboTag t, const char* attr) {
        if (node->v.element.tag != t) {
            return;
        }

        GumboAttribute* gattr;
        if ((gattr = gumbo_get_attribute(&node->v.element.attributes, attr))) {
            relative_urls.push_back(Uri(gattr->value));
        }
    }

    /**
     * Resolves the relative links to absolute.
     *
     */
    void munge() {
        for (const auto &x : relative_urls) {
            urls.insert(x.get_absolute(Uri(base_url)));
        }
    }
};

File::File(const string url) : url(url), data(File::download_url(url)),
    adler32hex(File::mk_hash())
{}

string File::mk_hash() const {
    Adler32 hash;
    string hex;
    StringSource ss(data, true,
        new HashFilter(hash,
            new HexEncoder(new StringSink( hex ))
        )
    );

    return hex;
}

bool File::size_cmp(File x, File y) {
    return x.data.size() < y.data.size();
}

string File::download_url(const string url) const {
    stringstream out;

    curlpp::Cleanup cleanup;
    curlpp::Easy request;

    request.setOpt(new curlpp::options::Url(url));
    request.setOpt(new curlpp::options::WriteStream(&out));
    request.setOpt(new curlpp::options::FollowLocation(true));

    request.perform();

    return out.str();
}

OriginUrl::OriginUrl(const string url) : File(url), urls(parse_urls()) {}

vector<File> OriginUrl::fetch_files() {
    vector<future<File>> futures;

    for (const auto &x : urls) {
        auto f(std::async([] (string url) -> File
            { return File(url); }, x));
        futures.push_back(move(f));
    }

    vector<File> files;

    while (futures.size() > 0 ) {
        for(unsigned int i = 0; i < futures.size(); i++) {
            if (futures[i].valid()) {
                files.push_back(futures[i].get());
                futures.erase(futures.begin() + i);
            }
        }
    }

    return files;
}

set<string> OriginUrl::parse_urls() const {
    return Html5Parser(data, url).urls;
}
<|endoftext|>


<commit_before>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
// (C) 2005 Mike Weiblen http://mew.cx/ released under the OSGPL.
// Simple example using GLUT to create an OpenGL window and OSG for rendering.
// Derived from osgGLUTsimple.cpp and osgkeyboardmouse.cpp

#include <osgGA/SimpleViewer>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>

#include <SDL.h>
#include <SDL_events.h>

#include <iostream>

int main( int argc, char **argv )
{
    if (argc<2)
    {
        std::cout << argv[0] <<": requires filename argument." << std::endl;
        return 1;
    }

    // init SDL
    if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
    {
        fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
        exit(1);
    }
    atexit(SDL_Quit);

    // load the scene.
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
    if (!loadedModel)
    {
        std::cout << argv[0] <<": No data loaded." << std::endl;
        return 1;
    }

    unsigned int windowWidth = 1280;
    unsigned int windowHeight = 1024;

    SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

        // set up the surface to render to
    SDL_Surface* screen = SDL_SetVideoMode(windowWidth, windowHeight, 32, SDL_OPENGL | SDL_FULLSCREEN | SDL_RESIZABLE);
    if ( screen == NULL )
    {
        std::cerr<<"Unable to set "<<windowWidth<<"x"<<windowHeight<<" video: %s\n"<< SDL_GetError()<<std::endl;
        exit(1);
    }

    SDL_EnableUNICODE(1);

    osgGA::SimpleViewer viewer;
    viewer.setSceneData(loadedModel.get());
    viewer.setCameraManipulator(new osgGA::TrackballManipulator);
    viewer.getEventQueue()->windowResize(0, 0, windowWidth, windowHeight );

    bool done = false;
    while( !done )
    {
        SDL_Event event;

        while ( SDL_PollEvent(&event) )
        {
            switch (event.type) {

                case SDL_MOUSEMOTION:
                    viewer.getEventQueue()->mouseMotion(event.motion.x, event.motion.y);
                    break;

                case SDL_MOUSEBUTTONDOWN:
                    viewer.getEventQueue()->mouseButtonPress(event.button.x, event.button.y, event.button.button);
                    break;

                case SDL_MOUSEBUTTONUP:
                    viewer.getEventQueue()->mouseButtonRelease(event.button.x, event.button.y, event.button.button);
                    break;

                case SDL_KEYUP:
                    viewer.getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) event.key.keysym.unicode);

                    if (event.key.keysym.sym==SDLK_ESCAPE) done = true;
                    if (event.key.keysym.sym=='f') SDL_WM_ToggleFullScreen(screen);

                    break;

                case SDL_KEYDOWN:
                    viewer.getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) event.key.keysym.unicode);
                    break;

                case SDL_VIDEORESIZE:
                {
                    viewer.getEventQueue()->windowResize(0, 0, event.resize.w, event.resize.h );

                    std::cout<<"event.resize.w="<<event.resize.w<<"  event.resize.h="<<event.resize.h<<std::endl;
                    break;
                }

                case SDL_QUIT:
                    done = true;
            }
        }

        if (done) continue;

        // draw the new frame
        viewer.frame();

    	// Swap Buffers
        SDL_GL_SwapBuffers();
    }

    return 0;
}

/*EOF*/
<commit_msg>Refactored the SDL example so that the event conversion in done is a seperate method.<commit_after>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
// (C) 2005 Mike Weiblen http://mew.cx/ released under the OSGPL.
// Simple example using GLUT to create an OpenGL window and OSG for rendering.
// Derived from osgGLUTsimple.cpp and osgkeyboardmouse.cpp

#include <osgGA/SimpleViewer>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>

#include <SDL.h>
#include <SDL_events.h>

#include <iostream>

bool convertEvent(SDL_Event& event, osgGA::EventQueue& eventQueue)
{
    switch (event.type) {

        case SDL_MOUSEMOTION:
            eventQueue.mouseMotion(event.motion.x, event.motion.y);
            return true;

        case SDL_MOUSEBUTTONDOWN:
            eventQueue.mouseButtonPress(event.button.x, event.button.y, event.button.button);
            return true;

        case SDL_MOUSEBUTTONUP:
            eventQueue.mouseButtonRelease(event.button.x, event.button.y, event.button.button);
            return true;

        case SDL_KEYUP:
            eventQueue.keyRelease( (osgGA::GUIEventAdapter::KeySymbol) event.key.keysym.unicode);
            return true;

        case SDL_KEYDOWN:
            eventQueue.keyPress( (osgGA::GUIEventAdapter::KeySymbol) event.key.keysym.unicode);
            return true;

        case SDL_VIDEORESIZE:
            eventQueue.windowResize(0, 0, event.resize.w, event.resize.h );
            return true;

        default:
            break;
    }
    return false;
}

int main( int argc, char **argv )
{
    if (argc<2)
    {
        std::cout << argv[0] <<": requires filename argument." << std::endl;
        return 1;
    }

    // init SDL
    if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
    {
        fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
        exit(1);
    }
    atexit(SDL_Quit);

    // load the scene.
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
    if (!loadedModel)
    {
        std::cout << argv[0] <<": No data loaded." << std::endl;
        return 1;
    }

    unsigned int windowWidth = 1280;
    unsigned int windowHeight = 1024;

    SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

        // set up the surface to render to
    SDL_Surface* screen = SDL_SetVideoMode(windowWidth, windowHeight, 32, SDL_OPENGL | SDL_FULLSCREEN | SDL_RESIZABLE);
    if ( screen == NULL )
    {
        std::cerr<<"Unable to set "<<windowWidth<<"x"<<windowHeight<<" video: %s\n"<< SDL_GetError()<<std::endl;
        exit(1);
    }

    SDL_EnableUNICODE(1);

    osgGA::SimpleViewer viewer;
    viewer.setSceneData(loadedModel.get());
    viewer.setCameraManipulator(new osgGA::TrackballManipulator);
    viewer.getEventQueue()->windowResize(0, 0, windowWidth, windowHeight );

    bool done = false;
    while( !done )
    {
        SDL_Event event;

        while ( SDL_PollEvent(&event) )
        {
            // pass the SDL event into the viewers event queue
            convertEvent(event, *viewer.getEventQueue());

            switch (event.type) {

                case SDL_KEYUP:

                    if (event.key.keysym.sym==SDLK_ESCAPE) done = true;
                    if (event.key.keysym.sym=='f') SDL_WM_ToggleFullScreen(screen);

                    break;

                case SDL_QUIT:
                    done = true;
            }
        }

        if (done) continue;

        // draw the new frame
        viewer.frame();

    	// Swap Buffers
        SDL_GL_SwapBuffers();
    }

    return 0;
}

/*EOF*/
<|endoftext|>


<commit_before>#include "../SDP_Solver.hxx"

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

// We use binary checkpointing because writing text does not write all
// of the necessary digits.  The GMP library sets it to one less than
// required for round-tripping.
template <typename T>
void write_local_blocks(const T &t,
                        boost::filesystem::ofstream &checkpoint_stream)
{
  El::BigFloat zero(0);
  const size_t serialized_size(zero.SerializedSize());
  std::vector<uint8_t> local_array(serialized_size);

  for(auto &block : t.blocks)
    {
      int64_t local_height(block.LocalHeight()),
        local_width(block.LocalWidth());
      checkpoint_stream.write(reinterpret_cast<char *>(&local_height),
                              sizeof(int64_t));
      checkpoint_stream.write(reinterpret_cast<char *>(&local_width),
                              sizeof(int64_t));
      for(int64_t row = 0; row < local_height; ++row)
        for(int64_t column = 0; column < local_width; ++column)
          {
            block.GetLocal(row, column).Serialize(local_array.data());
            checkpoint_stream.write(
              reinterpret_cast<char *>(local_array.data()),
              std::streamsize(local_array.size()));
          }
    }
}

void SDP_Solver::save_checkpoint(
  const boost::filesystem::path &checkpoint_directory,
  const Verbosity &verbosity) const
{
  boost::filesystem::path checkpoint_filename(
    checkpoint_directory / ("checkpoint." + std::to_string(El::mpi::Rank())));

  if(!exists(checkpoint_directory))
    {
      create_directories(checkpoint_directory);
    }
  else if(!is_directory(checkpoint_directory))
    {
      throw std::runtime_error("Checkpoint directory '"
                               + checkpoint_directory.string()
                               + "'already exists, but is not a directory");
    }
  if(exists(checkpoint_directory / checkpoint_filename))
    {
      if(verbosity >= Verbosity::regular && El::mpi::Rank() == 0)
        {
          std::cout << "Backing up checkpoint\n";
        }
      boost::filesystem::path backup_filename(checkpoint_filename.string()
                                              + ".bk");
      remove(backup_filename);
      rename(checkpoint_filename, backup_filename);
    }
  boost::filesystem::ofstream checkpoint_stream(checkpoint_filename);
  if(verbosity >= Verbosity::regular && El::mpi::Rank() == 0)
    {
      std::cout << "Saving checkpoint to    : " << checkpoint_directory
                << '\n';
    }
  write_local_blocks(x, checkpoint_stream);
  write_local_blocks(X, checkpoint_stream);
  write_local_blocks(y, checkpoint_stream);
  write_local_blocks(Y, checkpoint_stream);
}
<commit_msg>Add retry logic if the filesystem is not working properly.<commit_after>#include "../SDP_Solver.hxx"

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

// We use binary checkpointing because writing text does not write all
// of the necessary digits.  The GMP library sets it to one less than
// required for round-tripping.
template <typename T>
void write_local_blocks(const T &t,
                        boost::filesystem::ofstream &checkpoint_stream)
{
  El::BigFloat zero(0);
  const size_t serialized_size(zero.SerializedSize());
  std::vector<uint8_t> local_array(serialized_size);

  for(auto &block : t.blocks)
    {
      int64_t local_height(block.LocalHeight()),
        local_width(block.LocalWidth());
      checkpoint_stream.write(reinterpret_cast<char *>(&local_height),
                              sizeof(int64_t));
      checkpoint_stream.write(reinterpret_cast<char *>(&local_width),
                              sizeof(int64_t));
      for(int64_t row = 0; row < local_height; ++row)
        for(int64_t column = 0; column < local_width; ++column)
          {
            block.GetLocal(row, column).Serialize(local_array.data());
            checkpoint_stream.write(
              reinterpret_cast<char *>(local_array.data()),
              std::streamsize(local_array.size()));
          }
    }
}

void SDP_Solver::save_checkpoint(
  const boost::filesystem::path &checkpoint_directory,
  const Verbosity &verbosity) const
{
  boost::filesystem::path checkpoint_filename(
    checkpoint_directory / ("checkpoint." + std::to_string(El::mpi::Rank())));

  if(!exists(checkpoint_directory))
    {
      create_directories(checkpoint_directory);
    }
  else if(!is_directory(checkpoint_directory))
    {
      throw std::runtime_error("Checkpoint directory '"
                               + checkpoint_directory.string()
                               + "'already exists, but is not a directory");
    }
  if(exists(checkpoint_directory / checkpoint_filename))
    {
      if(verbosity >= Verbosity::regular && El::mpi::Rank() == 0)
        {
          std::cout << "Backing up checkpoint\n";
        }
      boost::filesystem::path backup_filename(checkpoint_filename.string()
                                              + ".bk");
      remove(backup_filename);
      rename(checkpoint_filename, backup_filename);
    }

  const size_t max_retries(10);
  bool wrote_successfully(false);
  for(size_t attempt=0; attempt<max_retries && !wrote_successfully; ++attempt)
    {
      boost::filesystem::ofstream checkpoint_stream(checkpoint_filename);
      if(verbosity >= Verbosity::regular && El::mpi::Rank() == 0)
        {
          std::cout << "Saving checkpoint to    : " << checkpoint_directory
                    << '\n';
        }
      write_local_blocks(x, checkpoint_stream);
      write_local_blocks(X, checkpoint_stream);
      write_local_blocks(y, checkpoint_stream);
      write_local_blocks(Y, checkpoint_stream);
      wrote_successfully=checkpoint_stream.good();
      if(!wrote_successfully)
        {
          if(attempt+1<max_retries)
            {
              std::stringstream ss;
              ss << "Error writing checkpoint file '"
                 << checkpoint_filename << "'.  Retrying "
                 << (attempt+2) << "/" << max_retries << "\n";
              std::cerr << ss.str() << std::flush;
            }
          else
            {
              std::stringstream ss;
              ss << "Error writing checkpoint file '"
                 << checkpoint_filename << "'.  Exceeded max retries.\n";
              throw std::runtime_error(ss.str());
            }
        }
    }
}
<|endoftext|>


<commit_before>//===- TreeView.cpp - diagtool tool for printing warning flags ------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "DiagTool.h"
#include "DiagnosticNames.h"
#include "clang/Basic/AllDiagnostics.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Process.h"

DEF_DIAGTOOL("tree", "Show warning flags in a tree view", TreeView)

using namespace clang;
using namespace diagtool;

static bool hasColors(const llvm::raw_ostream &out) {
  if (&out != &llvm::errs() && &out != &llvm::outs())
    return false;
  return llvm::errs().is_displayed() && llvm::outs().is_displayed();
}

class TreePrinter {
public:
  llvm::raw_ostream &out;
  const bool ShowColors;
  bool Internal;

  TreePrinter(llvm::raw_ostream &out)
      : out(out), ShowColors(hasColors(out)), Internal(false) {}

  void setColor(llvm::raw_ostream::Colors Color) {
    if (ShowColors)
      out << llvm::sys::Process::OutputColor(Color, false, false);
  }

  void resetColor() {
    if (ShowColors)
      out << llvm::sys::Process::ResetColor();
  }

  static bool isIgnored(unsigned DiagID) {
    // FIXME: This feels like a hack.
    static clang::DiagnosticsEngine Diags(new DiagnosticIDs,
                                          new DiagnosticOptions);
    return Diags.isIgnored(DiagID, SourceLocation());
  }

  static bool enabledByDefault(const GroupRecord &Group) {
    for (const DiagnosticRecord &DR : Group.diagnostics()) {
      if (isIgnored(DR.DiagID))
        return false;
    }

    for (const GroupRecord &GR : Group.subgroups()) {
      if (!enabledByDefault(GR))
        return false;
    }

    return true;
  }

  void printGroup(const GroupRecord &Group, unsigned Indent = 0) {
    out.indent(Indent * 2);

    if (enabledByDefault(Group))
      setColor(llvm::raw_ostream::GREEN);
    else
      setColor(llvm::raw_ostream::YELLOW);

    out << "-W" << Group.getName() << "\n";
    resetColor();

    ++Indent;
    for (const GroupRecord &GR : Group.subgroups()) {
      printGroup(GR, Indent);
    }

    if (Internal) {
      for (const DiagnosticRecord &DR : Group.diagnostics()) {
        if (ShowColors && !isIgnored(DR.DiagID))
          setColor(llvm::raw_ostream::GREEN);
        out.indent(Indent * 2);
        out << DR.getName();
        resetColor();
        out << "\n";
      }
    }
  }

  int showGroup(StringRef RootGroup) {
    ArrayRef<GroupRecord> AllGroups = getDiagnosticGroups();

    if (RootGroup.size() > UINT16_MAX) {
      llvm::errs() << "No such diagnostic group exists\n";
      return 1;
    }

    const GroupRecord *Found = llvm::lower_bound(AllGroups, RootGroup);
    if (Found == AllGroups.end() || Found->getName() != RootGroup) {
      llvm::errs() << "No such diagnostic group exists\n";
      return 1;
    }

    printGroup(*Found);

    return 0;
  }

  int showAll() {
    ArrayRef<GroupRecord> AllGroups = getDiagnosticGroups();
    llvm::DenseSet<unsigned> NonRootGroupIDs;

    for (const GroupRecord &GR : AllGroups) {
      for (auto SI = GR.subgroup_begin(), SE = GR.subgroup_end(); SI != SE;
           ++SI) {
        NonRootGroupIDs.insert((unsigned)SI.getID());
      }
    }

    assert(NonRootGroupIDs.size() < AllGroups.size());

    for (unsigned i = 0, e = AllGroups.size(); i != e; ++i) {
      if (!NonRootGroupIDs.count(i))
        printGroup(AllGroups[i]);
    }

    return 0;
  }

  void showKey() {
    if (ShowColors) {
      out << '\n';
      setColor(llvm::raw_ostream::GREEN);
      out << "GREEN";
      resetColor();
      out << " = enabled by default\n\n";
    }
  }
};

static void printUsage() {
  llvm::errs() << "Usage: diagtool tree [--internal] [<diagnostic-group>]\n";
}

int TreeView::run(unsigned int argc, char **argv, llvm::raw_ostream &out) {
  // First check our one flag (--flags-only).
  bool Internal = false;
  if (argc > 0) {
    StringRef FirstArg(*argv);
    if (FirstArg.equals("--internal")) {
      Internal = true;
      --argc;
      ++argv;
    }
  }

  bool ShowAll = false;
  StringRef RootGroup;

  switch (argc) {
  case 0:
    ShowAll = true;
    break;
  case 1:
    RootGroup = argv[0];
    if (RootGroup.startswith("-W"))
      RootGroup = RootGroup.substr(2);
    if (RootGroup == "everything")
      ShowAll = true;
    // FIXME: Handle other special warning flags, like -pedantic.
    break;
  default:
    printUsage();
    return -1;
  }

  TreePrinter TP(out);
  TP.Internal = Internal;
  TP.showKey();
  return ShowAll ? TP.showAll() : TP.showGroup(RootGroup);
}
<commit_msg>Re-submit r367649: Improve raw_ostream so that you can "write" colors using operator<<<commit_after>//===- TreeView.cpp - diagtool tool for printing warning flags ------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "DiagTool.h"
#include "DiagnosticNames.h"
#include "clang/Basic/AllDiagnostics.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Process.h"

DEF_DIAGTOOL("tree", "Show warning flags in a tree view", TreeView)

using namespace clang;
using namespace diagtool;

static bool hasColors(const llvm::raw_ostream &out) {
  if (&out != &llvm::errs() && &out != &llvm::outs())
    return false;
  return llvm::errs().is_displayed() && llvm::outs().is_displayed();
}

class TreePrinter {
public:
  llvm::raw_ostream &out;
  const bool ShowColors;
  bool Internal;

  TreePrinter(llvm::raw_ostream &out)
      : out(out), ShowColors(hasColors(out)), Internal(false) {}

  void setColor(llvm::raw_ostream::Colors Color) {
    if (ShowColors)
      out << llvm::sys::Process::OutputColor(static_cast<char>(Color), false,
                                             false);
  }

  void resetColor() {
    if (ShowColors)
      out << llvm::sys::Process::ResetColor();
  }

  static bool isIgnored(unsigned DiagID) {
    // FIXME: This feels like a hack.
    static clang::DiagnosticsEngine Diags(new DiagnosticIDs,
                                          new DiagnosticOptions);
    return Diags.isIgnored(DiagID, SourceLocation());
  }

  static bool enabledByDefault(const GroupRecord &Group) {
    for (const DiagnosticRecord &DR : Group.diagnostics()) {
      if (isIgnored(DR.DiagID))
        return false;
    }

    for (const GroupRecord &GR : Group.subgroups()) {
      if (!enabledByDefault(GR))
        return false;
    }

    return true;
  }

  void printGroup(const GroupRecord &Group, unsigned Indent = 0) {
    out.indent(Indent * 2);

    if (enabledByDefault(Group))
      setColor(llvm::raw_ostream::GREEN);
    else
      setColor(llvm::raw_ostream::YELLOW);

    out << "-W" << Group.getName() << "\n";
    resetColor();

    ++Indent;
    for (const GroupRecord &GR : Group.subgroups()) {
      printGroup(GR, Indent);
    }

    if (Internal) {
      for (const DiagnosticRecord &DR : Group.diagnostics()) {
        if (ShowColors && !isIgnored(DR.DiagID))
          setColor(llvm::raw_ostream::GREEN);
        out.indent(Indent * 2);
        out << DR.getName();
        resetColor();
        out << "\n";
      }
    }
  }

  int showGroup(StringRef RootGroup) {
    ArrayRef<GroupRecord> AllGroups = getDiagnosticGroups();

    if (RootGroup.size() > UINT16_MAX) {
      llvm::errs() << "No such diagnostic group exists\n";
      return 1;
    }

    const GroupRecord *Found = llvm::lower_bound(AllGroups, RootGroup);
    if (Found == AllGroups.end() || Found->getName() != RootGroup) {
      llvm::errs() << "No such diagnostic group exists\n";
      return 1;
    }

    printGroup(*Found);

    return 0;
  }

  int showAll() {
    ArrayRef<GroupRecord> AllGroups = getDiagnosticGroups();
    llvm::DenseSet<unsigned> NonRootGroupIDs;

    for (const GroupRecord &GR : AllGroups) {
      for (auto SI = GR.subgroup_begin(), SE = GR.subgroup_end(); SI != SE;
           ++SI) {
        NonRootGroupIDs.insert((unsigned)SI.getID());
      }
    }

    assert(NonRootGroupIDs.size() < AllGroups.size());

    for (unsigned i = 0, e = AllGroups.size(); i != e; ++i) {
      if (!NonRootGroupIDs.count(i))
        printGroup(AllGroups[i]);
    }

    return 0;
  }

  void showKey() {
    if (ShowColors) {
      out << '\n';
      setColor(llvm::raw_ostream::GREEN);
      out << "GREEN";
      resetColor();
      out << " = enabled by default\n\n";
    }
  }
};

static void printUsage() {
  llvm::errs() << "Usage: diagtool tree [--internal] [<diagnostic-group>]\n";
}

int TreeView::run(unsigned int argc, char **argv, llvm::raw_ostream &out) {
  // First check our one flag (--flags-only).
  bool Internal = false;
  if (argc > 0) {
    StringRef FirstArg(*argv);
    if (FirstArg.equals("--internal")) {
      Internal = true;
      --argc;
      ++argv;
    }
  }

  bool ShowAll = false;
  StringRef RootGroup;

  switch (argc) {
  case 0:
    ShowAll = true;
    break;
  case 1:
    RootGroup = argv[0];
    if (RootGroup.startswith("-W"))
      RootGroup = RootGroup.substr(2);
    if (RootGroup == "everything")
      ShowAll = true;
    // FIXME: Handle other special warning flags, like -pedantic.
    break;
  default:
    printUsage();
    return -1;
  }

  TreePrinter TP(out);
  TP.Internal = Internal;
  TP.showKey();
  return ShowAll ? TP.showAll() : TP.showGroup(RootGroup);
}
<|endoftext|>


<commit_before>//Foster.cpp
//Implements definitions of Foster functionality.
//"Bad becomes good" - Tory Foster
//josh@mindaptiv.com

//includes
#include "pch.h"
#include "Foster.h"
#include <windows.foundation.h>
#include <windows.system.h>
#include <sysinfoapi.h>

//If Visual Studio freaks out about this code someday, add this line back in OR modify your project settings
//#pragma comment(lib, "Ws2_32.lib")

//Method definitions:
//getters
unsigned int getFosterMilliseconds(struct cylonStruct tf)
{
	//return
	return tf.milliseconds;
}

unsigned int getFosterSeconds(struct cylonStruct tf)
{
	//return
	return tf.seconds;
}

unsigned int getFosterMinutes(struct cylonStruct tf)
{
	//return
	return tf.minutes;
}

unsigned int getFosterHours(struct cylonStruct tf)
{
	//return
	return tf.hours;
}

unsigned int getFosterDay(struct cylonStruct tf)
{
	//return
	return tf.day;
}

unsigned int getFosterDate(struct cylonStruct tf)
{
	//return
	return tf.date;
}

unsigned int getFosterMonth(struct cylonStruct tf)
{
	//return
	return tf.month;
}

unsigned int getFosterYear(struct cylonStruct tf)
{
	//return
	return tf.year;
}

long getFosterTimeZone(struct cylonStruct tf)
{
	//return
	return tf.timeZone;
}

unsigned int getFosterDST(struct cylonStruct tf)
{
	//return
	return tf.dst;
}

std::wstring getFosterTimeZoneName(struct cylonStruct tf)
{
	//return
	return tf.wTimeZoneName;
}

std::wstring getFosterUsername(struct cylonStruct tf)
{
	//return
	return tf.wUsername;
}

std::wstring getFosterDeviceName(struct cylonStruct tf)
{
	//return
	return tf.wDeviceName;
}

unsigned short getFosterArchitecture(struct cylonStruct tf)
{
	//return
	return tf.architecture;
}

unsigned short getFosterProcessorLevel(struct cylonStruct tf)
{
	//return
	return tf.processorLevel;
}

unsigned long getFosterPageSize(struct cylonStruct tf)
{
	//return
	return tf.pageSize;
}

unsigned long getFosterProcessorCount(struct cylonStruct tf)
{
	//return
	return tf.processorCount;
}

unsigned long getFosterAllocationGranularity(struct cylonStruct tf)
{
	//return
	return tf.allocationGranularity;
}

void* getFosterMinAppAddress(struct cylonStruct tf)
{
	//return
	return tf.minAppAddress;
}

void* getFosterMaxAppAddress(struct cylonStruct tf)
{
	//return
	return tf.maxAppAddress;
}

std::wstring getFosterPictureType(struct cylonStruct tf)
{
	//return
	return tf.pictureType;

}

Windows::Storage::IStorageFile^ getFosterPictureFile(struct cylonStruct tf)
{
	//return
	return tf.picture;
}
//end getters

//for getting username
void produceUsername(struct cylonStruct& tory)
{
	//Variable declaration
	Platform::String^ managedUsername;
	Windows::Foundation::IAsyncOperation<Platform::String^>^ operation;
	const wchar_t* operationDataPointer;
	std::wstring wideUsername;
	std::string username;

	//Retrieve username
	operation			= Windows::System::UserProfile::UserInformation::GetDisplayNameAsync();
	while(	operation->Status == Windows::Foundation::AsyncStatus::Started)
	{
		//WAIT, YO
	}
	managedUsername = operation->GetResults();
	operation->Close();

	//Convert username to std::wstring
	operationDataPointer	= managedUsername->Data();
	wideUsername			= std::wstring(operationDataPointer);
	//TODO convert from wstring to string

	//TODO: check if retrieved username is empty string? (therefore UserInformation::NameAccessAllowed property would be set to false)

	//Set username
	tory.wUsername = wideUsername;
}
//end getDisplayNameAsync

//Fills cylonStruct with timezone name, UTC offset bias, and dst flag
void produceTimeZone(struct cylonStruct& tory)
{
	//Variable Declaration
	DWORD					tzResult;
	TIME_ZONE_INFORMATION	tzinfo;
	std::wstring			timezoneName;

	//grab and convert bias
	tzResult	= GetTimeZoneInformation(&tzinfo);

	//set bias
	tory.timeZone = tzinfo.Bias;

	//Check DWORD value
	if (tzResult == TIME_ZONE_ID_STANDARD)
	{
		//standard time
		tory.dst = 0;
	}
	else if (tzResult == TIME_ZONE_ID_DAYLIGHT)
	{
		//daylight time
		tory.dst = 1;
	}
	else
	{
		//otherwise or invalid ==> shenanigans
		//"Oh hell! I have to run home and grab my broom!"
		tory.dst = 2;  //value is arbitrary
	}
	//end if

	//grab time zone name
	std::wstring standardName;

	//grab name from TimeZoneInformation
	standardName = tzinfo.StandardName;

	//place string name into tory
	tory.wTimeZoneName = standardName;
}
//end produceBias

//Grabs time information and stores it in cylonStruct
void produceDateTime(struct cylonStruct& tory)
{
	//Variable declaration
	SYSTEMTIME st;

	//init st
	GetLocalTime(&st);

	//grab values from SYSTEMTIME
	tory.milliseconds	= st.wMilliseconds;
	tory.seconds		= st.wSecond;
	tory.minutes		= st.wMinute;
	tory.hours			= st.wHour;

	tory.day			= st.wDayOfWeek;
	tory.date			= st.wDay;
	tory.month			= st.wMonth;
	tory.year			= st.wYear;
}
//end produceDateTime

//populates tory's device name
void produceDeviceName(struct cylonStruct& tory)
{
	//Variable declaration
	int				result;
	int				size_needed;
	char			hostBuffer[MAX_PATH];
	std::string		deviceName;
	WSAData			wsa_data;

	//start WSA
	WSAStartup(MAKEWORD(1, 1), &wsa_data);

	//grab result
	result		= gethostname(hostBuffer, MAX_PATH);
	deviceName	= hostBuffer;

	//check socket errors
	int error;
	error = WSAGetLastError();

	//cleanup WSA
	WSACleanup();

	//convert string to wstring
	size_needed = MultiByteToWideChar(CP_UTF8, 0, &deviceName[0], (int)deviceName.size(), NULL, 0);
	std::wstring wDeviceName(size_needed, 0);
	MultiByteToWideChar(CP_UTF8, 0, &deviceName[0], (int)deviceName.size(), &wDeviceName[0], size_needed);

	//set device name for tory
	tory.wDeviceName = wDeviceName;
}
//end produceDeviceName

//for getting processor info
void produceProcessorInfo(struct cylonStruct& tf)
{
	//Variable Declaration
	SYSTEM_INFO sysinfo;
	unsigned int architecture;

	//Grab system info
	GetNativeSystemInfo(&sysinfo);

	//test
	int one = 9;

	one = one * 9;
	//end test

	//Convert results into local values
	//Convert architecture
	if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
	{
		//x64 (AMD or Intel)
		architecture = 1;
	}
	else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM)
	{
		//ARM
		architecture = 2;
	}
	else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
	{
		//Intel Itanium-based
		architecture = 3;
	}
	else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
	{
		//x86
		architecture = 4;
	}
	else
	{
		//unknown error
		architecture = 0;
	}
	//end if

	//set tory architecture
	tf.architecture = architecture;

	//set tory page size
	tf.pageSize = (unsigned long)sysinfo.dwPageSize;

	//set the min and max pointers for apps
	tf.minAppAddress = (void*)sysinfo.lpMinimumApplicationAddress;
	tf.maxAppAddress = (void*)sysinfo.lpMaximumApplicationAddress;

	//set the number of processors
	tf.processorCount = (unsigned long)sysinfo.dwNumberOfProcessors;

	//set allocation granularity
	tf.allocationGranularity = (unsigned long)sysinfo.dwAllocationGranularity;

	//TODO grab hertz
}
//end produce processor info

//for getting memory info
void produceMemoryInfo(struct cylonStruct& tf)
{
	//TODO get memory
}
//end produceMemoryInfo

//for getting account picture
void produceAccountPicture(struct cylonStruct& tf)
{
	//variable declaration
	Windows::System::UserProfile::AccountPictureKind kind = Windows::System::UserProfile::AccountPictureKind::SmallImage;
	Windows::Storage::IStorageFile^ picture;
	std::wstring pictureType;
	const wchar_t* typeDataPointer;

	//retrieve picture
	picture = Windows::System::UserProfile::UserInformation::GetAccountPicture(kind);

	//set picture
	tf.picture = picture;

	//convert picture type to wstring
	typeDataPointer = picture->FileType->Data();
	pictureType = std::wstring(typeDataPointer);

	//set picture type
	tf.pictureType = pictureType;
}
//end produceAccountPicture

//Constructor
//build Tory
struct cylonStruct buildTory()
{
	//Variable Declartion
	struct cylonStruct tory;

	//username
	produceUsername(tory);

	//device name
	produceDeviceName(tory);

	//time zone
	produceTimeZone(tory);

	//date and time
	produceDateTime(tory);

	//processor
	produceProcessorInfo(tory);

	//picture
	produceAccountPicture(tory);

	//TODO add more host queries

	//return
	return tory;
}
//end build tory<commit_msg>remove debugging code<commit_after>//Foster.cpp
//Implements definitions of Foster functionality.
//"Bad becomes good" - Tory Foster
//josh@mindaptiv.com

//includes
#include "pch.h"
#include "Foster.h"
#include <windows.foundation.h>
#include <windows.system.h>
#include <sysinfoapi.h>

//If Visual Studio freaks out about this code someday, add this line back in OR modify your project settings
//#pragma comment(lib, "Ws2_32.lib")

//Method definitions:
//getters
unsigned int getFosterMilliseconds(struct cylonStruct tf)
{
	//return
	return tf.milliseconds;
}

unsigned int getFosterSeconds(struct cylonStruct tf)
{
	//return
	return tf.seconds;
}

unsigned int getFosterMinutes(struct cylonStruct tf)
{
	//return
	return tf.minutes;
}

unsigned int getFosterHours(struct cylonStruct tf)
{
	//return
	return tf.hours;
}

unsigned int getFosterDay(struct cylonStruct tf)
{
	//return
	return tf.day;
}

unsigned int getFosterDate(struct cylonStruct tf)
{
	//return
	return tf.date;
}

unsigned int getFosterMonth(struct cylonStruct tf)
{
	//return
	return tf.month;
}

unsigned int getFosterYear(struct cylonStruct tf)
{
	//return
	return tf.year;
}

long getFosterTimeZone(struct cylonStruct tf)
{
	//return
	return tf.timeZone;
}

unsigned int getFosterDST(struct cylonStruct tf)
{
	//return
	return tf.dst;
}

std::wstring getFosterTimeZoneName(struct cylonStruct tf)
{
	//return
	return tf.wTimeZoneName;
}

std::wstring getFosterUsername(struct cylonStruct tf)
{
	//return
	return tf.wUsername;
}

std::wstring getFosterDeviceName(struct cylonStruct tf)
{
	//return
	return tf.wDeviceName;
}

unsigned short getFosterArchitecture(struct cylonStruct tf)
{
	//return
	return tf.architecture;
}

unsigned short getFosterProcessorLevel(struct cylonStruct tf)
{
	//return
	return tf.processorLevel;
}

unsigned long getFosterPageSize(struct cylonStruct tf)
{
	//return
	return tf.pageSize;
}

unsigned long getFosterProcessorCount(struct cylonStruct tf)
{
	//return
	return tf.processorCount;
}

unsigned long getFosterAllocationGranularity(struct cylonStruct tf)
{
	//return
	return tf.allocationGranularity;
}

void* getFosterMinAppAddress(struct cylonStruct tf)
{
	//return
	return tf.minAppAddress;
}

void* getFosterMaxAppAddress(struct cylonStruct tf)
{
	//return
	return tf.maxAppAddress;
}

std::wstring getFosterPictureType(struct cylonStruct tf)
{
	//return
	return tf.pictureType;

}

Windows::Storage::IStorageFile^ getFosterPictureFile(struct cylonStruct tf)
{
	//return
	return tf.picture;
}
//end getters

//for getting username
void produceUsername(struct cylonStruct& tory)
{
	//Variable declaration
	Platform::String^ managedUsername;
	Windows::Foundation::IAsyncOperation<Platform::String^>^ operation;
	const wchar_t* operationDataPointer;
	std::wstring wideUsername;
	std::string username;

	//Retrieve username
	operation			= Windows::System::UserProfile::UserInformation::GetDisplayNameAsync();
	while(	operation->Status == Windows::Foundation::AsyncStatus::Started)
	{
		//WAIT, YO
	}
	managedUsername = operation->GetResults();
	operation->Close();

	//Convert username to std::wstring
	operationDataPointer	= managedUsername->Data();
	wideUsername			= std::wstring(operationDataPointer);
	//TODO convert from wstring to string

	//TODO: check if retrieved username is empty string? (therefore UserInformation::NameAccessAllowed property would be set to false)

	//Set username
	tory.wUsername = wideUsername;
}
//end getDisplayNameAsync

//Fills cylonStruct with timezone name, UTC offset bias, and dst flag
void produceTimeZone(struct cylonStruct& tory)
{
	//Variable Declaration
	DWORD					tzResult;
	TIME_ZONE_INFORMATION	tzinfo;
	std::wstring			timezoneName;

	//grab and convert bias
	tzResult	= GetTimeZoneInformation(&tzinfo);

	//set bias
	tory.timeZone = tzinfo.Bias;

	//Check DWORD value
	if (tzResult == TIME_ZONE_ID_STANDARD)
	{
		//standard time
		tory.dst = 0;
	}
	else if (tzResult == TIME_ZONE_ID_DAYLIGHT)
	{
		//daylight time
		tory.dst = 1;
	}
	else
	{
		//otherwise or invalid ==> shenanigans
		//"Oh hell! I have to run home and grab my broom!"
		tory.dst = 2;  //value is arbitrary
	}
	//end if

	//grab time zone name
	std::wstring standardName;

	//grab name from TimeZoneInformation
	standardName = tzinfo.StandardName;

	//place string name into tory
	tory.wTimeZoneName = standardName;
}
//end produceBias

//Grabs time information and stores it in cylonStruct
void produceDateTime(struct cylonStruct& tory)
{
	//Variable declaration
	SYSTEMTIME st;

	//init st
	GetLocalTime(&st);

	//grab values from SYSTEMTIME
	tory.milliseconds	= st.wMilliseconds;
	tory.seconds		= st.wSecond;
	tory.minutes		= st.wMinute;
	tory.hours			= st.wHour;

	tory.day			= st.wDayOfWeek;
	tory.date			= st.wDay;
	tory.month			= st.wMonth;
	tory.year			= st.wYear;
}
//end produceDateTime

//populates tory's device name
void produceDeviceName(struct cylonStruct& tory)
{
	//Variable declaration
	int				result;
	int				size_needed;
	char			hostBuffer[MAX_PATH];
	std::string		deviceName;
	WSAData			wsa_data;

	//start WSA
	WSAStartup(MAKEWORD(1, 1), &wsa_data);

	//grab result
	result		= gethostname(hostBuffer, MAX_PATH);
	deviceName	= hostBuffer;

	//check socket errors
	int error;
	error = WSAGetLastError();

	//cleanup WSA
	WSACleanup();

	//convert string to wstring
	size_needed = MultiByteToWideChar(CP_UTF8, 0, &deviceName[0], (int)deviceName.size(), NULL, 0);
	std::wstring wDeviceName(size_needed, 0);
	MultiByteToWideChar(CP_UTF8, 0, &deviceName[0], (int)deviceName.size(), &wDeviceName[0], size_needed);

	//set device name for tory
	tory.wDeviceName = wDeviceName;
}
//end produceDeviceName

//for getting processor info
void produceProcessorInfo(struct cylonStruct& tf)
{
	//Variable Declaration
	SYSTEM_INFO sysinfo;
	unsigned int architecture;

	//Grab system info
	GetNativeSystemInfo(&sysinfo);

	//Convert results into local values
	//Convert architecture
	if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
	{
		//x64 (AMD or Intel)
		architecture = 1;
	}
	else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM)
	{
		//ARM
		architecture = 2;
	}
	else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
	{
		//Intel Itanium-based
		architecture = 3;
	}
	else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
	{
		//x86
		architecture = 4;
	}
	else
	{
		//unknown error
		architecture = 0;
	}
	//end if

	//set tory architecture
	tf.architecture = architecture;

	//set tory page size
	tf.pageSize = (unsigned long)sysinfo.dwPageSize;

	//set the min and max pointers for apps
	tf.minAppAddress = (void*)sysinfo.lpMinimumApplicationAddress;
	tf.maxAppAddress = (void*)sysinfo.lpMaximumApplicationAddress;

	//set the number of processors
	tf.processorCount = (unsigned long)sysinfo.dwNumberOfProcessors;

	//set allocation granularity
	tf.allocationGranularity = (unsigned long)sysinfo.dwAllocationGranularity;

	//TODO grab hertz
}
//end produce processor info

//for getting memory info
void produceMemoryInfo(struct cylonStruct& tf)
{
	//TODO get memory
}
//end produceMemoryInfo

//for getting account picture
void produceAccountPicture(struct cylonStruct& tf)
{
	//variable declaration
	Windows::System::UserProfile::AccountPictureKind kind = Windows::System::UserProfile::AccountPictureKind::SmallImage;
	Windows::Storage::IStorageFile^ picture;
	std::wstring pictureType;
	const wchar_t* typeDataPointer;

	//retrieve picture
	picture = Windows::System::UserProfile::UserInformation::GetAccountPicture(kind);

	//set picture
	tf.picture = picture;

	//convert picture type to wstring
	typeDataPointer = picture->FileType->Data();
	pictureType = std::wstring(typeDataPointer);

	//set picture type
	tf.pictureType = pictureType;
}
//end produceAccountPicture

//Constructor
//build Tory
struct cylonStruct buildTory()
{
	//Variable Declartion
	struct cylonStruct tory;

	//username
	produceUsername(tory);

	//device name
	produceDeviceName(tory);

	//time zone
	produceTimeZone(tory);

	//date and time
	produceDateTime(tory);

	//processor
	produceProcessorInfo(tory);

	//picture
	produceAccountPicture(tory);

	//TODO add more host queries

	//return
	return tory;
}
//end build tory<|endoftext|>


<commit_before>//===- tools/dsymutil/CFBundle.cpp - CFBundle helper ------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "CFBundle.h"

#ifdef __APPLE__
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include <CoreFoundation/CoreFoundation.h>
#include <assert.h>
#include <glob.h>
#include <memory>
#endif

namespace llvm {
namespace dsymutil {

#ifdef __APPLE__
/// Deleter that calls CFRelease rather than deleting the pointer.
template <typename T> struct CFDeleter {
  void operator()(T *P) {
    if (P)
      ::CFRelease(P);
  }
};

/// This helper owns any CoreFoundation pointer and will call CFRelease() on
/// any valid pointer it owns unless that pointer is explicitly released using
/// the release() member function.
template <typename T>
using CFReleaser =
    std::unique_ptr<typename std::remove_pointer<T>::type,
                    CFDeleter<typename std::remove_pointer<T>::type>>;

/// RAII wrapper around CFBundleRef.
class CFString : public CFReleaser<CFStringRef> {
public:
  CFString(CFStringRef CFStr = nullptr) : CFReleaser<CFStringRef>(CFStr) {}

  const char *UTF8(std::string &Str) const {
    return CFString::UTF8(get(), Str);
  }

  CFIndex GetLength() const {
    if (CFStringRef Str = get())
      return CFStringGetLength(Str);
    return 0;
  }

  static const char *UTF8(CFStringRef CFStr, std::string &Str);
};

/// Static function that puts a copy of the UTF8 contents of CFStringRef into
/// std::string and returns the C string pointer that is contained in the
/// std::string when successful, nullptr otherwise.
///
/// This allows the std::string parameter to own the extracted string, and also
/// allows that string to be returned as a C string pointer that can be used.
const char *CFString::UTF8(CFStringRef CFStr, std::string &Str) {
  if (!CFStr)
    return nullptr;

  const CFStringEncoding Encoding = kCFStringEncodingUTF8;
  CFIndex MaxUTF8StrLength = CFStringGetLength(CFStr);
  MaxUTF8StrLength =
      CFStringGetMaximumSizeForEncoding(MaxUTF8StrLength, Encoding);
  if (MaxUTF8StrLength > 0) {
    Str.resize(MaxUTF8StrLength);
    if (!Str.empty() &&
        CFStringGetCString(CFStr, &Str[0], Str.size(), Encoding)) {
      Str.resize(strlen(Str.c_str()));
      return Str.c_str();
    }
  }

  return nullptr;
}

/// RAII wrapper around CFBundleRef.
class CFBundle : public CFReleaser<CFBundleRef> {
public:
  CFBundle(const char *Path = nullptr) : CFReleaser<CFBundleRef>() {
    if (Path && Path[0])
      SetFromPath(Path);
  }

  CFBundle(CFURLRef url)
      : CFReleaser<CFBundleRef>(url ? ::CFBundleCreate(nullptr, url)
                                    : nullptr) {}

  /// Return the bundle identifier.
  CFStringRef GetIdentifier() const {
    if (CFBundleRef bundle = get())
      return ::CFBundleGetIdentifier(bundle);
    return nullptr;
  }

  /// Return value for key.
  CFTypeRef GetValueForInfoDictionaryKey(CFStringRef key) const {
    if (CFBundleRef bundle = get())
      return ::CFBundleGetValueForInfoDictionaryKey(bundle, key);
    return nullptr;
  }

private:
  /// Update this instance with a new bundle created from the given path.
  bool SetFromPath(const char *Path);
};

bool CFBundle::SetFromPath(const char *InPath) {
  // Release our old bundle and URL.
  reset();

  if (InPath && InPath[0]) {
    char ResolvedPath[PATH_MAX];
    const char *Path = ::realpath(InPath, ResolvedPath);
    if (Path == nullptr)
      Path = InPath;

    CFAllocatorRef Allocator = kCFAllocatorDefault;
    // Make our Bundle URL.
    CFReleaser<CFURLRef> BundleURL(::CFURLCreateFromFileSystemRepresentation(
        Allocator, (const UInt8 *)Path, strlen(Path), false));
    if (BundleURL.get()) {
      CFIndex LastLength = LONG_MAX;

      while (BundleURL.get() != nullptr) {
        // Check the Path range and make sure we didn't make it to just "/",
        // ".", or "..".
        CFRange rangeIncludingSeparators;
        CFRange range = ::CFURLGetByteRangeForComponent(
            BundleURL.get(), kCFURLComponentPath, &rangeIncludingSeparators);
        if (range.length > LastLength)
          break;

        reset(::CFBundleCreate(Allocator, BundleURL.get()));
        if (get() != nullptr) {
          if (GetIdentifier() != nullptr)
            break;
          reset();
        }
        BundleURL.reset(::CFURLCreateCopyDeletingLastPathComponent(
            Allocator, BundleURL.get()));

        LastLength = range.length;
      }
    }
  }

  return get() != nullptr;
}

#endif

/// On Darwin, try and find the original executable's Info.plist information
/// using CoreFoundation calls by creating a URL for the executable and
/// chopping off the last Path component. The CFBundle can then get the
/// identifier and grab any needed information from it directly. Return default
/// CFBundleInfo on other platforms.
CFBundleInfo getBundleInfo(StringRef ExePath) {
  CFBundleInfo BundleInfo;

#ifdef __APPLE__
  if (ExePath.empty() || !sys::fs::exists(ExePath))
    return BundleInfo;

  auto PrintError = [&](CFTypeID TypeID) {
    CFString TypeIDCFStr(::CFCopyTypeIDDescription(TypeID));
    std::string TypeIDStr;
    errs() << "The Info.plist key \"CFBundleShortVersionString\" is"
           << "a " << TypeIDCFStr.UTF8(TypeIDStr)
           << ", but it should be a string in: " << ExePath << ".\n";
  };

  CFBundle Bundle(ExePath.data());
  if (CFStringRef BundleID = Bundle.GetIdentifier()) {
    CFString::UTF8(BundleID, BundleInfo.IDStr);
    if (CFTypeRef TypeRef =
            Bundle.GetValueForInfoDictionaryKey(CFSTR("CFBundleVersion"))) {
      CFTypeID TypeID = ::CFGetTypeID(TypeRef);
      if (TypeID == ::CFStringGetTypeID())
        CFString::UTF8((CFStringRef)TypeRef, BundleInfo.VersionStr);
      else
        PrintError(TypeID);
    }
    if (CFTypeRef TypeRef = Bundle.GetValueForInfoDictionaryKey(
            CFSTR("CFBundleShortVersionString"))) {
      CFTypeID TypeID = ::CFGetTypeID(TypeRef);
      if (TypeID == ::CFStringGetTypeID())
        CFString::UTF8((CFStringRef)TypeRef, BundleInfo.ShortVersionStr);
      else
        PrintError(TypeID);
    }
  }
#endif

  return BundleInfo;
}

} // end namespace dsymutil
} // end namespace llvm
<commit_msg>[dsymutil][NFC] Replace calls to CoreFoundation with LLVM equivalent.<commit_after>//===- tools/dsymutil/CFBundle.cpp - CFBundle helper ------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "CFBundle.h"

#ifdef __APPLE__
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <CoreFoundation/CoreFoundation.h>
#include <assert.h>
#include <glob.h>
#include <memory>
#endif

namespace llvm {
namespace dsymutil {

#ifdef __APPLE__
/// Deleter that calls CFRelease rather than deleting the pointer.
template <typename T> struct CFDeleter {
  void operator()(T *P) {
    if (P)
      ::CFRelease(P);
  }
};

/// This helper owns any CoreFoundation pointer and will call CFRelease() on
/// any valid pointer it owns unless that pointer is explicitly released using
/// the release() member function.
template <typename T>
using CFReleaser =
    std::unique_ptr<typename std::remove_pointer<T>::type,
                    CFDeleter<typename std::remove_pointer<T>::type>>;

/// RAII wrapper around CFBundleRef.
class CFString : public CFReleaser<CFStringRef> {
public:
  CFString(CFStringRef CFStr = nullptr) : CFReleaser<CFStringRef>(CFStr) {}

  const char *UTF8(std::string &Str) const {
    return CFString::UTF8(get(), Str);
  }

  CFIndex GetLength() const {
    if (CFStringRef Str = get())
      return CFStringGetLength(Str);
    return 0;
  }

  static const char *UTF8(CFStringRef CFStr, std::string &Str);
};

/// Static function that puts a copy of the UTF-8 contents of CFStringRef into
/// std::string and returns the C string pointer that is contained in the
/// std::string when successful, nullptr otherwise.
///
/// This allows the std::string parameter to own the extracted string, and also
/// allows that string to be returned as a C string pointer that can be used.
const char *CFString::UTF8(CFStringRef CFStr, std::string &Str) {
  if (!CFStr)
    return nullptr;

  const CFStringEncoding Encoding = kCFStringEncodingUTF8;
  CFIndex MaxUTF8StrLength = CFStringGetLength(CFStr);
  MaxUTF8StrLength =
      CFStringGetMaximumSizeForEncoding(MaxUTF8StrLength, Encoding);
  if (MaxUTF8StrLength > 0) {
    Str.resize(MaxUTF8StrLength);
    if (!Str.empty() &&
        CFStringGetCString(CFStr, &Str[0], Str.size(), Encoding)) {
      Str.resize(strlen(Str.c_str()));
      return Str.c_str();
    }
  }

  return nullptr;
}

/// RAII wrapper around CFBundleRef.
class CFBundle : public CFReleaser<CFBundleRef> {
public:
  CFBundle(StringRef Path) : CFReleaser<CFBundleRef>() { SetFromPath(Path); }

  CFBundle(CFURLRef Url)
      : CFReleaser<CFBundleRef>(Url ? ::CFBundleCreate(nullptr, Url)
                                    : nullptr) {}

  /// Return the bundle identifier.
  CFStringRef GetIdentifier() const {
    if (CFBundleRef bundle = get())
      return ::CFBundleGetIdentifier(bundle);
    return nullptr;
  }

  /// Return value for key.
  CFTypeRef GetValueForInfoDictionaryKey(CFStringRef key) const {
    if (CFBundleRef bundle = get())
      return ::CFBundleGetValueForInfoDictionaryKey(bundle, key);
    return nullptr;
  }

private:
  /// Helper to initialize this instance with a new bundle created from the
  /// given path. This function will recursively remove components from the
  /// path in its search for the nearest Info.plist.
  void SetFromPath(StringRef Path);
};

void CFBundle::SetFromPath(StringRef Path) {
  // Start from an empty/invalid CFBundle.
  reset();

  if (Path.empty() || !sys::fs::exists(Path))
    return;

  SmallString<256> RealPath;
  sys::fs::real_path(Path, RealPath, /*expand_tilde*/ true);

  do {
    // Create a CFURL from the current path and use it to create a CFBundle.
    CFReleaser<CFURLRef> BundleURL(::CFURLCreateFromFileSystemRepresentation(
        kCFAllocatorDefault, (const UInt8 *)RealPath.data(), RealPath.size(),
        false));
    reset(::CFBundleCreate(kCFAllocatorDefault, BundleURL.get()));

    // If we have a valid bundle and find its identifier we are done.
    if (get() != nullptr) {
      if (GetIdentifier() != nullptr)
        return;
      reset();
    }

    // Remove the last component of the path and try again until there's
    // nothing left but the root.
    sys::path::remove_filename(RealPath);
  } while (RealPath != sys::path::root_name(RealPath));
}
#endif

/// On Darwin, try and find the original executable's Info.plist to extract
/// information about the bundle. Return default values on other platforms.
CFBundleInfo getBundleInfo(StringRef ExePath) {
  CFBundleInfo BundleInfo;

#ifdef __APPLE__
  auto PrintError = [&](CFTypeID TypeID) {
    CFString TypeIDCFStr(::CFCopyTypeIDDescription(TypeID));
    std::string TypeIDStr;
    errs() << "The Info.plist key \"CFBundleShortVersionString\" is"
           << "a " << TypeIDCFStr.UTF8(TypeIDStr)
           << ", but it should be a string in: " << ExePath << ".\n";
  };

  CFBundle Bundle(ExePath);
  if (CFStringRef BundleID = Bundle.GetIdentifier()) {
    CFString::UTF8(BundleID, BundleInfo.IDStr);
    if (CFTypeRef TypeRef =
            Bundle.GetValueForInfoDictionaryKey(CFSTR("CFBundleVersion"))) {
      CFTypeID TypeID = ::CFGetTypeID(TypeRef);
      if (TypeID == ::CFStringGetTypeID())
        CFString::UTF8((CFStringRef)TypeRef, BundleInfo.VersionStr);
      else
        PrintError(TypeID);
    }
    if (CFTypeRef TypeRef = Bundle.GetValueForInfoDictionaryKey(
            CFSTR("CFBundleShortVersionString"))) {
      CFTypeID TypeID = ::CFGetTypeID(TypeRef);
      if (TypeID == ::CFStringGetTypeID())
        CFString::UTF8((CFStringRef)TypeRef, BundleInfo.ShortVersionStr);
      else
        PrintError(TypeID);
    }
  }
#endif

  return BundleInfo;
}

} // end namespace dsymutil
} // end namespace llvm
<|endoftext|>


<commit_before>#include "Player.h"

Player::~Player()
{
}

void Player::Update(float deltaTime)//make this affected by delta time
{
	// Calculate velocity based on pixels-per-frame
	pos_.x += velocity.x * deltaTime;
	pos_.y += velocity.y * deltaTime;

	// Add acceleration to velocity
	if (abs(velocity.x) < 100) {
		velocity.x += acc.x;
	};

	velocity.y += acc.y;

	SpriteAnimation::Update(deltaTime);
}

void Player::OnKeyDown(Uint16 key)
{
	switch (key)
	{
	case SDL_SCANCODE_RIGHT:
		velocity.x = 1 * playerSpeed;
		break;
	case SDL_SCANCODE_LEFT:
		velocity.x = 1 * -playerSpeed;
		break;
	case SDL_SCANCODE_SPACE:
		break;
	}
	if (!playing_)
	{
		Play(true);
	}
	UpdateCurrAnimation();
}

void Player::OnKeyUp(Uint16 key)
{
	switch (key)
	{
	case SDL_SCANCODE_RIGHT:
		velocity.x = 0;
		break;
	case SDL_SCANCODE_LEFT:
		velocity.x = 0;
		break;
	case SDL_SCANCODE_SPACE:
		if (onGround)
		{
			velocity.y = -1 * jumpSpeed;
			onGround = false;
			//velocity.y = -1 * jumpSpeed;
			//need jump timer, max hold space bar timer and then gravity pulls down darude.
		}
		break;
	}
	if (!playing_)
	{
		Play(true);
	}
	UpdateCurrAnimation();
}

void Player::UpdateCurrAnimation()
{
	if ((velocity.y > 0 && velocity.x > 0) && currentAnim != ANIM_JUMP_RIGHT)
	{
		currentAnim = ANIM_JUMP_RIGHT;
		SetStartFrame(6);
	}
	else if ((velocity.y > 0 && velocity.x < 0) && currentAnim != ANIM_JUMP_LEFT)
	{
		currentAnim = ANIM_JUMP_LEFT;
		SetStartFrame(9);
	}
	else if (velocity.x > 0 && currentAnim != ANIM_RUN_RIGHT)
	{
		currentAnim = ANIM_RUN_RIGHT;
		SetStartFrame(0);
	}
	else if (velocity.x < 0 && currentAnim != ANIM_RUN_LEFT)
	{
		currentAnim = ANIM_RUN_LEFT;
		SetStartFrame(3);
	}
	else if (velocity.x == 0 && currentAnim == ANIM_RUN_RIGHT)
	{
		currentAnim = ANIM_IDLE_RIGHT;
		SetStartFrame(12);
	}
	else if (velocity.x == 0 && currentAnim == ANIM_RUN_LEFT)
	{
		currentAnim = ANIM_IDLE_LEFT;
		SetStartFrame(15);
	}
}
<commit_msg>jibrils bug fix<commit_after>#include "Player.h"

Player::~Player()
{
}

void Player::Update(float deltaTime)//make this affected by delta time
{
	// Calculate velocity based on pixels-per-frame
	pos_.x += velocity.x * deltaTime;
	pos_.y += velocity.y * deltaTime;

	// Add acceleration to velocity
	if (abs(velocity.x) < 100) {
		velocity.x += acc.x;
	};

	if (!onGround)
	{
		velocity.y += acc.y;
	}

	SpriteAnimation::Update(deltaTime);
}

void Player::OnKeyDown(Uint16 key)
{
	switch (key)
	{
	case SDL_SCANCODE_RIGHT:
		velocity.x = 1 * playerSpeed;
		break;
	case SDL_SCANCODE_LEFT:
		velocity.x = 1 * -playerSpeed;
		break;
	case SDL_SCANCODE_SPACE:
		break;
	}
	if (!playing_)
	{
		Play(true);
	}
	UpdateCurrAnimation();
}

void Player::OnKeyUp(Uint16 key)
{
	switch (key)
	{
	case SDL_SCANCODE_RIGHT:
		velocity.x = 0;
		break;
	case SDL_SCANCODE_LEFT:
		velocity.x = 0;
		break;
	case SDL_SCANCODE_SPACE:
		if (onGround)
		{
			velocity.y = -1 * jumpSpeed;
			onGround = false;
			//velocity.y = -1 * jumpSpeed;
			//need jump timer, max hold space bar timer and then gravity pulls down darude.
		}
		break;
	}
	if (!playing_)
	{
		Play(true);
	}
	UpdateCurrAnimation();
}

void Player::UpdateCurrAnimation()
{
	if ((velocity.y > 0 && velocity.x > 0) && currentAnim != ANIM_JUMP_RIGHT)
	{
		currentAnim = ANIM_JUMP_RIGHT;
		SetStartFrame(6);
	}
	else if ((velocity.y > 0 && velocity.x < 0) && currentAnim != ANIM_JUMP_LEFT)
	{
		currentAnim = ANIM_JUMP_LEFT;
		SetStartFrame(9);
	}
	else if (velocity.x > 0 && currentAnim != ANIM_RUN_RIGHT)
	{
		currentAnim = ANIM_RUN_RIGHT;
		SetStartFrame(0);
	}
	else if (velocity.x < 0 && currentAnim != ANIM_RUN_LEFT)
	{
		currentAnim = ANIM_RUN_LEFT;
		SetStartFrame(3);
	}
	else if (velocity.x == 0 && currentAnim == ANIM_RUN_RIGHT)
	{
		currentAnim = ANIM_IDLE_RIGHT;
		SetStartFrame(12);
	}
	else if (velocity.x == 0 && currentAnim == ANIM_RUN_LEFT)
	{
		currentAnim = ANIM_IDLE_LEFT;
		SetStartFrame(15);
	}
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkGeometry2DData.h"
#include "mitkBaseProcess.h"

//##ModelId=3E639CD30201
mitk::Geometry2DData::Geometry2DData()
{
}

//##ModelId=3E639CD30233
mitk::Geometry2DData::~Geometry2DData()
{
}

void mitk::Geometry2DData::SetGeometry(mitk::Geometry3D *geometry)
{
  if(geometry==NULL)
    SetGeometry2D(NULL);
  else
  {
    Geometry2D* geometry2d = dynamic_cast<Geometry2D*>(geometry);
    if(geometry2d==NULL)
      itkExceptionMacro(<<"Trying to set a geometry which is not a Geometry2D into Geometry2DData.");
    SetGeometry2D(geometry2d);
  }
}

//##ModelId=3E6423D2030E
void mitk::Geometry2DData::SetGeometry2D(mitk::Geometry2D *geometry2d)
{
  Superclass::SetGeometry(geometry2d);
}

//##ModelId=3E66CC5A0295
void mitk::Geometry2DData::UpdateOutputInformation()
{
  Superclass::UpdateOutputInformation();
}

//##ModelId=3E66CC5A02B4
void mitk::Geometry2DData::SetRequestedRegionToLargestPossibleRegion()
{

}

//##ModelId=3E66CC5A02D2
bool mitk::Geometry2DData::RequestedRegionIsOutsideOfTheBufferedRegion()
{
  if(GetGeometry2D()==NULL) return true;

  return false;
}

//##ModelId=3E66CC5A02F0
bool mitk::Geometry2DData::VerifyRequestedRegion()
{
  if(GetGeometry2D()==NULL) return false;

  return true;
}

//##ModelId=3E66CC5A030E
void mitk::Geometry2DData::SetRequestedRegion(itk::DataObject *data)
{

}

//##ModelId=3E67D85E00B7
void mitk::Geometry2DData::CopyInformation(const itk::DataObject *data)
{
}
<commit_msg>ENH: slight optimization<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkGeometry2DData.h"
#include "mitkBaseProcess.h"

//##ModelId=3E639CD30201
mitk::Geometry2DData::Geometry2DData()
{
}

//##ModelId=3E639CD30233
mitk::Geometry2DData::~Geometry2DData()
{
}

void mitk::Geometry2DData::SetGeometry(mitk::Geometry3D *geometry)
{
  if(geometry==NULL)
    SetGeometry2D(NULL);
  else
  {
    Geometry2D* geometry2d = dynamic_cast<Geometry2D*>(geometry);
    if(geometry2d==NULL)
      itkExceptionMacro(<<"Trying to set a geometry which is not a Geometry2D into Geometry2DData.");
    SetGeometry2D(geometry2d);
  }
}

//##ModelId=3E6423D2030E
void mitk::Geometry2DData::SetGeometry2D(mitk::Geometry2D *geometry2d)
{
  if(geometry2d != NULL)
  {
    TimeSlicedGeometry* timeSlicedGeometry = GetTimeSlicedGeometry();
    if(timeSlicedGeometry == NULL)
    {
      Superclass::SetGeometry(geometry2d);
      return;
    }
    timeSlicedGeometry->InitializeEvenlyTimed(geometry2d, 1);
    Modified();
  }
  else
    Superclass::SetGeometry(geometry2d);
}

//##ModelId=3E66CC5A0295
void mitk::Geometry2DData::UpdateOutputInformation()
{
  Superclass::UpdateOutputInformation();
}

//##ModelId=3E66CC5A02B4
void mitk::Geometry2DData::SetRequestedRegionToLargestPossibleRegion()
{

}

//##ModelId=3E66CC5A02D2
bool mitk::Geometry2DData::RequestedRegionIsOutsideOfTheBufferedRegion()
{
  if(GetGeometry2D()==NULL) return true;

  return false;
}

//##ModelId=3E66CC5A02F0
bool mitk::Geometry2DData::VerifyRequestedRegion()
{
  if(GetGeometry2D()==NULL) return false;

  return true;
}

//##ModelId=3E66CC5A030E
void mitk::Geometry2DData::SetRequestedRegion(itk::DataObject *data)
{

}

//##ModelId=3E67D85E00B7
void mitk::Geometry2DData::CopyInformation(const itk::DataObject *data)
{
}
<|endoftext|>


<commit_before>#include <kv/Heine.hpp>
#include <kv/qAiry.hpp>
#include <cmath>
typedef kv::interval<double> itv;
typedef kv::complex< kv::interval<double> > cp;
using namespace std;
int main()
{
  cout.precision(17);
  int n=50;
  itv x,q;
  q="0.7";

  x=3.5;
  for(int i=1;i<=n;i++){
    x=x-kv::Ramanujan_qAiry(itv(q),itv(x))*(1-q)*x
      /(kv::Ramanujan_qAiry(itv(q),itv(x))-kv::Ramanujan_qAiry(itv(q),itv(q*x)));
  cout<<x<<endl;
  cout<<"value of RqA"<<kv::Ramanujan_qAiry(itv(q),itv(x))<<endl;
  }
}
<commit_msg>Update RqAqNewton.cc<commit_after>#include <kv/Heine.hpp>
#include <kv/qAiry.hpp>
#include <cmath>
typedef kv::interval<double> itv;
typedef kv::complex< kv::interval<double> > cp;
using namespace std;
int main()
{
  cout.precision(17);
  int n=50;
  itv x,q;
  q="0.7";

  x=3.5;
  for(int i=1;i<=n;i++){
    x=x-kv::Ramanujan_qAiry(itv(q),itv(x))*(1-q)*x
      /(kv::Ramanujan_qAiry(itv(q),itv(x))-kv::Ramanujan_qAiry(itv(q),itv(q*x)));
  cout<<x<<endl;
  cout<<"value of RqA inf"<<kv::Ramanujan_qAiry(itv(q),itv(x.lower()))<<endl;
  cout<<"value of RqA sup"<<kv::Ramanujan_qAiry(itv(q),itv(x.upper()))<<endl;
  cout<<"value of RqA mid"<<kv::Ramanujan_qAiry(itv(q),itv(mid(x)))<<endl;
  }
}
<|endoftext|>


<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// A collection of various data filters
//
// =============================================================================

#include <algorithm>

#include "chrono/utils/ChFilters.h"
#include "chrono/core/ChMathematics.h"

namespace chrono {
namespace utils {

// -----------------------------------------------------------------------------
ChRunningAverage::ChRunningAverage(int n) : m_n(n), m_index(0), m_std(0) {
    m_data.resize(n, 0.0);
}

double ChRunningAverage::Add(double val) {
    m_data[(m_index++) % m_n] = val;
    int size = std::min(m_index, m_n);
    double mean = m_data.sum() / size;
    m_std = std::sqrt(std::pow(m_data - mean, 2.0).sum() / (size - 1));
    return mean;
}

// -----------------------------------------------------------------------------
ChMovingAverage::ChMovingAverage(const std::valarray<double>& data, int n) : m_n(n) {
    int np = (int) data.size();
    m_out.resize(np);

    // Start and end of data
    int lim = ChMin(n, np);
    for (int i = 0; i < lim; i++) {
        m_out[i] = data[i];
        for (int j = 1; j <= i; j++)
            m_out[i] += data[i - j] + data[i + j];
        m_out[i] /= (2 * i + 1);
    }

    for (int i = 0; i < lim; i++) {
        m_out[np - 1 - i] = data[np - 1 - i];
        for (int j = 1; j <= i; j++)
            m_out[np - 1 - i] += data[np - 1 - i - j] + data[np - 1 - i + j];
        m_out[np - 1 - i] /= (2 * i + 1);
    }

    // Middle values
    for (int i = lim; i < np - lim; i++) {
        m_out[i] = data[i];
        for (int j = 1; j <= n; j++)
            m_out[i] += data[i - j] + data[i + j];
        m_out[i] /= (2 * n + 1);
    }
}

}  // end namespace utils
}  // end namespace chrono
<commit_msg>Fix issue with calculation of standard deviation at first point<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// A collection of various data filters
//
// =============================================================================

#include <algorithm>

#include "chrono/utils/ChFilters.h"
#include "chrono/core/ChMathematics.h"

namespace chrono {
namespace utils {

// -----------------------------------------------------------------------------
ChRunningAverage::ChRunningAverage(int n) : m_n(n), m_index(0), m_std(0) {
    m_data.resize(n, 0.0);
}

double ChRunningAverage::Add(double val) {
    m_data[(m_index++) % m_n] = val;
    int size = std::min(m_index, m_n);
    double mean = m_data.sum() / size;
    m_std = (size == 1) ? 0 : std::sqrt(std::pow(m_data - mean, 2.0).sum() / (size - 1));
    return mean;
}

// -----------------------------------------------------------------------------
ChMovingAverage::ChMovingAverage(const std::valarray<double>& data, int n) : m_n(n) {
    int np = (int) data.size();
    m_out.resize(np);

    // Start and end of data
    int lim = ChMin(n, np);
    for (int i = 0; i < lim; i++) {
        m_out[i] = data[i];
        for (int j = 1; j <= i; j++)
            m_out[i] += data[i - j] + data[i + j];
        m_out[i] /= (2 * i + 1);
    }

    for (int i = 0; i < lim; i++) {
        m_out[np - 1 - i] = data[np - 1 - i];
        for (int j = 1; j <= i; j++)
            m_out[np - 1 - i] += data[np - 1 - i - j] + data[np - 1 - i + j];
        m_out[np - 1 - i] /= (2 * i + 1);
    }

    // Middle values
    for (int i = lim; i < np - lim; i++) {
        m_out[i] = data[i];
        for (int j = 1; j <= n; j++)
            m_out[i] += data[i - j] + data[i + j];
        m_out[i] /= (2 * n + 1);
    }
}

}  // end namespace utils
}  // end namespace chrono
<|endoftext|>


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

#include "joynr/ImmutableMessage.h"

#include "joynr/Message.h"

namespace joynr
{

INIT_LOGGER(ImmutableMessage);

ImmutableMessage::ImmutableMessage(smrf::ByteVector&& serializedMessage, bool verifyInput)
        : serializedMessage(std::move(serializedMessage)),
          messageDeserializer(smrf::ByteArrayView(this->serializedMessage), verifyInput),
          receivedFromGlobal(false),
          bodyView(),
          decompressedBody()
{
    init();
}

ImmutableMessage::ImmutableMessage(const smrf::ByteVector& serializedMessage, bool verifyInput)
        : serializedMessage(serializedMessage),
          messageDeserializer(smrf::ByteArrayView(this->serializedMessage), verifyInput),
          receivedFromGlobal(false),
          bodyView(),
          decompressedBody()
{
    init();
}

std::string ImmutableMessage::getSender() const
{
    return messageDeserializer.getSender();
}

std::string ImmutableMessage::getRecipient() const
{
    return messageDeserializer.getRecipient();
}

bool ImmutableMessage::isTtlAbsolute() const
{
    return messageDeserializer.isTtlAbsolute();
}

const std::unordered_map<std::string, std::string>& ImmutableMessage::getHeaders() const
{
    return headers;
}

bool ImmutableMessage::isEncrypted() const
{
    return messageDeserializer.isEncrypted();
}

bool ImmutableMessage::isSigned() const
{
    return messageDeserializer.isSigned();
}

smrf::ByteArrayView ImmutableMessage::getUnencryptedBody() const
{
    if (!bodyView) {
        if (!messageDeserializer.isCompressed()) {
            bodyView = messageDeserializer.getBody();
        } else {
            decompressedBody = messageDeserializer.decompressBody();
            bodyView = smrf::ByteArrayView(*decompressedBody);
        }
    }
    return *bodyView;
}

std::string ImmutableMessage::toLogMessage() const
{
    return serializer::serializeToJson(*this);
}

const std::string& ImmutableMessage::getType() const
{
    return type;
}

const std::string& ImmutableMessage::getId() const
{
    return id;
}

boost::optional<std::string> ImmutableMessage::getReplyTo() const
{
    return getOptionalHeaderByKey(Message::HEADER_REPLY_TO());
}

boost::optional<std::string> ImmutableMessage::getEffort() const
{
    return getOptionalHeaderByKey(Message::HEADER_EFFORT());
}

JoynrTimePoint ImmutableMessage::getExpiryDate() const
{
    // for now we only support absolute TTLs
    assert(messageDeserializer.isTtlAbsolute());
    return JoynrTimePoint(std::chrono::milliseconds(messageDeserializer.getTtlMs()));
}

const smrf::ByteVector& ImmutableMessage::getSerializedMessage() const
{
    return serializedMessage;
}

std::size_t ImmutableMessage::getMessageSize() const
{
    return messageDeserializer.getMessageSize();
}

bool ImmutableMessage::isReceivedFromGlobal() const
{
    return receivedFromGlobal;
}

void ImmutableMessage::setReceivedFromGlobal(bool receivedFromGlobal)
{
    this->receivedFromGlobal = receivedFromGlobal;
}

void ImmutableMessage::setCreator(const std::string& creator)
{
    this->creator = creator;
}

void ImmutableMessage::setCreator(std::string&& creator)
{
    this->creator = std::move(creator);
}

const std::string& ImmutableMessage::getCreator() const
{
    return creator;
}

boost::optional<std::string> ImmutableMessage::getOptionalHeaderByKey(const std::string& key) const
{
    boost::optional<std::string> value;
    auto it = headers.find(key);
    if (it != headers.cend()) {
        value = it->second;
    }
    return value;
}

void ImmutableMessage::init()
{
    headers = messageDeserializer.getHeaders();
    boost::optional<std::string> optionalId = getOptionalHeaderByKey(Message::HEADER_ID());
    boost::optional<std::string> optionalType = getOptionalHeaderByKey(Message::HEADER_TYPE());

    JOYNR_LOG_TRACE(logger, "init: {}", toLogMessage());

    // check if necessary headers are set
    if (!optionalId.is_initialized() || !optionalType.is_initialized()) {
        throw std::invalid_argument("missing header");
    } else {
        id = std::move(*optionalId);
        type = std::move(*optionalType);
    }
}

} // namespace joynr
<commit_msg>[C++] fixed member initialization order in ImmutableMessage<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2017 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

#include "joynr/ImmutableMessage.h"

#include "joynr/Message.h"

namespace joynr
{

INIT_LOGGER(ImmutableMessage);

ImmutableMessage::ImmutableMessage(smrf::ByteVector&& serializedMessage, bool verifyInput)
        : serializedMessage(std::move(serializedMessage)),
          messageDeserializer(smrf::ByteArrayView(this->serializedMessage), verifyInput),
          headers(),
          bodyView(),
          decompressedBody(),
          receivedFromGlobal(false),
          creator(),
          id(),
          type()
{
    init();
}

ImmutableMessage::ImmutableMessage(const smrf::ByteVector& serializedMessage, bool verifyInput)
        : serializedMessage(serializedMessage),
          messageDeserializer(smrf::ByteArrayView(this->serializedMessage), verifyInput),
          headers(),
          bodyView(),
          decompressedBody(),
          receivedFromGlobal(false),
          creator(),
          id(),
          type()
{
    init();
}

std::string ImmutableMessage::getSender() const
{
    return messageDeserializer.getSender();
}

std::string ImmutableMessage::getRecipient() const
{
    return messageDeserializer.getRecipient();
}

bool ImmutableMessage::isTtlAbsolute() const
{
    return messageDeserializer.isTtlAbsolute();
}

const std::unordered_map<std::string, std::string>& ImmutableMessage::getHeaders() const
{
    return headers;
}

bool ImmutableMessage::isEncrypted() const
{
    return messageDeserializer.isEncrypted();
}

bool ImmutableMessage::isSigned() const
{
    return messageDeserializer.isSigned();
}

smrf::ByteArrayView ImmutableMessage::getUnencryptedBody() const
{
    if (!bodyView) {
        if (!messageDeserializer.isCompressed()) {
            bodyView = messageDeserializer.getBody();
        } else {
            decompressedBody = messageDeserializer.decompressBody();
            bodyView = smrf::ByteArrayView(*decompressedBody);
        }
    }
    return *bodyView;
}

std::string ImmutableMessage::toLogMessage() const
{
    return serializer::serializeToJson(*this);
}

const std::string& ImmutableMessage::getType() const
{
    return type;
}

const std::string& ImmutableMessage::getId() const
{
    return id;
}

boost::optional<std::string> ImmutableMessage::getReplyTo() const
{
    return getOptionalHeaderByKey(Message::HEADER_REPLY_TO());
}

boost::optional<std::string> ImmutableMessage::getEffort() const
{
    return getOptionalHeaderByKey(Message::HEADER_EFFORT());
}

JoynrTimePoint ImmutableMessage::getExpiryDate() const
{
    // for now we only support absolute TTLs
    assert(messageDeserializer.isTtlAbsolute());
    return JoynrTimePoint(std::chrono::milliseconds(messageDeserializer.getTtlMs()));
}

const smrf::ByteVector& ImmutableMessage::getSerializedMessage() const
{
    return serializedMessage;
}

std::size_t ImmutableMessage::getMessageSize() const
{
    return messageDeserializer.getMessageSize();
}

bool ImmutableMessage::isReceivedFromGlobal() const
{
    return receivedFromGlobal;
}

void ImmutableMessage::setReceivedFromGlobal(bool receivedFromGlobal)
{
    this->receivedFromGlobal = receivedFromGlobal;
}

void ImmutableMessage::setCreator(const std::string& creator)
{
    this->creator = creator;
}

void ImmutableMessage::setCreator(std::string&& creator)
{
    this->creator = std::move(creator);
}

const std::string& ImmutableMessage::getCreator() const
{
    return creator;
}

boost::optional<std::string> ImmutableMessage::getOptionalHeaderByKey(const std::string& key) const
{
    boost::optional<std::string> value;
    auto it = headers.find(key);
    if (it != headers.cend()) {
        value = it->second;
    }
    return value;
}

void ImmutableMessage::init()
{
    headers = messageDeserializer.getHeaders();
    boost::optional<std::string> optionalId = getOptionalHeaderByKey(Message::HEADER_ID());
    boost::optional<std::string> optionalType = getOptionalHeaderByKey(Message::HEADER_TYPE());

    JOYNR_LOG_TRACE(logger, "init: {}", toLogMessage());

    // check if necessary headers are set
    if (!optionalId.is_initialized() || !optionalType.is_initialized()) {
        throw std::invalid_argument("missing header");
    } else {
        id = std::move(*optionalId);
        type = std::move(*optionalType);
    }
}

} // namespace joynr
<|endoftext|>