<commit_before>// -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
//
// This code is public domain
// (but note, that the led-matrix library this depends on is GPL v2)

#include "led-matrix.h"
#include "threaded-canvas-manipulator.h"

#include <getopt.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <bass.h>

#include <algorithm>

#define SPECWIDTH 64 // display width (should be multiple of 4)
#define SPECHEIGHT 32  // height (changing requires palette adjustments too)
#define BANDS 64

#define MAX(x,y) ((x > y) ? x : y)

#pragma pack(1)
typedef struct {
  BYTE rgbRed,rgbGreen,rgbBlue;
} RGB;
#pragma pack()

using namespace rgb_matrix;

DWORD chan;

RGB palette[] = {
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {200, 0, 0},
  {200, 0, 0},
  {200, 0, 0},
  {200, 0, 0},
  {200, 0, 0}
};

class VolumeBars : public ThreadedCanvasManipulator {
public:
  VolumeBars(Canvas *m, int delay_ms=50)
    : ThreadedCanvasManipulator(m), delay_ms_(delay_ms),
      numBars_(BANDS), t_(0) {
        printf("I constructed\n");
  }

  void Run() {
    printf("I started\n");
    int numBars_ = BANDS;
    int x,y,y1,y2;
    const int width = canvas()->width();
    height_ = canvas()->height();
    barWidth_ = 2; //width/numBars_;

    // Start the loop
    while (running()) {
      float fft[1024];
      BASS_ChannelGetData(chan,fft,BASS_DATA_FFT2048); // get the FFT data
      for (x=0;x<SPECWIDTH;x++) {
        y=sqrt(fft[x+1])*3*SPECHEIGHT-4; // scale it (sqrt to make low values more visible)
        // printf("x: %d, y: %d, y1: %d, y2: %d\n", x, y, y1, y2);
        if (y>SPECHEIGHT) y=SPECHEIGHT; // cap it
        y2 = SPECHEIGHT + 1;
        while (--y2>MAX(y,y1)) drawBarRow(x, y2, {0,0,0});
        if (x && (y1=(y+y1)/2)) // interpolate from previous to make the display smoother
          while (--y1>=0) drawBarRow(x, y1, palette[y1]);
        y1=y;
        while (--y>=0) drawBarRow(x, y, palette[y]); // draw level
      }
      usleep(delay_ms_ * 1000);
    }
  }

private:
  void drawBarRow(int bar, uint8_t y, RGB color) {
    for (uint8_t x=bar*barWidth_; x<(bar+1)*barWidth_; ++x) {
      canvas()->SetPixel(x, height_-1-y, color.rgbRed, color.rgbGreen, color.rgbBlue);
    }
  }

  int delay_ms_;
  int numBars_;
  int barWidth_;
  int height_;
  int heightGreen_;
  int heightYellow_;
  int heightOrange_;
  int heightRed_;
  int t_;
};

static int usage(const char *progname) {
  fprintf(stderr, "usage: %s <options> -D <demo-nr> [optional parameter]\n",
          progname);
  fprintf(stderr, "Options:\n"
          "\t-r <rows>     : Display rows. 16 for 16x32, 32 for 32x32. "
          "Default: 32\n"
          "\t-c <chained>  : Daisy-chained boards. Default: 1.\n"
          "\t-L            : 'Large' display, composed out of 4 times 32x32\n"
          "\t-p <pwm-bits> : Bits used for PWM. Something between 1..11\n"
          "\t-l            : Don't do luminance correction (CIE1931)\n"
          "\t-D <demo-nr>  : Always needs to be set\n"
          "\t-d            : run as daemon. Use this when starting in\n"
          "\t                /etc/init.d, but also when running without\n"
          "\t                terminal (e.g. cron).\n"
          "\t-t <seconds>  : Run for these number of seconds, then exit.\n"
          "\t       (if neither -d nor -t are supplied, waits for <RETURN>)\n"
          "\t-w <count>    : Wait states (to throttle I/O speed)\n");
  fprintf(stderr, "Example:\n\t%s -t 10 -D 1 runtext.ppm\n"
          "Scrolls the runtext for 10 seconds\n", progname);
  return 1;
}

int main(int argc, char *argv[]) {
  bool as_daemon = false;
  int runtime_seconds = -1;
  int demo = -1;
  int rows = 32;
  int chain = 1;
  int scroll_ms = 30;
  int pwm_bits = -1;
  bool large_display = false;
  bool do_luminance_correct = true;
  uint8_t w = 0; // Use default # of write cycles

  const char *demo_parameter = NULL;

  int opt;
  while ((opt = getopt(argc, argv, "dl:t:r:p:c:m:w:L")) != -1) {
    switch (opt) {
    case 'd':
      as_daemon = true;
      break;

    case 't':
      runtime_seconds = atoi(optarg);
      break;

    case 'r':
      rows = atoi(optarg);
      break;

    case 'c':
      chain = atoi(optarg);
      break;

    case 'm':
      scroll_ms = atoi(optarg);
      break;

    case 'p':
      pwm_bits = atoi(optarg);
      break;

    case 'l':
      do_luminance_correct = !do_luminance_correct;
      break;

    case 'L':
      // The 'large' display assumes a chain of four displays with 32x32
      chain = 4;
      rows = 32;
      large_display = true;
      break;

    case 'w':
      w = atoi(optarg);
      break;

    default: /* '?' */
      return usage(argv[0]);
    }
  }

  if (optind < argc) {
    demo_parameter = argv[optind];
  }

  if (getuid() != 0) {
    fprintf(stderr, "Must run as root to be able to access /dev/mem\n"
            "Prepend 'sudo' to the command:\n\tsudo %s ...\n", argv[0]);
    return 1;
  }

  if (rows != 16 && rows != 32) {
    fprintf(stderr, "Rows can either be 16 or 32\n");
    return 1;
  }

  if (chain < 1) {
    fprintf(stderr, "Chain outside usable range\n");
    return 1;
  }
  if (chain > 8) {
    fprintf(stderr, "That is a long chain. Expect some flicker.\n");
  }

  // Initialize GPIO pins. This might fail when we don't have permissions.
  GPIO io;
  if (!io.Init())
    return 1;
  if(w) io.writeCycles = w;

  // The matrix, our 'frame buffer' and display updater.
  RGBMatrix *matrix = new RGBMatrix(&io, rows, chain);
  matrix->set_luminance_correct(do_luminance_correct);
  if (pwm_bits >= 0 && !matrix->SetPWMBits(pwm_bits)) {
    fprintf(stderr, "Invalid range of pwm-bits\n");
    return 1;
  }

  Canvas *canvas = matrix;

  // The ThreadedCanvasManipulator objects are filling
  // the matrix continuously.
  ThreadedCanvasManipulator *image_gen = image_gen = new VolumeBars(canvas, scroll_ms);

  // initialize BASS
  if (!BASS_Init(-1,44100,0,NULL,NULL)) {
    printf("Can't initialize device\n");
    return 0;
  }

  BASS_SetConfig(BASS_CONFIG_NET_PLAYLIST,1); // enable playlist processing
  BASS_SetConfig(BASS_CONFIG_NET_PREBUF,0); // minimize automatic pre-buffering, so we can do it (and display it) instead

  BASS_PluginLoad("libbass_aac.so",0); // load BASS_AAC (if present) for AAC support

  // Image generating demo is crated. Now start the thread.
  image_gen->Start();

  char url[1000];
  DWORD r;
  while (true)
  {
    fgets(url, sizeof(url), stdin);
    url[strcspn(url, "\n")] = 0;
    BASS_StreamFree(chan); // close old stream
    if (!(chan=BASS_StreamCreateURL(url,0,BASS_STREAM_BLOCK|BASS_STREAM_STATUS|BASS_STREAM_AUTOFREE,NULL,(void*)r))) {
      printf("BASS Error: %d\n", BASS_ErrorGetCode());
      break; //TODO add proper error handling here
    } else {
      BASS_ChannelPlay(chan,FALSE);
    }
  }

  BASS_Free();

  // Stop image generating thread.
  delete image_gen;
  delete canvas;

  return 0;
}
<commit_msg>clean up warnings<commit_after>// -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
//
// This code is public domain
// (but note, that the led-matrix library this depends on is GPL v2)

#include "led-matrix.h"
#include "threaded-canvas-manipulator.h"

#include <getopt.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <bass.h>

#include <algorithm>

#define SPECWIDTH 64 // display width (should be multiple of 4)
#define SPECHEIGHT 32  // height (changing requires palette adjustments too)
#define BANDS 64

#define CHAIN 4
#define ROWS 32
#define REFRESH_RATE 30

#define MAX(x,y) ((x > y) ? x : y)

#pragma pack(1)
typedef struct {
  BYTE rgbRed,rgbGreen,rgbBlue;
} RGB;
#pragma pack()

using namespace rgb_matrix;

DWORD chan;

RGB palette[] = {
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {200, 0, 0},
  {200, 0, 0},
  {200, 0, 0},
  {200, 0, 0},
  {200, 0, 0}
};

class VolumeBars : public ThreadedCanvasManipulator {
public:
  VolumeBars(Canvas *m, int delay_ms=50)
    : ThreadedCanvasManipulator(m), delay_ms_(delay_ms),
      numBars_(BANDS), t_(0) {
  }

  void Run() {
    int x,y,y1,y2;
    y1 = 0;
    height_ = canvas()->height();
    barWidth_ = 2; //width/numBars_;

    // Start the loop
    while (running()) {
      float fft[1024];
      BASS_ChannelGetData(chan,fft,BASS_DATA_FFT2048); // get the FFT data
      for (x=0;x<SPECWIDTH;x++) {
        y=sqrt(fft[x+1])*3*SPECHEIGHT-4; // scale it (sqrt to make low values more visible)
        // printf("x: %d, y: %d, y1: %d, y2: %d\n", x, y, y1, y2);
        if (y>SPECHEIGHT) y=SPECHEIGHT; // cap it
        y2 = SPECHEIGHT + 1;
        while (--y2>MAX(y,y1)) drawBarRow(x, y2, {0,0,0});
        if (x && (y1=(y+y1)/2)) // interpolate from previous to make the display smoother
          while (--y1>=0) drawBarRow(x, y1, palette[y1]);
        y1=y;
        while (--y>=0) drawBarRow(x, y, palette[y]); // draw level
      }
      usleep(delay_ms_ * 1000);
    }
  }

private:
  void drawBarRow(int bar, uint8_t y, RGB color) {
    for (uint8_t x=bar*barWidth_; x<(bar+1)*barWidth_; ++x) {
      canvas()->SetPixel(x, height_-1-y, color.rgbRed, color.rgbGreen, color.rgbBlue);
    }
  }

  int delay_ms_;
  int numBars_;
  int barWidth_;
  int height_;
  int heightGreen_;
  int heightYellow_;
  int heightOrange_;
  int heightRed_;
  int t_;
};

int main(int argc, char *argv[])
{
  if (getuid() != 0) {
    fprintf(stderr, "Must run as root to be able to access /dev/mem\n"
            "Prepend 'sudo' to the command:\n\tsudo %s ...\n", argv[0]);
    return 1;
  }

  // Initialize GPIO pins. This might fail when we don't have permissions.
  GPIO io;
  if (!io.Init())
    return 1;

  // The matrix, our 'frame buffer' and display updater.
  RGBMatrix *matrix = new RGBMatrix(&io, ROWS, CHAIN);

  Canvas *canvas = matrix;

  // The ThreadedCanvasManipulator objects are filling
  // the matrix continuously.
  ThreadedCanvasManipulator *image_gen = image_gen = new VolumeBars(canvas, REFRESH_RATE);

  // initialize BASS
  if (!BASS_Init(-1,44100,0,NULL,NULL)) {
    printf("Can't initialize device\n");
    return 0;
  }

  BASS_SetConfig(BASS_CONFIG_NET_PLAYLIST,1); // enable playlist processing
  BASS_SetConfig(BASS_CONFIG_NET_PREBUF,0); // minimize automatic pre-buffering, so we can do it (and display it) instead

  BASS_PluginLoad("libbass_aac.so",0); // load BASS_AAC (if present) for AAC support

  // Image generating demo is crated. Now start the thread.
  image_gen->Start();

  char url[1000];
  DWORD r;
  while (true)
  {
    fgets(url, sizeof(url), stdin);
    url[strcspn(url, "\n")] = 0;
    BASS_StreamFree(chan); // close old stream
    if (!(chan=BASS_StreamCreateURL(url,0,BASS_STREAM_BLOCK|BASS_STREAM_STATUS|BASS_STREAM_AUTOFREE,NULL,(void*)r))) {
      printf("BASS Error: %d\n", BASS_ErrorGetCode());
      break; //TODO add proper error handling here
    } else {
      BASS_ChannelPlay(chan,FALSE);
    }
  }

  BASS_Free();

  // Stop image generating thread.
  delete image_gen;
  delete canvas;

  return 0;
}
<|endoftext|>


<commit_before>d366d97a-2747-11e6-b11e-e0f84713e7b8<commit_msg>updated some files<commit_after>d38c04ae-2747-11e6-8e83-e0f84713e7b8<|endoftext|>


<commit_before>#include "layouterXHTML.h"
#include "layouterSDL.h"

#define TXT_WIDTH 700
#define WIN_WIDTH 800

int main ()
{
  textStyleSheet_c styleSheet;

  // setze default sprache des textes
  styleSheet.language="en-Engl";

  // alle Fonts, die so genutzt werden: familie heißt sans, und dann der bold Font dazu
  styleSheet.font("sans", "/usr/share/fonts/freefont/FreeSans.ttf");
  styleSheet.font("sans", "/usr/share/fonts/freefont/FreeSansBold.ttf", "normal", "normal", "bold");

  // CSS regeln, immer Selector, attribut, wert
  styleSheet.addRule("body", "color", "#ffffff");
  styleSheet.addRule("body", "font-family", "sans");
  styleSheet.addRule("body", "font-style", "normal");
  styleSheet.addRule("body", "font-size", "30px");
  styleSheet.addRule("body", "font-variant", "normal");
  styleSheet.addRule("body", "font-weight", "normal");
  styleSheet.addRule("body", "text-align", "justify");
  styleSheet.addRule(".BigFont", "font-size", "35px");
  styleSheet.addRule(".BoldFont", "font-weight", "bold");
  styleSheet.addRule("i", "color", "#ff0000");
  styleSheet.addRule("h1", "font-weight", "bold");
  styleSheet.addRule("h1", "font-size", "60px");
  styleSheet.addRule("h1", "text-align", "center");

  // der zu formatierende text
  std::string text = u8""
    "
Überschrift
"
    "
Test Text more and some "
    "
more text so
 that the pa\u00ADra\u00ADgraph is at least "
    "
long
 enough to span some lines on the screen let us "
    "also include sm hebrew נייה, העגורן הוא and back to english
"
    "
2nd Paragraph
 with
a\ndivision
"
    "
.
"
    "
a b c andnowoneverylongwordthatdoesntfitononelineandmight d e f °C
"
    "

First long text in an ul list of html sdfsd fsd fs dfsd f gobble di gock and"
    "even more

Second with just a bit

"
    "
MargaretAreYouGrievingOverGoldengroveUnleavingLeavesLikeTheThingsOfManYouWithYourFreshThoughtsCareForCanYouAhAsTheHeartGrowsOlderItWillComeToSuchSightsColderByAndByNorSpareASighThoughWorldsOfWanwoodLeafmealLieAndYetYouWillWeepAndKnowWhyNowNoMatterChildTheNameSorrowsSpringsAreTheSameNorMouthHadNoNorMindExpressedWhatHeartHeardOfGhostGuessedItIsTheBlightManWasBornForItIsMargaretYouMournFor
"
    "";

  // Vektor mit auszugebenden Text layouts, besteht immer aus einem layoute
  // und dessen Position auf dem Bildschirm
  std::vector<layoutInfo_c> l;

  // grauer Hintergrund, damit ich sehen kann, ob der Text die korrekte Breite hat
  // erzeuge ein künstliches Layout nur mit einem Rechteck drin... so etwas wird später
  // nicht mehr benötigt, ist nur für den Test
  textLayout_c la;
  textLayout_c::commandData c;
  c.command = textLayout_c::commandData::CMD_RECT;
  c.x = c.y = 0;
  c.w = TXT_WIDTH;
  c.h = 600;
  c.r = c.g = c.b = 50;
  la.addCommand(c);
  l.emplace_back(layoutInfo_c(la, (WIN_WIDTH-TXT_WIDTH)/2, 20));

  // das eigentliche Layout
  // layoutXHTML macht die Arbeit, übergeben wird der Text, das Stylesheet und eine Klasse,
  // die die Form des Textes beinhaltet (für nicht rechteckiges Layout
  l.emplace_back(layoutInfo_c(layoutXHTML(text, styleSheet, rectangleShape_c(TXT_WIDTH)),
                              (WIN_WIDTH-TXT_WIDTH)/2, 20));

  // Ausgabe mittels SDL
  showLayoutsSelf(WIN_WIDTH, 600, l);
}
<commit_msg>update the test program<commit_after>#include "layouterXHTML.h"
#include "layouterSDL.h"
#include <boost/concept_check.hpp>

#include <fstream>

#define TXT_WIDTH 700
#define WIN_WIDTH 800

using namespace STLL;

class niftyShape_c : public shape_c
{
public:
  niftyShape_c(void) {}

  virtual int32_t getLeft(int32_t top, int32_t /*bottom*/) const { return top/4; }
  virtual int32_t getRight(int32_t top, int32_t /*bottom*/) const { return TXT_WIDTH-top/8; }
};

std::pair<std::shared_ptr<uint8_t>, size_t> loadFile(const std::string & fn)
{
  std::ifstream f(fn.c_str());

  f.seekg(0, std::ios_base::end);

  auto size = f.tellg();

  uint8_t * dat = new uint8_t[size];

  f.seekg(0, std::ios_base::beg);

  f.read((char*)dat, size);

  return std::make_pair(std::shared_ptr<uint8_t>(dat, std::default_delete<uint8_t[]>()), size);
}

void showLayoutsSelf(int w, int h, const std::vector<layoutInfo_c> & data)
{
  /* Initialize our SDL window */
  if(SDL_Init(SDL_INIT_VIDEO) < 0)   {
    fprintf(stderr, "Failed to initialize SDL");
    return;
  }

  SDL_Surface *screen;
  screen = SDL_SetVideoMode(w, h, 32, SDL_SWSURFACE | SDL_DOUBLEBUF);

  /* Enable key repeat, just makes it so we don't have to worry about fancy
   * scanboard keyboard input and such */
  SDL_EnableKeyRepeat(300, 130);
  SDL_EnableUNICODE(1);

  /* Clear our surface */
  SDL_FillRect(screen, NULL, 0 );

  for (auto & a : data)
    showLayoutSDL(a.layout, a.sx, a.sy, screen);

  SDL_Flip(screen);

  /* Our main event/draw loop */
  int done = 0;

  while (!done)
  {

    /* Handle SDL events */
    SDL_Event event;
    while(SDL_PollEvent(&event))
    {
      switch (event.type)
      {
        case SDL_KEYDOWN:
        case SDL_QUIT:
          done = 1;
          break;
      }
    }

    SDL_Delay(150);
  }

  SDL_Quit();
}

int main ()
{
  textStyleSheet_c styleSheet;

  // alle Fonts, die so genutzt werden: familie heißt sans, und dann der bold Font dazu
  styleSheet.font("sans", fontResource_c("/usr/share/fonts/freefont/FreeSans.ttf"));
  styleSheet.font("sans", fontResource_c("/usr/share/fonts/freefont/FreeSansBold.ttf"), "normal", "normal", "bold");
  styleSheet.font("sans-ar", fontResource_c(loadFile("fonts/amiri-0.104/amiri-regular.ttf"), "arabic"));

  // CSS regeln, immer Selector, attribut, wert
  styleSheet.addRule("body", "color", "#ffffff");
  styleSheet.addRule("body", "font-size", "18px");
  styleSheet.addRule("body", "text-align", "justify");
  styleSheet.addRule("p", "text-indent", "10px");
  styleSheet.addRule("body", "padding", "10px");
  styleSheet.addRule("body", "background-color", "#303030");
//  styleSheet.addRule("p", "padding", "10px");
//  styleSheet.addRule("ul", "padding", "10px");
//  styleSheet.addRule("li", "padding", "10px");
  styleSheet.addRule(".BigFont", "font-size", "25px");
  styleSheet.addRule(".BoldFont", "font-weight", "bold");
  styleSheet.addRule(".RTL", "text-align-last", "right");
  styleSheet.addRule("i", "color", "#ff0000");
  styleSheet.addRule("h1", "font-weight", "bold");
  styleSheet.addRule("h1", "font-size", "60px");
  styleSheet.addRule("h1", "text-align", "center");
  styleSheet.addRule("h1", "text-decoration", "underline");
  styleSheet.addRule(".und", "text-decoration", "underline");
  styleSheet.addRule("p[lang|=he]", "direction", "rtl");
  styleSheet.addRule("ul[lang|=he]", "direction", "rtl");
  styleSheet.addRule("p[lang|=ar]", "direction", "rtl");
  styleSheet.addRule("p[lang|=ar]", "font-family", "sans-ar");
  styleSheet.addRule(".framed", "border-width", "3px");
  styleSheet.addRule(".framed", "padding", "10px");
  styleSheet.addRule(".framed", "border-color", "#ff0000");
  styleSheet.addRule(".framed", "background-color", "#ff8080");
  styleSheet.addRule(".framed", "margin", "10px");

  // der zu formatierende text
  std::string text = u8""
    "
Überschrift mit
"
    "
Test Text more and some "
    "
more text so
 that the pa\u00ADra\u00ADgraph is at least "
    "
long
 enough to span some lines on the screen let us "
    "also include some more hebrew נייה, העגורן הוא and back to english
"
    "
אברהם בן שמואל אבולעפיה (1240 - 1291 בערך), רב ומקובל שראה עצמו כנביא וכמשיח, "
    "נחשב לרוב כנציג הבולט של זרם הקבלה האקסטטית. היה בין הראשונים שהחלו במסע לגילוי עשרת "
    "השבטים האבודים. עקב חרם שהוטל עליו על ידי הרשבא בעקבות הכרזתו על עצמו כמשיח, נשתכח אבולעפיה "
    " מלב, עד השינוי שהחל במאה השש-עשרה בו החלו הרמק ורבי חיים ויטאל להתייחס לכתביו. להכרה מלאה "
    "זכה, במאה השמונה-עשרה, עם התייחסותו החיובית של החידא לספרו הקבלי של אבולעפיה, חיי העולם הבא. "
    "אבולעפיה חיבר עשרות ספרי קבלה, שזכו להתייחסות נרחבת גם בקרב קהיליית החוקרים המדעית. חלקם יצאו "
    "לאור לאחרונה במהדורות מחודשות.
"
    "
كأس الأمم الأفريقية لكرة القدم 2008، ,عرفت أيضاً باسم إم.تي.إن كأس الأمم الأفريقية "
    "لكرة
القدم بسبب الشركة
 القدم بسبب الشركة الراعية للبطولة إم.تي.إن، كانت النسخة السادسة والعشرون من كأس الأمم الأفريقية، "
    "وهي البطولة الرئيسية لمنتخبات الاتحاد الأفريقي لكرة القدم (كاف) والتي تقام كل سنتين منذ سنة "
    "1957. نظمت المسابقة في أربعة مدن في جميع أنحاء غانا بين 20 يناير و 10 فبراير 2008. وبحضور 16 منتخبا "
    "أفريقيا مقسمين على 4 مجموعات ويتأهل أول فريقين لكل مجموعة إلى دور الثمانية حيث الأدوار الإقصائية، "
    "وكانت مباراة الأفتتاح بين غانا وغينيا والتي انتهت بفوز غانا 2-1، وانتهت البطولة بفوز مصر بالبطولة "
    "القارية، بعد أن هزمت الكاميرون 1–0 في النهائي الذي أقيم علي ملعب أوهين دجان بمدينة أكرا، بينما فاز "
    "منخب غانا بالمركز الثالث عقب تغلبه على فريق ساحل العاج بأربعة أهداف مقابل هدفين. (تابع القراءة)
"
    "
2nd Paragraph
 with
a\ndivision
"
    "
.
"
    "
a b c andnowoneverylongwordthatdoesntfitononelineandmight d e f °C
"
    "

First
long
 text in an ul list of html sdfsd fsd fs dfsd f gobble di gock and "
    "even more

Second with just a bit

"
    "

First long text in an ul list of html sdfsd fsd fs dfsd f gobble di gock and "
    "even more

Second with just a bit

"
    "
MargaretAreYouGrievingOverGoldengroveUnleavingLeavesLikeTheThingsOfManYouWithYourF"
    "reshThoughtsCareForCanYouAhAsTheHeartGrowsOlderItWillComeToSuchSightsColderByAndByNor"
    "SpareASighThoughWorldsOfWanwoodLeafmealLieAndYetYouWillWeepAndKnowWhyNowNoMatterChild"
    "TheNameSorrowsSpringsAreTheSameNorMouthHadNoNorMindExpressedWhatHeartHeardOfGhostGues"
    "sedItIsTheBlightManWasBornForItIsMargaretYouMournFor
"
    "";

  // Vektor mit auszugebenden Text layouts, besteht immer aus einem layoute
  // und dessen Position auf dem Bildschirm
  std::vector<layoutInfo_c> l;

  // grauer Hintergrund, damit ich sehen kann, ob der Text die korrekte Breite hat
  // erzeuge ein künstliches Layout nur mit einem Rechteck drin... so etwas wird später
  // nicht mehr benötigt, ist nur für den Test
  textLayout_c la;
  textLayout_c::commandData c;
  c.command = textLayout_c::commandData::CMD_RECT;
  c.x = c.y = 0;
  c.w = TXT_WIDTH;
  c.h = 600;
  c.r = c.g = c.b = 50;
  la.addCommand(c);
  l.emplace_back(layoutInfo_c(la, (WIN_WIDTH-TXT_WIDTH)/2, 10));

  try {
    // das eigentliche Layout
    // layoutXHTML macht die Arbeit, übergeben wird der Text, das Stylesheet und eine Klasse,
    // die die Form des Textes beinhaltet (für nicht rechteckiges Layout
    l.emplace_back(layoutInfo_c(layoutXHTML(text, styleSheet, rectangleShape_c(TXT_WIDTH)),
                                (WIN_WIDTH-TXT_WIDTH)/2, 10));

    l[0].layout.data[0].h = l[1].layout.getHeight();

    // Ausgabe mittels SDL
    showLayoutsSelf(WIN_WIDTH, 1000, l);
  }
  catch (XhtmlException_c & e)
  {
    printf("Xhtml Exception: %s\n", e.what());
  }
}
<|endoftext|>


<commit_before>55ca5af8-2748-11e6-90da-e0f84713e7b8<commit_msg>My Life for Auir<commit_after>55d75a59-2748-11e6-9c64-e0f84713e7b8<|endoftext|>


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

#include "framepacker.hpp"
#include <list>
#include <string>
#include <Windows.h>
#include "freeimage.h"

using namespace framepacker;

namespace framepacker {

struct color {
	color() : r(0), g(0), b(0), a(0) {
	}
	color(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a) : r(_r), g(_g), b(_b), a(_a) {
	}

	bool is_transparent(void) const {
		return a == 0;
	}

	unsigned char r;
	unsigned char g;
	unsigned char b;
	unsigned char a;
};

class freeimage {

public:
	freeimage() : handle(NULL), w(0), h(0) {
	}
	freeimage(const char* p) {
		load_file(p);
	}
	~freeimage() {
		unload();
	}

	const char* get_path(void) const { return path.c_str(); }

	int width(void) const { return w; }
	int height(void) const { return h; }

	BYTE* bytes(void) const { return FreeImage_GetBits(handle); }

	color pixel(unsigned x, unsigned y) const {
		RGBQUAD col;
		FreeImage_GetPixelColor(handle, x, y, &col);
		color ret;
		ret.r = col.rgbRed;
		ret.g = col.rgbGreen;
		ret.b = col.rgbBlue;
		ret.a = col.rgbReserved;

		return ret;
	}
	void pixel(unsigned x, unsigned y, color &c) {
		RGBQUAD col;
		col.rgbRed = c.r;
		col.rgbGreen = c.g;
		col.rgbBlue = c.b;
		col.rgbReserved = c.a;
		FreeImage_SetPixelColor(handle, x, y, &col);
	}

	void copy_from(freeimage &src, unsigned left, unsigned top, unsigned width, unsigned height, unsigned x, unsigned y) {
		FIBITMAP* fib = FreeImage_Copy(src.handle, left, top, left + width, top + height);
		FreeImage_Paste(handle, fib, x, y, 255);
		FreeImage_Unload(fib);
	}

	bool is_transparent(unsigned x, unsigned y) const {
		color c = pixel(x, y);

		return c.is_transparent();
	}

	bool resize(int _w, int _h) {
		unload();
		handle = FreeImage_Allocate(_w, _h, 32);
		w = _w;
		h = _h;

		return true;
	}

	bool load_file(const char* p) {
		path = p;

		handle = NULL;
		w = 0;
		h = 0;

		FREE_IMAGE_FORMAT fif = FreeImage_GetFIFFromFilename(path.c_str());
		if(fif != FIF_UNKNOWN) {
			handle = FreeImage_Load(fif, path.c_str());
			if (FreeImage_GetBPP(handle) != 32)  {
				FIBITMAP* tmp = handle;
				handle = FreeImage_ConvertTo32Bits(tmp);
			}

			w = FreeImage_GetWidth(handle);
			h = FreeImage_GetHeight(handle);

			return true;
		}

		return false;
	}

	void unload(void) {
		if(!handle)
			return;

		FreeImage_Unload(handle);
		handle = NULL;
	}

	void save(const char* p) {
		FreeImage_Save(FIF_PNG, handle, p);
	}

private:
	std::string path;
	FIBITMAP* handle;
	unsigned w;
	unsigned h;

};

}

typedef packer<freeimage> packer_type;

#define _BIN_FILE_NAME "framepacker"

#define _CHECK_ARG(__c, __i, __e) \
	do { \
		if(__c <= __i + 1) { \
			printf(__e); \
			return; \
		} \
	} while(0)

static unsigned short _set_console_color(unsigned short col) {
	CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
	if(!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbiInfo)) {
		printf("GetConsoleScreenBufferInfo error!\n");

		return 0;
	}
	if(!SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), col)) {
		printf("SetConsoleTextAttribute error!\n");

		return 0;
	}

	return csbiInfo.wAttributes;
}

struct ConsoleColor {
	ConsoleColor(unsigned short col) {
		old = _set_console_color(col);
	}
	~ConsoleColor() {
		_set_console_color(old);
	}

	unsigned short old;
};

#define CONSOLE_COLOR(C) ConsoleColor __##__FUNCTION__##__LINE__(C);

static void _show_tip(void) {
	printf("[Usage]\n");
	printf("  %s FILE_LIST [-o output_file] [OPTIONS] - Packs some images\n", _BIN_FILE_NAME);
	printf("\n");
	printf("  FILE_LIST := file*\n");
	printf("  OPTIONS   := -p n    : Padding, 1 as default\n");
	printf("            := -s mxn  : Expected texture size, eg. 256x512, may enlarge result\n");
	printf("            := -t      : Disable rotation\n");
	printf("            := -w      : Disable forcing texture to POT (Power of 2)\n");
	printf("            := -m      : Disable alpha trim\n");
}

static void _process_parameters(int argc, char* argv[]) {
	int i = 1;
	std::string m = "\0";
	int padding = 1;
	int w = 0, h = 0;
	bool allow_rotate = true;
	bool power_of_2 = true;
	bool alpha_trim = true;

	std::list<std::string> inputs;
	std::list<std::pair<std::string, std::string> > options;

	// Parses arguments.
	while(i < argc) {
		if(!memcmp(argv[i], "-", 1)) {
			if(!memcmp(argv[i] + 1, "o", 1)) {
				m = 'o';
				_CHECK_ARG(argc, i, "-o: File name expected.\n");
				options.push_back(std::make_pair(m, argv[++i]));
				++i;
			} else if(!memcmp(argv[i] + 1, "p", 1)) {
				_CHECK_ARG(argc, i, "-p: Padding size expected.\n");
				padding = max(std::atoi(argv[++i]), 0);
			} else if(!memcmp(argv[i] + 1, "s", 1)) {
				_CHECK_ARG(argc, i, "-s: Size expected.\n");
				char buf[256];
				_snprintf_s(buf, sizeof(buf), argv[++i]);
				char* ctx = NULL;
				char* tmp = strtok_s(buf, "x", &ctx);
				w = std::atoi(tmp);
				h = std::atoi(ctx);
				++i;
			} else if(!memcmp(argv[i] + 1, "t", 1)) {
				allow_rotate = false;
				++i;
			} else if(!memcmp(argv[i] + 1, "w", 1)) {
				power_of_2 = false;
				++i;
			} else if(!memcmp(argv[i] + 1, "m", 1)) {
				alpha_trim = false;
				++i;
			} else {
				printf("Unknown argument: %s.\n", argv[i++]);
			}
		} else {
			inputs.push_back(argv[i++]);
		}
	}

	// Tells output path.
	std::string outpath = "output.png";
	for(auto it = options.begin(); it != options.end(); ++it) {
		if(it->first == "o")
			outpath = it->second;
	}

	// Prepares packing.
	DWORD time = GetTickCount();

	packer_type packer;
	packer.padding = padding;
	packer.output_texture_size = vec2(w, h);
	packer.allow_rotate = allow_rotate;
	packer.power_of_2 = power_of_2;
	packer.alpha_trim = alpha_trim;
	packer.comparer = packer_type::compare_area;

	for(auto it = inputs.begin(); it != inputs.end(); ++it) {
		packer_type::texture_type img(new freeimage(it->c_str()));

		packer.add(it->c_str(), img);
	}

	DWORD load_time = GetTickCount() - time;
	time = GetTickCount();

	// Packs it.
	packer_type::texture_type result(new freeimage);
	packer_type::texture_coll_type packed;
	packer_type::texture_coll_type failed;
	packer.pack(result, packed, failed);

	DWORD pack_time = GetTickCount() - time;

	// Prompts.
	{
		CONSOLE_COLOR(FOREGROUND_INTENSITY);
		printf("Packed %d:\n", packed.size());
		for(auto it = packed.begin(); it != packed.end(); ++it) {
			packer_type::block_type &blk = it->second;
			printf("  %s [%d, %d] - [%d, %d]\n", it->first.c_str(), blk.fit->min_x(), blk.fit->min_y(), blk.fit->min_x() + blk.fit->width(), blk.fit->min_y() + blk.fit->height());
		}
	}
	if(failed.size()) {
		CONSOLE_COLOR(FOREGROUND_RED | FOREGROUND_GREEN);
		printf("Failed %d:\n", failed.size());
		for(auto it = failed.begin(); it != failed.end(); ++it) {
			packer_type::block_type &blk = it->second;
			printf("  %s\n", it->first.c_str());
		}
	}
	{
		CONSOLE_COLOR(FOREGROUND_INTENSITY);
		printf("Cost time: %gs loading; %gs packing.\n", (float)load_time / 1000.0f, (float)pack_time / 1000.0f);
	}

	// Serializes.
	{
		CONSOLE_COLOR(FOREGROUND_INTENSITY);
		std::string out_tex = outpath + ".png";
		result->save(out_tex.c_str());
		printf("Texture written: %s.\n", out_tex.c_str());
	}
	{
		CONSOLE_COLOR(FOREGROUND_INTENSITY);
		std::string out_meta = outpath + ".json";
		std::ofstream fs(out_meta);
		packer.write_meta(fs, packed, result, outpath.c_str());
		fs.close();
		printf("Meta data written: %s.\n", out_meta.c_str());
	}
}

static void _on_startup(void) {
	FreeImage_Initialise();
}

static void _on_exit(void) {
	FreeImage_DeInitialise();
}

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

	_on_startup();

	if(argc == 1)
		_show_tip();
	else if(argc >= 2)
		_process_parameters(argc, argv);

	return 0;
}
<commit_msg>-removed main.cpp, not all builds share the only framepacker.cpp unit.<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

#define ELEMENTS_PER_BUY_OPTION 2
#define STORE_ID_OFFSET 0
#define PRICE_OFFSET 1

#define NUM_PRODUCTS 2
#define NUM_BUY_OPTIONS 2

#define NUM_THREADS 512 // El número mínimo de threads es 32 (por el tamaño de warp) y el maximo 1024

void initAllProductsBuyOptions(int *all_products_buy_options);

void printAllProductsAllBuyOptions(int *all_products_buy_options);
void getBestBuyOptions(int *all_products_buy_options, int *best_buy_options);
void printBestBuyOptions(int *best_buy_options);

int main(int argc, char** argv)
{
    // Buy options in host and device
    int *host_all_products_buy_options = (int *) malloc( NUM_PRODUCTS * NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION * sizeof(int) );
    int *best_buy_options = (int *) malloc( NUM_PRODUCTS * ELEMENTS_PER_BUY_OPTION * sizeof(int) );

    initAllProductsBuyOptions(host_all_products_buy_options);

    // DEBUG
    printAllProductsAllBuyOptions(host_all_products_buy_options);
    getBestBuyOptions(host_all_products_buy_options, best_buy_options);
    printBestBuyOptions(best_buy_options);
    // END DEBUG
}

void initAllProductsBuyOptions(int *all_products_buy_options)
{
    // START Vector all the buy options for the product 1

    // product_1_store_1_buy_option;
    all_products_buy_options[0] = 11; // store_id
    all_products_buy_options[1] = 11;  // price

    // product_1_store_2_buy_option;
    all_products_buy_options[2] = 12; // store_id
    all_products_buy_options[3] = 12;  // price

    // END Vector all the buy options for the product 1

    // START Vector all the buy options for the product 2

    // product_1_store_1_buy_option;
    all_products_buy_options[4] = 21; // store_id
    all_products_buy_options[5] = 21;  // price

    // product_1_store_2_buy_option;
    all_products_buy_options[6] = 22; // store_id
    all_products_buy_options[7] = 2;  // price

    // END Vector all the buy options for the product 2
}

void printAllProductsAllBuyOptions(int *all_products_buy_options)
{
    cout << "All products buy options:" << endl;
    for (int i = 0; i < NUM_PRODUCTS; ++i){
        cout << endl << "\tproduct_id: " << i << endl;
        for (int j = 0; j < NUM_BUY_OPTIONS*2; j += 2){
            cout << "Buy option:" << endl;
            cout << "\tstore_id: " << all_products_buy_options[i*NUM_BUY_OPTIONS*2+j] << endl;
            cout << "\tprice: " << all_products_buy_options[i*NUM_BUY_OPTIONS*2+j+1] << endl;
        }
    }
}

void getBestBuyOptions(int *all_products_buy_options, int *best_buy_options)
{
    for(int product_iteration = 0; product_iteration < NUM_PRODUCTS; ++product_iteration)
    {
        int current_product_position = product_iteration * NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION;
        int current_product_store_position = current_product_position + STORE_ID_OFFSET;
        int current_product_price_position = current_product_position + PRICE_OFFSET;

        int best_store = all_products_buy_options[current_product_store_position];
        int best_price = all_products_buy_options[current_product_price_position];

        for(int product_to_compare = ELEMENTS_PER_BUY_OPTION; product_to_compare < NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION; product_to_compare += ELEMENTS_PER_BUY_OPTION)
        {
            if (all_products_buy_options[current_product_position + product_to_compare + PRICE_OFFSET] < best_price)
            {
               best_store = all_products_buy_options[product_iteration * NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION + product_to_compare + STORE_ID_OFFSET];
               best_price = all_products_buy_options[product_iteration * NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION + product_to_compare + PRICE_OFFSET];
            }
        }
        best_buy_options[product_iteration * ELEMENTS_PER_BUY_OPTION + STORE_ID_OFFSET] = best_store;
        best_buy_options[product_iteration * ELEMENTS_PER_BUY_OPTION + PRICE_OFFSET] = best_price;
    }
}

void printBestBuyOptions(int *best_buy_options)
{
    cout << endl <<"Best products buy options:" << endl;
    for (int i = 0; i < NUM_PRODUCTS * ELEMENTS_PER_BUY_OPTION; i += ELEMENTS_PER_BUY_OPTION)
    {
        cout << "Best buy option for product_id: " << i / ELEMENTS_PER_BUY_OPTION << endl;
        cout << "\tstore_id: " << best_buy_options[i + STORE_ID_OFFSET] << endl;
        cout << "\tprice: " << best_buy_options[i + PRICE_OFFSET] << endl;
    }
}
<commit_msg>[WIP] Implement initAllProductsBuyOptions() with random values. Bug inside.<commit_after>#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

#define ELEMENTS_PER_BUY_OPTION 2
#define STORE_ID_OFFSET 0
#define PRICE_OFFSET 1

#define NUM_PRODUCTS 2
#define NUM_BUY_OPTIONS 2

#define NUM_THREADS 512 // El número mínimo de threads es 32 (por el tamaño de warp) y el maximo 1024

void initAllProductsBuyOptions(int *all_products_buy_options);

void printAllProductsAllBuyOptions(int *all_products_buy_options);
void getBestBuyOptions(int *all_products_buy_options, int *best_buy_options);
void printBestBuyOptions(int *best_buy_options);

int main(int argc, char** argv)
{
    // Buy options in host and device
    int *host_all_products_buy_options = (int *) malloc( NUM_PRODUCTS * NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION * sizeof(int) );
    int *best_buy_options = (int *) malloc( NUM_PRODUCTS * ELEMENTS_PER_BUY_OPTION * sizeof(int) );

    initAllProductsBuyOptions(host_all_products_buy_options);

    // DEBUG
    printAllProductsAllBuyOptions(host_all_products_buy_options);
    getBestBuyOptions(host_all_products_buy_options, best_buy_options);
    printBestBuyOptions(best_buy_options);
    // END DEBUG
}

void initAllProductsBuyOptions(int *all_products_buy_options)
{
    for(int product_iteration = 0; product_iteration < NUM_PRODUCTS; ++product_iteration)
    {
        int current_product_position = product_iteration * NUM_BUY_OPTIONS;

        for(int buy_option_iteration = 0; buy_option_iteration < NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION; buy_option_iteration += ELEMENTS_PER_BUY_OPTION)
        {
            int current_product_store_position = current_product_position + buy_option_iteration * ELEMENTS_PER_BUY_OPTION + STORE_ID_OFFSET;
            int current_product_price_position = current_product_position + buy_option_iteration * ELEMENTS_PER_BUY_OPTION + PRICE_OFFSET;

            cout << "product_iteration: " << product_iteration << endl;
            cout << "buy_option_iteration: " << buy_option_iteration << endl;
            cout << "current_product_position: " << current_product_position << endl;
            cout << "current_product_store_position: " << current_product_store_position << endl;
            cout << "current_product_price_position: " << current_product_price_position << endl;
            cout << "NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION: " << NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION << endl << endl;

            // Set the current product buy option to the store with the same id as the current iteration in order to do not duplicate buy options.
            all_products_buy_options[current_product_store_position] = buy_option_iteration;

            // Set the price with a random value between 0 and 100.
            all_products_buy_options[current_product_price_position] = rand() % 100;
        }
    }
}

void printAllProductsAllBuyOptions(int *all_products_buy_options)
{
    cout << "*** All products buy options ***" << endl;
    for (int i = 0; i < NUM_PRODUCTS; ++i){
        cout << endl << "Buy options for product_id: " << i << endl;
        for (int j = 0; j < NUM_BUY_OPTIONS*2; j += 2){
            cout << "\tstore_id: " << all_products_buy_options[i*NUM_BUY_OPTIONS*2+j] << endl;
            cout << "\tprice: " << all_products_buy_options[i*NUM_BUY_OPTIONS*2+j+1] << endl << endl;
        }
    }
}

void getBestBuyOptions(int *all_products_buy_options, int *best_buy_options)
{
    for(int product_iteration = 0; product_iteration < NUM_PRODUCTS; ++product_iteration)
    {
        int current_product_position = product_iteration * NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION;
        int current_product_store_position = current_product_position + STORE_ID_OFFSET;
        int current_product_price_position = current_product_position + PRICE_OFFSET;

        int best_store = all_products_buy_options[current_product_store_position];
        int best_price = all_products_buy_options[current_product_price_position];

        for(int product_to_compare = ELEMENTS_PER_BUY_OPTION; product_to_compare < NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION; product_to_compare += ELEMENTS_PER_BUY_OPTION)
        {
            if (all_products_buy_options[current_product_position + product_to_compare + PRICE_OFFSET] < best_price)
            {
               best_store = all_products_buy_options[product_iteration * NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION + product_to_compare + STORE_ID_OFFSET];
               best_price = all_products_buy_options[product_iteration * NUM_BUY_OPTIONS * ELEMENTS_PER_BUY_OPTION + product_to_compare + PRICE_OFFSET];
            }
        }
        best_buy_options[product_iteration * ELEMENTS_PER_BUY_OPTION + STORE_ID_OFFSET] = best_store;
        best_buy_options[product_iteration * ELEMENTS_PER_BUY_OPTION + PRICE_OFFSET] = best_price;
    }
}

void printBestBuyOptions(int *best_buy_options)
{
    cout << endl <<"*** Best products buy options ***" << endl << endl;
    for (int i = 0; i < NUM_PRODUCTS * ELEMENTS_PER_BUY_OPTION; i += ELEMENTS_PER_BUY_OPTION)
    {
        cout << "Best buy option for product_id: " << i / ELEMENTS_PER_BUY_OPTION << endl;
        cout << "\tstore_id: " << best_buy_options[i + STORE_ID_OFFSET] << endl;
        cout << "\tprice: " << best_buy_options[i + PRICE_OFFSET] << endl << endl;
    }
}
<|endoftext|>


<commit_before>#include <glib.h>
#include<libnotify/notify.h>
#include <gtk/gtk.h>
#include "logging.h"
#include "totimer.h"

int main(int argc, char** argv)
{
    if (argc<2)
        return 0;
    gtk_init(&argc, &argv);
    notify_init("pomodori");
    tres lastres;
    lastres.time=0;
    lastres.reason=argv[1];
    settimer(&lastres,1);
    gtk_main();
    return 0;
}<commit_msg>revert to original time<commit_after>#include <glib.h>
#include<libnotify/notify.h>
#include <gtk/gtk.h>
#include "logging.h"
#include "totimer.h"

int main(int argc, char** argv)
{
    if (argc<2)
        return 0;
    gtk_init(&argc, &argv);
    notify_init("pomodori");
    tres lastres;
    lastres.time=0;
    lastres.reason=argv[1];
    settimer(&lastres,POTIME);
    gtk_main();
    return 0;
}<|endoftext|>


<commit_before>74f33c80-2749-11e6-9d29-e0f84713e7b8<commit_msg>Bug fixes and performance improvements<commit_after>7501904f-2749-11e6-bc2c-e0f84713e7b8<|endoftext|>


<commit_before>cb039dd1-4b02-11e5-aa3c-28cfe9171a43<commit_msg>#BUG723 uncommitted code found on my computer Monday morning<commit_after>cb0d688a-4b02-11e5-83b9-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int main() {

  return 0
}
<commit_msg>Added testing comment<commit_after>#include <iostream>

using namespace std;

int main() {

    // test
    // still testing
  return 0
}
<|endoftext|>


<commit_before>
#include "cppEvolve/cppEvolve.hpp"
#include "cppEvolve/Genome/List1D/List1D.hpp"
#include "cppEvolve/Genome/Tree/Tree.hpp"
#include "cppEvolve/Genome/Tree/Mutator.hpp"
#include "cppEvolve/Genome/Tree/Crossover.hpp"
#include <ctime>
#include <cstdlib>
#include <deque>
#include <array>
#include <map>
#include <set>
#include <list>

using namespace evolve;

namespace functions
{
    int x =100;

    int sum(int x, int y)
    {
        return x + y;
    }

    int get5()
    {
        return 5;
    };

    int getX()
    {
        return functions::x;
    }
}

using namespace functions;
int main()
{

    srand(time(NULL));
    /*
    typedef std::vector<int> genome;

    Generator<genome> generator(foo, 5);

    SimpleGA<genome, 400> ga(generator,
                             List1DGenome::Evaluator::sum<genome>,
                             List1DGenome::Crossover::singlePoint<genome>,
                             List1DGenome::Mutator::swap<genome>,
                             Selector::top<genome, 30>,
                             10);

    ga.run();
    */
    Tree::TreeFactory<int> factory;
    factory.addNode(sum, "sum");
    factory.addTerminator(get5, "5");
    factory.addTerminator(getX, "X");

    auto tree = factory.make();
    auto tree2 = factory.make();

    std::cout << *tree << std::endl;

    std::cout << "Eval: " << tree->eval() << std::endl;

    auto result = Tree::Crossover::singlePointCrossover(tree, tree2, factory);

    std::cout << *result << std::endl;

    std::cout << "Eval: " << result->eval() << std::endl;
    std::cout << result->getDepth();

    return 0;
}
<commit_msg>Added additional demonstrations to main<commit_after>
#include "cppEvolve/cppEvolve.hpp"
#include "cppEvolve/TreeGA.hpp"
#include "cppEvolve/Genome/List1D/List1D.hpp"
#include "cppEvolve/Genome/Tree/Tree.hpp"
#include "cppEvolve/Genome/Tree/Mutator.hpp"
#include "cppEvolve/Genome/Tree/Crossover.hpp"
#include <ctime>
#include <cstdlib>
#include <deque>
#include <array>
#include <map>
#include <set>
#include <list>

using namespace evolve;

namespace functions
{
    int x =100;

    int sum(int x, int y)
    {
        return x + y;
    }

    int average(int x, int y)
    {
        return (x+y)/2;
    }

    int get5()
    {
        return 5;
    };

    int getX()
    {
        return functions::x;
    }

    template<typename T>
    float fitness(const Tree::Tree<T>* tree)
    {
        x=2;
        return tree->eval();
    }

}

using namespace functions;

int main()
{

    srand(time(NULL));
/*
    typedef std::vector<int> genome;

    Generator<genome> generator(get5, 5);

    SimpleGA<genome, 400> ga(generator,
                             List1DGenome::Evaluator::sum<genome>,
                             List1DGenome::Crossover::singlePoint<genome>,
                             List1DGenome::Mutator::swap<genome>,
                             Selector::top<genome, 30>,
                             10);

    ga.run();

*/
    Tree::TreeFactory<int> factory(6);
    factory.addNode(sum, "sum");
    factory.addNode(average, "average");
    factory.addTerminator(get5, "5");
    factory.addTerminator(getX, "X");

    TreeGA<int> ga(factory,
                 fitness<int>,
                 Tree::Crossover::singlePointCrossover<int>,
                 Tree::Mutator::randomNode<int>,
                 Selector::top<Tree::Tree<int>*, 30>,
                 1000);

    ga.run();

/*
    Tree::TreeFactory<int> factory(6);
    factory.addNode(sum, "sum");
    factory.addNode(average, "average");
    factory.addTerminator(get5, "5");
    factory.addTerminator(getX, "X");
    auto tree = factory.make();
    auto tree2 = factory.make();

    std::cout << *tree << std::endl;

    std::cout << "Eval: " << tree->eval() << std::endl;

    auto result = Tree::Crossover::singlePointCrossover(tree, tree2, factory);
    Tree::Mutator::randomNode(result, factory);

    std::cout << *result << std::endl;

    std::cout << "Eval: " << result->eval() << std::endl;
    std::cout << result->getDepth();
    */
    return 0;
}
<|endoftext|>


<commit_before>#include "main.h"
#include <iostream>

/**

*/
MainWindow::MainWindow()
{
  //set variables
	started = false;
	finished = true;
	score_ = 0;
	lives_ = 0;
	executions = 0;
	speed = 15;
	canLose = true;
	len = 3500;

  //create Pixmap images
  	as1 = new QPixmap("images/airsoldier1.png","png");
  	as2 = new QPixmap("images/airsoldier2.png","png");
  	at = new QPixmap("images/aquatank.png","png");
  	g1 = new QPixmap("images/gargoyle1.png","png");
  	g2 = new QPixmap("images/gargoyle2.png","png");
  	rn1 = new QPixmap("images/rednocturne1.png","png");
  	rn2 = new QPixmap("images/rednocturne2.png","png");
  	ts1 = new QPixmap("images/tornadostep1.png","png");
  	ts2 = new QPixmap("images/tornadostep2.png","png");
  	wm1 = new QPixmap("images/whitemushroom1.png","png");
  	wm2 = new QPixmap("images/whitemushroom2.png","png");
  	l = new QPixmap("images/life.png","png");
  	bg = new QPixmap("images/background.png","png");
  	bgs = new QPixmap("images/startbackground.png","png");
  //create overall layout
	this->setGeometry(1,0,20,20);

	window = new QWidget;
	setCentralWidget(window);
	layout = new QVBoxLayout(window);
	window->setLayout(layout);

  //create options sidebar
	options = new QHBoxLayout();
	layout->addLayout(options);
  //create gamespace
	scene = new QGraphicsScene();
	scene->setSceneRect(0,0,650,350);
	view = new QGraphicsView(scene);
	view->setFixedSize(675,375);
	QRect r(0,0,675,375);
	QColor c(Qt::black);
	QBrush b(c,*bgs);
	view->setBackgroundBrush(b);
 	layout->addWidget(view);

  //create start button
  	start = new QPushButton("Start Game");
	options->addWidget(start);
	QObject::connect(start,SIGNAL(clicked()),this,SLOT(startGame()));

  //create pause button
  	pause = new QPushButton("Pause Game");
  	options->addWidget(pause);
  	QObject::connect(pause,SIGNAL(clicked()),this,SLOT(pauseGame()));
  //create quit button
	quit = new QPushButton("Quit Game");
	options->addWidget(quit);
	QObject::connect(quit,SIGNAL(clicked()),qApp,SLOT(quit()));
  //create invincibility option
  	invincible = new QRadioButton("Invincible Mode?",this);
  	options->addWidget(invincible);

  //create message text
  	message = new Message();
  	message->setStart();
  	scene->addItem(message);

  //create input for name
	name_ = new QLineEdit();
	name_->setGeometry(300,250,190,30);
 	scene->addWidget(name_);

  //create timer
  	timer = new QTimer();
	timer->setInterval(speed);
	QObject::connect(timer,SIGNAL(timeout()),this,SLOT(handleTimer()));
}

/**
Deletes the timer.
*/
MainWindow::~MainWindow()
{
	delete timer;
	delete window;
}

/**
Starts or restarts the game. If a game hasn't been started, it checks for a user name input and, if valid, starts a game.

If a game is in the middle of gameplay, the current items are deleted and values/items are reset to their initialized state.

If a game has ended, initial items are created.

The game timer is started in this function.
*/
void MainWindow::startGame()
{
	if(!started)
	{
		//grab username
		QString n = name_->text();
		//if empty, the game won't start;
		if(n == "")
			return;

		//create username and score output
		n = n + " Score";
		s = new QFormLayout();
 	 	score = new QLineEdit(QString::number(score_));
 	 	score->setReadOnly(true);
  		score->setFixedWidth(100);
  		s->addRow(n,score);
  		options->addLayout(s);
  		options->setStretch(3,0.5);

		//make welcome screen invisible and unaccessible
		name_->setEnabled(false);
		name_->setHidden(true);
		name_->setReadOnly(true);

		started = true;
		lives_ = 3;
	}
	else
	{
		//reset values
		timer->stop();
		speed = 15;
		timer->setInterval(speed);
		score_ = 0;
		lives_ = 3;
		executions = 0;
		lose = 0;
		canLose = true;
		len = 3500;

		//delete items if not already deleted
		if(!finished)
			{
			//delete player
			delete player;

			//delete enemies
			for(QVector<Item*>::iterator it = items.begin(); it != items.end(); ++it)
			{
				Item* temp = *it;
				scene->removeItem(temp);
				delete temp;
			}
			items.clear();

			//delete lives
			for(QVector<Life*>::iterator it = lives.begin(); it != lives.end(); ++ it)
			{
				Life* temp = *it;
				scene->removeItem(temp);
				delete temp;
			}
			lives.clear();
			}
		}

		finished = false;
		//hide message
		message->setVisible(false);

		//create new player
		player = new Player();
		scene->addItem(player);

		//create lives
		int x = 5;
		for(int i=0;i<3;i++)
		{
			life = new Life(x,5,l);
			scene->addItem(life);
			lives.push_back(life);
			x = x+15;
		}

		//start timer
		timer->start();
}

/**
Pauses the game. Only applicable if the game has already been started. When pressed, the game timer is stopped and the button text changed to "Continue". If pressed again, the text is changed back and the timer started.
*/
void MainWindow::pauseGame()
{
	if(started)
	{
		if(timer->isActive())
		{
			timer->stop();
			pause->setText("Continue");
		}
		else
		{
			timer->start();
			pause->setText("Pause");
		}
	}
}

/**
Handles the timer every time it timesout. If invincible mode is checked, no collisions will be checked. Otherwise it will first check against the walls and then against the items.

If a player holds no lives, endGame() is called. If not, Items are then moved.

handleTimer() also checks if new enemies should be spawned or if the game should be sped up.
*/
void MainWindow::handleTimer()
{
  if(!invincible->isChecked())
  {
	//check collisions against wall if not invincible
	if(canLose)
	{
		if((player->getY() <= 0) || ((player->getY() + 50) >= 350))
		{
			loseLife();
			return;
		}
	}
	else if(lose == 51)
	{
		canLose = true;
		lose = 0;
		player->setVisible(true);
	}
	else
	{
		if(lose % 2)
			player->setVisible(false);
		else
			player->setVisible(true);
		lose++;
	}

	//check collisions against enemies if not invincible
	for(QVector<Item*>::iterator it = items.begin(); it != items.end(); ++it)
	{
	  Item* temp = *it;
	  temp->collide();
	}

	//check if dead
	if(!lives_)
	{
		endGame();
		return;
	}
  }
	//check if items left the scene
	deleteEnemies();

	//move items
	for(QVector<Item*>::iterator it = items.begin(); it != items.end(); ++it)
	{
		Item* temp = *it;
		temp->move();
	}

	//move player and checkes mousePress for player velocity
	int v;
	if(qApp->mouseButtons() == Qt::LeftButton)
		v = 0;
	else
		v = 1;
	player->move(v);

	//create enemies
	if(!(executions % (len/50)))
	{
		createEnemies();
	}

	//increase score and executions
	score_++;
	score->setText(QString::number(score_));
	executions++;

	//check if game requires speeding up
	if(!(executions % len) && (len <= 15000))
	{
		speed = speed / 2;
		timer->setInterval(speed);
		len = len + 5000;
	}
}

/**
Creates a new item. The new item is randomized. For WhiteMushrooms and TornadoSteps, they must also be selected by a second random statement.
*/
void MainWindow::createEnemies()
{
	//randomly create enemies
	srand(time(0));
	int a = rand() % 7;
	int b = rand() % 300;

	switch(a)
	{
		//create red nocture
		case 1:
		{
			newItem = new RedNocturne(b,rn1,rn2,player,this);
			scene->addItem(newItem);
			items.push_back(newItem);
			return;
		}
		//create aquatank
		case 2:
		{
			newItem = new Aquatank(b,at,player,this);
			scene->addItem(newItem);
			items.push_back(newItem);
			return;
		}
		//chance to create white mushroom
		case 3:
		{
			int c = rand() % 3;
			//create gem
			if(!c)
			{
				newItem = new WhiteMushroom(b,player,wm1,wm2,this);
				scene->addItem(newItem);
				items.push_back(newItem);
			}
			return;
		}
		//chance to create tornado step
		case 4:
		{
			int c = rand() % 3;
			//create gem
			if(!c)
			{
				//make sure b is in boundaries
				if(b > 250)
					b = 200;
				newItem = new TornadoStep(b,ts1,ts2,player,this);
				scene->addItem(newItem);
				items.push_back(newItem);
			}
			return;
		}
		//create air soldier
		case 5:
		{
			newItem = new AirSoldier(as1,as2,player,this);
			scene->addItem(newItem);
			items.push_back(newItem);
			return;
		}
		//create gargoyle
		case 6:
		{
			newItem = new Gargoyle(player->getY(),g1,g2,player,this);
			scene->addItem(newItem);
			items.push_back(newItem);
			return;
		}
	}

}

/**
Called when a player loses a life. Decreases the count and delets a Life image in the corner. Starts the canLose buffer so that a user can avoid the object that just killed them.
*/
void MainWindow::loseLife()
{
	lives_--;
	life = lives.back();
	scene->removeItem(life);
	lives.pop_back();
	player->setVisible(false);
	lose = 0;
	canLose = false;
}

/**
Ends the game. Stops the timer and sets the finished flag. Removes and deletes the player and the items. Also sets the GameOver message.
*/
void MainWindow::endGame()
{
	timer->stop();
	finished = true;
	scene->removeItem(player);

/*	QVector<Life*>::iterator it = lives.begin();
	while(it != lives.end())
	{
		Life* temp = *it;
		scene->removeItem(temp);
		delete temp;
		++it;
	}

	for(QVector<Item*>::iterator it = items.begin(); it != items.end(); ++it)
	{
		Item* temp = *it;
		scene->removeItem(temp);
		delete temp;
	}
	items.clear();
*/
	//set gameover message
	message->setEnd();
	message->setVisible(true);
}

/**
Called by WhiteMushroom. Gives the user an additional life.
*/
void MainWindow::gainLife()
{
	lives_++;

	Life* end = lives.back();
	life = new Life((end->getX()+15),5,l);
	scene->addItem(life);
	lives.push_back(life);
}

/**
Called by TornadoStep. Gives the user 100 additional points.
*/
void MainWindow::gainPoints()
{
	score_ = score_ + 100;
	score->setText(QString::number(score_));
}

/**
Iterates through the vector of items. If the item has moved past the left boundary, it is deleted.
*/
void MainWindow::deleteEnemies()
{
	QVector<Item*>::iterator it = items.begin();

	while(it != items.end())
	{
		Item* temp = *it;
		if(temp->getX() <= -20)
	 	 {
			it = items.erase(it);
			scene->removeItem(temp);
			delete temp;
		}
	  	else
		  ++it;
	}
}

/**
@param x number of lives to set lives_ to
Called by Aquatank. Sets the number of lives to x.
*/
void MainWindow::setLife(int x)
{
	lives_ = x;
}
<commit_msg>Finalized enemy spawning.<commit_after>#include "main.h"
#include <iostream>

/**

*/
MainWindow::MainWindow()
{
  //set variables
	started = false;
	finished = true;
	score_ = 0;
	lives_ = 0;
	executions = 0;
	speed = 15;
	canLose = true;
	len = 3500;

  //create Pixmap images
  	as1 = new QPixmap("images/airsoldier1.png","png");
  	as2 = new QPixmap("images/airsoldier2.png","png");
  	at = new QPixmap("images/aquatank.png","png");
  	g1 = new QPixmap("images/gargoyle1.png","png");
  	g2 = new QPixmap("images/gargoyle2.png","png");
  	rn1 = new QPixmap("images/rednocturne1.png","png");
  	rn2 = new QPixmap("images/rednocturne2.png","png");
  	ts1 = new QPixmap("images/tornadostep1.png","png");
  	ts2 = new QPixmap("images/tornadostep2.png","png");
  	wm1 = new QPixmap("images/whitemushroom1.png","png");
  	wm2 = new QPixmap("images/whitemushroom2.png","png");
  	l = new QPixmap("images/life.png","png");
  	bg = new QPixmap("images/background.png","png");
  	bgs = new QPixmap("images/startbackground.png","png");
  //create overall layout
	this->setGeometry(1,0,20,20);

	window = new QWidget;
	setCentralWidget(window);
	layout = new QVBoxLayout(window);
	window->setLayout(layout);

  //create options sidebar
	options = new QHBoxLayout();
	layout->addLayout(options);
  //create gamespace
	scene = new QGraphicsScene();
	scene->setSceneRect(0,0,650,350);
	view = new QGraphicsView(scene);
	view->setFixedSize(675,375);
	QRect r(0,0,675,375);
	QColor c(Qt::black);
	QBrush b(c,*bgs);
	view->setBackgroundBrush(b);
 	layout->addWidget(view);

  //create start button
  	start = new QPushButton("Start Game");
	options->addWidget(start);
	QObject::connect(start,SIGNAL(clicked()),this,SLOT(startGame()));

  //create pause button
  	pause = new QPushButton("Pause Game");
  	options->addWidget(pause);
  	QObject::connect(pause,SIGNAL(clicked()),this,SLOT(pauseGame()));
  //create quit button
	quit = new QPushButton("Quit Game");
	options->addWidget(quit);
	QObject::connect(quit,SIGNAL(clicked()),qApp,SLOT(quit()));
  //create invincibility option
  	invincible = new QRadioButton("Invincible Mode?",this);
  	options->addWidget(invincible);

  //create message text
  	message = new Message();
  	message->setStart();
  	scene->addItem(message);

  //create input for name
	name_ = new QLineEdit();
	name_->setGeometry(300,250,190,30);
 	scene->addWidget(name_);

  //create timer
  	timer = new QTimer();
	timer->setInterval(speed);
	QObject::connect(timer,SIGNAL(timeout()),this,SLOT(handleTimer()));
}

/**
Deletes the timer.
*/
MainWindow::~MainWindow()
{
	delete timer;
	delete window;
}

/**
Starts or restarts the game. If a game hasn't been started, it checks for a user name input and, if valid, starts a game.

If a game is in the middle of gameplay, the current items are deleted and values/items are reset to their initialized state.

If a game has ended, initial items are created.

The game timer is started in this function.
*/
void MainWindow::startGame()
{
	if(!started)
	{
		//grab username
		QString n = name_->text();
		//if empty, the game won't start;
		if(n == "")
			return;

		//create username and score output
		n = n + " Score";
		s = new QFormLayout();
 	 	score = new QLineEdit(QString::number(score_));
 	 	score->setReadOnly(true);
  		score->setFixedWidth(100);
  		s->addRow(n,score);
  		options->addLayout(s);
  		options->setStretch(3,0.5);

		//make welcome screen invisible and unaccessible
		name_->setEnabled(false);
		name_->setHidden(true);
		name_->setReadOnly(true);

		started = true;
		lives_ = 3;
	}
	else
	{
		//reset values
		timer->stop();
		speed = 15;
		timer->setInterval(speed);
		score_ = 0;
		lives_ = 3;
		executions = 0;
		lose = 0;
		canLose = true;
		len = 3500;

		//delete items if not already deleted
		if(!finished)
			{
			//delete player
			delete player;

			//delete enemies
			for(QVector<Item*>::iterator it = items.begin(); it != items.end(); ++it)
			{
				Item* temp = *it;
				scene->removeItem(temp);
				delete temp;
			}
			items.clear();

			//delete lives
			for(QVector<Life*>::iterator it = lives.begin(); it != lives.end(); ++ it)
			{
				Life* temp = *it;
				scene->removeItem(temp);
				delete temp;
			}
			lives.clear();
			}
		}

		finished = false;
		//hide message
		message->setVisible(false);

		//create new player
		player = new Player();
		scene->addItem(player);

		//create lives
		int x = 5;
		for(int i=0;i<3;i++)
		{
			life = new Life(x,5,l);
			scene->addItem(life);
			lives.push_back(life);
			x = x+15;
		}

		//start timer
		timer->start();
}

/**
Pauses the game. Only applicable if the game has already been started. When pressed, the game timer is stopped and the button text changed to "Continue". If pressed again, the text is changed back and the timer started.
*/
void MainWindow::pauseGame()
{
	if(started)
	{
		if(timer->isActive())
		{
			timer->stop();
			pause->setText("Continue");
		}
		else
		{
			timer->start();
			pause->setText("Pause");
		}
	}
}

/**
Handles the timer every time it timesout. If invincible mode is checked, no collisions will be checked. Otherwise it will first check against the walls and then against the items.

If a player holds no lives, endGame() is called. If not, Items are then moved.

handleTimer() also checks if new enemies should be spawned or if the game should be sped up.
*/
void MainWindow::handleTimer()
{
  if(!invincible->isChecked())
  {
	//check collisions against wall if not invincible
	if(canLose)
	{
		if((player->getY() <= 0) || ((player->getY() + 50) >= 350))
		{
			loseLife();
			return;
		}
	}
	else if(lose == 51)
	{
		canLose = true;
		lose = 0;
		player->setVisible(true);
	}
	else
	{
		if(lose % 2)
			player->setVisible(false);
		else
			player->setVisible(true);
		lose++;
	}

	//check collisions against enemies if not invincible
	for(QVector<Item*>::iterator it = items.begin(); it != items.end(); ++it)
	{
	  Item* temp = *it;
	  temp->collide();
	}

	//check if dead
	if(!lives_)
	{
		endGame();
		return;
	}
  }
	//check if items left the scene
	deleteEnemies();

	//move items
	for(QVector<Item*>::iterator it = items.begin(); it != items.end(); ++it)
	{
		Item* temp = *it;
		temp->move();
	}

	//move player and checkes mousePress for player velocity
	int v;
	if(qApp->mouseButtons() == Qt::LeftButton)
		v = 0;
	else
		v = 1;
	player->move(v);

	//create enemies
	if(!(executions % 100))
	{
		createEnemies();
	}

	//increase score and executions
	score_++;
	score->setText(QString::number(score_));
	executions++;

	//check if game requires speeding up
	if(!(executions % len) && (len <= 15000))
	{
		speed = speed / 2;
		timer->setInterval(speed);
		len = len + 5000;
	}
}

/**
Creates a new item. The new item is randomized. For WhiteMushrooms and TornadoSteps, they must also be selected by a second random statement.
*/
void MainWindow::createEnemies()
{
	//randomly create enemies
	srand(time(0));
	int a = rand() % 7;
	int b = rand() % 300;

	switch(a)
	{
		//create red nocture
		case 1:
		{
			newItem = new RedNocturne(b,rn1,rn2,player,this);
			scene->addItem(newItem);
			items.push_back(newItem);
			return;
		}
		//create aquatank
		case 2:
		{
			newItem = new Aquatank(b,at,player,this);
			scene->addItem(newItem);
			items.push_back(newItem);
			return;
		}
		//chance to create white mushroom
		case 3:
		{
			int c = rand() % 3;
			//create gem
			if(!c)
			{
				newItem = new WhiteMushroom(b,player,wm1,wm2,this);
				scene->addItem(newItem);
				items.push_back(newItem);
			}
			return;
		}
		//chance to create tornado step
		case 4:
		{
			int c = rand() % 3;
			//create gem
			if(!c)
			{
				//make sure b is in boundaries
				if(b > 250)
					b = 200;
				newItem = new TornadoStep(b,ts1,ts2,player,this);
				scene->addItem(newItem);
				items.push_back(newItem);
			}
			return;
		}
		//create air soldier
		case 5:
		{
			newItem = new AirSoldier(as1,as2,player,this);
			scene->addItem(newItem);
			items.push_back(newItem);
			return;
		}
		//create gargoyle
		case 6:
		{
			newItem = new Gargoyle(player->getY(),g1,g2,player,this);
			scene->addItem(newItem);
			items.push_back(newItem);
			return;
		}
	}

}

/**
Called when a player loses a life. Decreases the count and delets a Life image in the corner. Starts the canLose buffer so that a user can avoid the object that just killed them.
*/
void MainWindow::loseLife()
{
	lives_--;
	life = lives.back();
	scene->removeItem(life);
	lives.pop_back();
	player->setVisible(false);
	lose = 0;
	canLose = false;
}

/**
Ends the game. Stops the timer and sets the finished flag. Removes and deletes the player and the items. Also sets the GameOver message.
*/
void MainWindow::endGame()
{
	timer->stop();
	finished = true;
	scene->removeItem(player);

	QVector<Life*>::iterator it = lives.begin();
	while(it != lives.end())
	{
		Life* temp = *it;
		scene->removeItem(temp);
		delete temp;
		++it;
	}

	for(QVector<Item*>::iterator it = items.begin(); it != items.end(); ++it)
	{
		Item* temp = *it;
		scene->removeItem(temp);
		delete temp;
	}
	items.clear();

	//set gameover message
	message->setEnd();
	message->setVisible(true);
}

/**
Called by WhiteMushroom. Gives the user an additional life.
*/
void MainWindow::gainLife()
{
	lives_++;

	Life* end = lives.back();
	life = new Life((end->getX()+15),5,l);
	scene->addItem(life);
	lives.push_back(life);
}

/**
Called by TornadoStep. Gives the user 100 additional points.
*/
void MainWindow::gainPoints()
{
	score_ = score_ + 100;
	score->setText(QString::number(score_));
}

/**
Iterates through the vector of items. If the item has moved past the left boundary, it is deleted.
*/
void MainWindow::deleteEnemies()
{
	QVector<Item*>::iterator it = items.begin();

	while(it != items.end())
	{
		Item* temp = *it;
		if(temp->getX() <= -20)
	 	 {
			it = items.erase(it);
			scene->removeItem(temp);
			delete temp;
		}
	  	else
		  ++it;
	}
}

/**
@param x number of lives to set lives_ to
Called by Aquatank. Sets the number of lives to x.
*/
void MainWindow::setLife(int x)
{
	lives_ = x;
}
<|endoftext|>


<commit_before><commit_msg>For G3 use included origin from log<commit_after><|endoftext|>


<commit_before>f33e2e61-2747-11e6-8999-e0f84713e7b8<commit_msg>Really doesn't crash if X, now<commit_after>f34d34fa-2747-11e6-9e0b-e0f84713e7b8<|endoftext|>


<commit_before>/// \file RNTupleDS.cxx
/// \ingroup NTuple ROOT7
/// \author Jakob Blomer <jblomer@cern.ch>
/// \date 2018-10-04
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

/*************************************************************************
 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <ROOT/RField.hxx>
#include <ROOT/RFieldValue.hxx>
#include <ROOT/RNTupleDescriptor.hxx>
#include <ROOT/RNTupleDS.hxx>
#include <ROOT/RNTupleUtil.hxx>
#include <ROOT/RPageStorage.hxx>
#include <ROOT/RStringView.hxx>

#include <TError.h>

#include <string>
#include <vector>
#include <typeinfo>
#include <utility>

namespace ROOT {
namespace Experimental {

void ROOT::Experimental::RNTupleDS::AddFields(const RNTupleDescriptor &desc, DescriptorId_t parentId)
{
   for (const auto& f : desc.GetFieldRange(parentId)) {
      fColumnNames.emplace_back(desc.GetQualifiedFieldName(f.GetId()));
      fColumnTypes.emplace_back(f.GetTypeName());
      fColumnFieldIds.emplace_back(f.GetId());
      if (f.GetStructure() == ENTupleStructure::kRecord)
         AddFields(desc, f.GetId());
   }
}

ROOT::Experimental::RNTupleDS::RNTupleDS(std::unique_ptr<Detail::RPageSource> pageSource)
{
   pageSource->Attach();
   const auto &descriptor = pageSource->GetDescriptor();

   AddFields(descriptor, descriptor.GetFieldZeroId());

   fSources.emplace_back(std::move(pageSource));
}

RDF::RDataSource::Record_t RNTupleDS::GetColumnReadersImpl(std::string_view name, const std::type_info& /* ti */)
{
   const auto colIdx = std::distance(
      fColumnNames.begin(), std::find(fColumnNames.begin(), fColumnNames.end(), name));
   // TODO(jblomer): check expected type info like in, e.g., RRootDS.cxx

   std::vector<void*> ptrs;
   for (unsigned int slot = 0; slot < fNSlots; ++slot) {
      if (!fValuePtrs[slot][colIdx]) {
         const auto &descriptor = fSources[slot]->GetDescriptor();
         auto colName = fColumnNames[colIdx];
         auto typeName = fColumnTypes[colIdx];
         auto fieldId = descriptor.FindFieldId(colName);
         fFields[slot][colIdx] = std::unique_ptr<Detail::RFieldBase>(
            Detail::RFieldBase::Create(descriptor.GetFieldDescriptor(fieldId).GetFieldName(), typeName));
         Detail::RFieldFuse::ConnectRecursively(fieldId, *fSources[slot], *fFields[slot][colIdx]);
         fValues[slot][colIdx] = fFields[slot][colIdx]->GenerateValue();
         fValuePtrs[slot][colIdx] = fValues[slot][colIdx].GetRawPtr();
         if (slot == 0)
            fActiveColumns.emplace_back(colIdx);
      }
      ptrs.push_back(&fValuePtrs[slot][colIdx]);
   }

   return ptrs;
}

bool RNTupleDS::SetEntry(unsigned int slot, ULong64_t entryIndex)
{
   for (auto colIdx : fActiveColumns) {
      fFields[slot][colIdx]->Read(entryIndex, &fValues[slot][colIdx]);
   }
   return true;
}

std::vector<std::pair<ULong64_t, ULong64_t>> RNTupleDS::GetEntryRanges()
{
   // TODO(jblomer): use cluster boundaries for the entry ranges
   std::vector<std::pair<ULong64_t, ULong64_t>> ranges;
   if (fHasSeenAllRanges) return ranges;

   auto nEntries = fSources[0]->GetNEntries();
   const auto chunkSize = nEntries / fNSlots;
   const auto reminder = 1U == fNSlots ? 0 : nEntries % fNSlots;
   auto start = 0UL;
   auto end = 0UL;
   for (auto i : ROOT::TSeqU(fNSlots)) {
      start = end;
      end += chunkSize;
      ranges.emplace_back(start, end);
      (void)i;
   }
   ranges.back().second += reminder;
   fHasSeenAllRanges = true;
   return ranges;
}

std::string RNTupleDS::GetTypeName(std::string_view colName) const
{
   const auto index = std::distance(
      fColumnNames.begin(), std::find(fColumnNames.begin(), fColumnNames.end(), colName));
   return fColumnTypes[index];
}

bool RNTupleDS::HasColumn(std::string_view colName) const
{
   return std::find(fColumnNames.begin(), fColumnNames.end(), colName) !=
          fColumnNames.end();
}

void RNTupleDS::Initialise()
{
   fHasSeenAllRanges = false;
}

void RNTupleDS::Finalise()
{
}

void RNTupleDS::SetNSlots(unsigned int nSlots)
{
   R__ASSERT(fNSlots == 0);
   R__ASSERT(nSlots > 0);
   fNSlots = nSlots;

   fFields.resize(fNSlots);
   fValues.resize(fNSlots);
   fValuePtrs.resize(fNSlots);
   for (unsigned int i = 1; i < fNSlots; ++i) {
      fSources.emplace_back(fSources[0]->Clone());
      R__ASSERT(i == (fSources.size() - 1));
      fSources[i]->Attach();
   }

   auto nColumns = fColumnNames.size();
   for (unsigned int i = 0; i < fNSlots; ++i) {
      fFields[i].resize(nColumns);
      fValues[i].resize(nColumns);
      fValuePtrs[i].resize(nColumns, nullptr);
   }
}

RDataFrame MakeNTupleDataFrame(std::string_view ntupleName, std::string_view fileName)
{
   auto pageSource = Detail::RPageSource::Create(ntupleName, fileName);
   ROOT::RDataFrame rdf(std::make_unique<RNTupleDS>(std::move(pageSource)));
   return rdf;
}

} // ns Experimental
} // ns ROOT
<commit_msg>[RNTupleDS][NFC] Use fully qualified name for free function definition<commit_after>/// \file RNTupleDS.cxx
/// \ingroup NTuple ROOT7
/// \author Jakob Blomer <jblomer@cern.ch>
/// \date 2018-10-04
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

/*************************************************************************
 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <ROOT/RField.hxx>
#include <ROOT/RFieldValue.hxx>
#include <ROOT/RNTupleDescriptor.hxx>
#include <ROOT/RNTupleDS.hxx>
#include <ROOT/RNTupleUtil.hxx>
#include <ROOT/RPageStorage.hxx>
#include <ROOT/RStringView.hxx>

#include <TError.h>

#include <string>
#include <vector>
#include <typeinfo>
#include <utility>

namespace ROOT {
namespace Experimental {

void RNTupleDS::AddFields(const RNTupleDescriptor &desc, DescriptorId_t parentId)
{
   for (const auto& f : desc.GetFieldRange(parentId)) {
      fColumnNames.emplace_back(desc.GetQualifiedFieldName(f.GetId()));
      fColumnTypes.emplace_back(f.GetTypeName());
      fColumnFieldIds.emplace_back(f.GetId());
      if (f.GetStructure() == ENTupleStructure::kRecord)
         AddFields(desc, f.GetId());
   }
}

RNTupleDS::RNTupleDS(std::unique_ptr<Detail::RPageSource> pageSource)
{
   pageSource->Attach();
   const auto &descriptor = pageSource->GetDescriptor();

   AddFields(descriptor, descriptor.GetFieldZeroId());

   fSources.emplace_back(std::move(pageSource));
}

RDF::RDataSource::Record_t RNTupleDS::GetColumnReadersImpl(std::string_view name, const std::type_info& /* ti */)
{
   const auto colIdx = std::distance(
      fColumnNames.begin(), std::find(fColumnNames.begin(), fColumnNames.end(), name));
   // TODO(jblomer): check expected type info like in, e.g., RRootDS.cxx

   std::vector<void*> ptrs;
   for (unsigned int slot = 0; slot < fNSlots; ++slot) {
      if (!fValuePtrs[slot][colIdx]) {
         const auto &descriptor = fSources[slot]->GetDescriptor();
         auto colName = fColumnNames[colIdx];
         auto typeName = fColumnTypes[colIdx];
         auto fieldId = descriptor.FindFieldId(colName);
         fFields[slot][colIdx] = std::unique_ptr<Detail::RFieldBase>(
            Detail::RFieldBase::Create(descriptor.GetFieldDescriptor(fieldId).GetFieldName(), typeName));
         Detail::RFieldFuse::ConnectRecursively(fieldId, *fSources[slot], *fFields[slot][colIdx]);
         fValues[slot][colIdx] = fFields[slot][colIdx]->GenerateValue();
         fValuePtrs[slot][colIdx] = fValues[slot][colIdx].GetRawPtr();
         if (slot == 0)
            fActiveColumns.emplace_back(colIdx);
      }
      ptrs.push_back(&fValuePtrs[slot][colIdx]);
   }

   return ptrs;
}

bool RNTupleDS::SetEntry(unsigned int slot, ULong64_t entryIndex)
{
   for (auto colIdx : fActiveColumns) {
      fFields[slot][colIdx]->Read(entryIndex, &fValues[slot][colIdx]);
   }
   return true;
}

std::vector<std::pair<ULong64_t, ULong64_t>> RNTupleDS::GetEntryRanges()
{
   // TODO(jblomer): use cluster boundaries for the entry ranges
   std::vector<std::pair<ULong64_t, ULong64_t>> ranges;
   if (fHasSeenAllRanges) return ranges;

   auto nEntries = fSources[0]->GetNEntries();
   const auto chunkSize = nEntries / fNSlots;
   const auto reminder = 1U == fNSlots ? 0 : nEntries % fNSlots;
   auto start = 0UL;
   auto end = 0UL;
   for (auto i : ROOT::TSeqU(fNSlots)) {
      start = end;
      end += chunkSize;
      ranges.emplace_back(start, end);
      (void)i;
   }
   ranges.back().second += reminder;
   fHasSeenAllRanges = true;
   return ranges;
}

std::string RNTupleDS::GetTypeName(std::string_view colName) const
{
   const auto index = std::distance(
      fColumnNames.begin(), std::find(fColumnNames.begin(), fColumnNames.end(), colName));
   return fColumnTypes[index];
}

bool RNTupleDS::HasColumn(std::string_view colName) const
{
   return std::find(fColumnNames.begin(), fColumnNames.end(), colName) !=
          fColumnNames.end();
}

void RNTupleDS::Initialise()
{
   fHasSeenAllRanges = false;
}

void RNTupleDS::Finalise()
{
}

void RNTupleDS::SetNSlots(unsigned int nSlots)
{
   R__ASSERT(fNSlots == 0);
   R__ASSERT(nSlots > 0);
   fNSlots = nSlots;

   fFields.resize(fNSlots);
   fValues.resize(fNSlots);
   fValuePtrs.resize(fNSlots);
   for (unsigned int i = 1; i < fNSlots; ++i) {
      fSources.emplace_back(fSources[0]->Clone());
      R__ASSERT(i == (fSources.size() - 1));
      fSources[i]->Attach();
   }

   auto nColumns = fColumnNames.size();
   for (unsigned int i = 0; i < fNSlots; ++i) {
      fFields[i].resize(nColumns);
      fValues[i].resize(nColumns);
      fValuePtrs[i].resize(nColumns, nullptr);
   }
}
} // ns Experimental
} // ns ROOT

ROOT::RDataFrame ROOT::Experimental::MakeNTupleDataFrame(std::string_view ntupleName, std::string_view fileName)
{
   auto pageSource = ROOT::Experimental::Detail::RPageSource::Create(ntupleName, fileName);
   ROOT::RDataFrame rdf(std::make_unique<RNTupleDS>(std::move(pageSource)));
   return rdf;
}
<|endoftext|>


<commit_before>#include <stdio.h>

#ifdef _WIN32
#	include <windows.h>
#else
#	include <sys/time.h>
#endif

#include <GL/gl.h>
#include <GL/glut.h>

#define KEY_ESCAPE 27

int width = 640;
int height = 480;
float field_of_view_angle = 45;
float z_near = 1;
float z_far = 500;

void display() {
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
  gluLookAt(20, -10, 10, 10, 10, 0, 0.0, 0.0, 1.0);

  // GRID
  glColor3f(1.0f, 1.0f, 1.0f);
  for (int i=1; i<100; i++) {
    glBegin(GL_LINES);
      glVertex3f(i,   0, 0);
      glVertex3f(i, 100, 0);
    glEnd();
    glBegin(GL_LINES);
      glVertex3f(0,   i, 0);
      glVertex3f(100, i, 0);
    glEnd();
  }

  // AXIS
  glColor3f(1, 0, 0);
  glBegin(GL_LINES);
    glVertex3f(0, 0, 0);
    glVertex3f(100, 0, 0);
  glEnd();
  glColor3f(0, 1, 0);
  glBegin(GL_LINES);
    glVertex3f(0, 0, 0);
    glVertex3f(0, 100, 0);
  glEnd();
  glColor3f(0, 0, 1);
  glBegin(GL_LINES);
    glVertex3f(0, 0, 0);
    glVertex3f(0, 0, 100);
  glEnd();

	glutSwapBuffers();
}

void initialize ()  {
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );
	glutInitWindowSize(width, height);
	glutCreateWindow("Darwin's dream");
	glutDisplayFunc(display);
	glutIdleFunc( display );
  glutKeyboardFunc(keyboard);

  glMatrixMode(GL_PROJECTION);
  glViewport(0, 0, width, height);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  GLfloat aspect = (GLfloat) width / height;
  gluPerspective(45, aspect, 1, 500);
  glMatrixMode(GL_MODELVIEW);
  glShadeModel( GL_SMOOTH );
  glClearDepth( 1.0f );
  glEnable( GL_DEPTH_TEST );
  glDepthFunc( GL_LEQUAL );
  glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
  glClearColor(0.0, 0.0, 0.0, 1.0);
}

void keyboard ( unsigned char key, int mouseX, int mouseY ) {
  switch ( key ) {
    case KEY_ESCAPE:
      exit ( 0 );
      break;
    default:
      break;
  }
}

int main(int argc, char **argv) {
	initialize();
	glutMainLoop();

	return 0;
}

<commit_msg>Drawing cubes<commit_after>#include <stdio.h>

#ifdef _WIN32
#	include <windows.h>
#else
#	include <sys/time.h>
#endif

#include <GL/gl.h>
#include <GL/glut.h>

#define KEY_ESCAPE 27

int width = 640;
int height = 480;

void drawCube(float x, float y, float z) {
  glPushMatrix();
  glTranslatef(x, y, z);

  glBegin(GL_QUADS);
  glVertex3f(0,0 ,0);
  glVertex3f(1.0f, 0, 0);
  glVertex3f(1.0f, 1.0f, 0);
  glVertex3f(0, 1.0f, 0);

  glVertex3f(0, 0, 0);
  glVertex3f(0, 0, 1.0f);
  glVertex3f(0, 1.0f, 0);
  glVertex3f(0, 1.0f, 1.0f);

  glVertex3f(0, 0, 0);
  glVertex3f(0, 0, 1.0f);
  glVertex3f(1.0f, 0, 1.0f);
  glVertex3f(1.0f, 0, 0);

  glVertex3f(0, 0, 1.0f);
  glVertex3f(1.0f, 0, 1.0f);
  glVertex3f(1.0f, 1.0f, 1.0f);
  glVertex3f(0, 1.0f, 1.0f);

  glVertex3f(0,0 ,1.0f );
  glVertex3f(1.0f, 0, 1.0f);
  glVertex3f(1.0f, 1.0f, 1.0f);
  glVertex3f(0, 1.0f, 1.0f);

  glVertex3f(0, 1.0f, 0);
  glVertex3f(0, 1.0f, 1.0f);
  glVertex3f(1.0f, 1.0f, 1.0f);
  glVertex3f(1.0f, 1.0f, 0);
  glEnd();

  glPopMatrix();
}

void display() {
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
  gluLookAt(20, -10, 10, 10, 0, 0, 0.0, 0.0, 1.0);

  // GRID
  glColor3f(1.0f, 1.0f, 1.0f);
  for (int i=1; i<100; i++) {
    glBegin(GL_LINES);
      glVertex3f(i,   0, 0);
      glVertex3f(i, 100, 0);
    glEnd();
    glBegin(GL_LINES);
      glVertex3f(0,   i, 0);
      glVertex3f(100, i, 0);
    glEnd();
  }

  // AXIS
  glColor3f(1, 0, 0);
  glBegin(GL_LINES);
    glVertex3f(0, 0, 0);
    glVertex3f(100, 0, 0);
  glEnd();
  glColor3f(0, 1, 0);
  glBegin(GL_LINES);
    glVertex3f(0, 0, 0);
    glVertex3f(0, 100, 0);
  glEnd();
  glColor3f(0, 0, 1);
  glBegin(GL_LINES);
    glVertex3f(0, 0, 0);
    glVertex3f(0, 0, 100);
  glEnd();

  glColor3f(.5, .2, .8);
  drawCube(0,0,0);

	glutSwapBuffers();
}

void keyboard ( unsigned char key, int mouseX, int mouseY ) {
  switch ( key ) {
    case KEY_ESCAPE:
      exit ( 0 );
      break;
    default:
      break;
  }
}

void initialize()  {
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );
	glutInitWindowSize(width, height);
	glutCreateWindow("Darwin's dream");
	glutDisplayFunc(display);
	glutIdleFunc( display );
  glutKeyboardFunc(keyboard);

  glMatrixMode(GL_PROJECTION);
  glViewport(0, 0, width, height);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  GLfloat aspect = (GLfloat) width / height;
  gluPerspective(45, aspect, 1, 500);
  glMatrixMode(GL_MODELVIEW);
  glShadeModel( GL_SMOOTH );
  glClearDepth( 1.0f );
  glEnable( GL_DEPTH_TEST );
  glDepthFunc( GL_LEQUAL );
  glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
  glClearColor(0.0, 0.0, 0.0, 1.0);
}

int main(int argc, char **argv) {
	glutInit(&argc, argv);
	initialize();
	glutMainLoop();

	return 0;
}

<|endoftext|>