<commit_before>// =============================================================================
// Description: Provides an interface for the robot's shooter
// Author: FRC Team 3512, Spartatroniks
// =============================================================================

#include "Shooter.hpp"

Shooter::Shooter() {
    // m_shooterHeightPID = PIDController( 0.f, 0.f, 0.f, 0.f, 0.f, &m_shooterHeightMotor, &m_shooterHeightMotor);
    m_leftShootGrbx.SetInverted(true);
    m_leftShootGrbx.SetPIDSourceType(PIDSourceType::kRate);
    m_rightShootGrbx.SetPIDSourceType(PIDSourceType::kRate);

    auto state = std::make_unique<State>("IDLE");
    state->Entry = [this] {
    m_leftShootGrbx.Set(0);
    m_rightShootGrbx.Set(0);
    m_rollBallGrbx.Set(0);
     };

    m_intakeSM.AddState(std::move(state));
    m_intakeSM.SetState("IDLE");

    state = std::make_unique<State>("START_INTAKE");
    state->Entry = [this] {
        m_leftShootGrbx.Set(-.5);
        m_rightShootGrbx.Set(-.5);
        m_rollBallGrbx.Set(-.5);
    };
    state->Transition = [this] {
        if (IsBallLoaded()) {
            return "IDLE";
        }
        else {
            return "";
        }
    };

    m_intakeSM.AddState(std::move(state));

}

void Shooter::Shoot() {
    // Shoot only if motors spinning
    if (IsBallLoaded()) {
        m_rollBallGrbx.Set(.75);
    }
}

void Shooter::StopIntakeMotor() {
    m_rollBallGrbx.Set(0);
}
void Shooter::StartIntake() {
	if (m_intakeSM.GetState() == "IDLE") {
		m_intakeSM.SetState("START_INTAKE");
	}
}

bool Shooter::IsBallLoaded() const {
    return m_intakeLimit.Get();
}

bool Shooter::ToggleManualOverride() {
    m_manual = !m_manual;
}

bool Shooter::GetManualOverride() const {
    return m_manual;
}

void Shooter::SetManualShooterHeight(double position) {
    m_shooterHeightGrbx.Set(position);
}

void Shooter::SetPIDShooterSpeed(double speed) {
    m_leftShootPID.Enable();
    m_rightShootPID.Enable();
}

void Shooter::SetManualShooterSpeed(double speed) {
    m_leftShootPID.Disable();
    m_rightShootPID.Disable();

    m_leftShootGrbx.Set(speed);
    m_rightShootGrbx.Set(speed);
}

// TODO: FOR CURVING THE BOULDERS ONLY, REMOVE BEFORE FINAL RELEASE!
void Shooter::SetLeftShooterSpeed(double speed) {
    m_leftShootGrbx.Set(speed);
}

void Shooter::SetRightShooterSpeed(double speed) {
    m_rightShootGrbx.Set(speed);
}

/* Conversion table for calculating RPM
 * ||///////////////||/////////////////||///////////////||//////////////||
 * ||    S ticks    ||    1 rev        ||    1000 ms    ||    60 sec    ||
 * ||    -------    ||    ---------    ||    -------    ||    ------    ||
 * ||    100 ms     ||    360 ticks    ||    1 sec      ||    1 min     ||
 * ||///////////////||/////////////////||///////////////||//////////////||
 */
float Shooter::GetLeftRPM() const {
    // TODO: document magic number math
    std::cout << "Left Motor Raw Output: " << m_leftShootGrbx.GetSpeed() <<
        std::endl;
    return m_leftShootGrbx.GetSpeed() * 5.0f * 1000.0f * 60.0f * 2.0f /
           (100.0f * 360.0f);
}

float Shooter::GetRightRPM() const {
    // TODO: document magic number math
    std::cout << "Right Motor Raw Output: " << m_rightShootGrbx.GetSpeed() <<
        std::endl;
    return m_rightShootGrbx.GetSpeed() * 5.0f * 1000.0f * 60.0f * 2.0f /
           (100.0f * 360.0f);
}

void Shooter::ReloadPID() {
}

void Shooter::ResetEncoders() {
}
<commit_msg>Added missing UpdateState function<commit_after>// =============================================================================
// Description: Provides an interface for the robot's shooter
// Author: FRC Team 3512, Spartatroniks
// =============================================================================

#include "Shooter.hpp"

Shooter::Shooter() {
    // m_shooterHeightPID = PIDController( 0.f, 0.f, 0.f, 0.f, 0.f, &m_shooterHeightMotor, &m_shooterHeightMotor);
    m_leftShootGrbx.SetInverted(true);
    m_leftShootGrbx.SetPIDSourceType(PIDSourceType::kRate);
    m_rightShootGrbx.SetPIDSourceType(PIDSourceType::kRate);

    auto state = std::make_unique<State>("IDLE");
    state->Entry = [this] {
    m_leftShootGrbx.Set(0);
    m_rightShootGrbx.Set(0);
    m_rollBallGrbx.Set(0);
     };

    m_intakeSM.AddState(std::move(state));
    m_intakeSM.SetState("IDLE");

    state = std::make_unique<State>("START_INTAKE");
    state->Entry = [this] {
        m_leftShootGrbx.Set(-.5);
        m_rightShootGrbx.Set(-.5);
        m_rollBallGrbx.Set(-.5);
    };
    state->Transition = [this] {
        if (IsBallLoaded()) {
            return "IDLE";
        }
        else {
            return "";
        }
    };

    m_intakeSM.AddState(std::move(state));

}

void Shooter::Shoot() {
    // Shoot only if motors spinning
    if (IsBallLoaded()) {
        m_rollBallGrbx.Set(.75);
    }
}

void Shooter::StopIntakeMotor() {
    m_rollBallGrbx.Set(0);
}
void Shooter::StartIntake() {
	if (m_intakeSM.GetState() == "IDLE") {
		m_intakeSM.SetState("START_INTAKE");
	}
}

bool Shooter::IsBallLoaded() const {
    return m_intakeLimit.Get();
}

bool Shooter::ToggleManualOverride() {
    m_manual = !m_manual;
}

void Shooter::UpdateState() {
	m_intakeSM.Run();
}

bool Shooter::GetManualOverride() const {
    return m_manual;
}

void Shooter::SetManualShooterHeight(double position) {
    m_shooterHeightGrbx.Set(position);
}

void Shooter::SetPIDShooterSpeed(double speed) {
    m_leftShootPID.Enable();
    m_rightShootPID.Enable();
}

void Shooter::SetManualShooterSpeed(double speed) {
    m_leftShootPID.Disable();
    m_rightShootPID.Disable();

    m_leftShootGrbx.Set(speed);
    m_rightShootGrbx.Set(speed);
}

// TODO: FOR CURVING THE BOULDERS ONLY, REMOVE BEFORE FINAL RELEASE!
void Shooter::SetLeftShooterSpeed(double speed) {
    m_leftShootGrbx.Set(speed);
}

void Shooter::SetRightShooterSpeed(double speed) {
    m_rightShootGrbx.Set(speed);
}

/* Conversion table for calculating RPM
 * ||///////////////||/////////////////||///////////////||//////////////||
 * ||    S ticks    ||    1 rev        ||    1000 ms    ||    60 sec    ||
 * ||    -------    ||    ---------    ||    -------    ||    ------    ||
 * ||    100 ms     ||    360 ticks    ||    1 sec      ||    1 min     ||
 * ||///////////////||/////////////////||///////////////||//////////////||
 */
float Shooter::GetLeftRPM() const {
    // TODO: document magic number math
    std::cout << "Left Motor Raw Output: " << m_leftShootGrbx.GetSpeed() <<
        std::endl;
    return m_leftShootGrbx.GetSpeed() * 5.0f * 1000.0f * 60.0f * 2.0f /
           (100.0f * 360.0f);
}

float Shooter::GetRightRPM() const {
    // TODO: document magic number math
    std::cout << "Right Motor Raw Output: " << m_rightShootGrbx.GetSpeed() <<
        std::endl;
    return m_rightShootGrbx.GetSpeed() * 5.0f * 1000.0f * 60.0f * 2.0f /
           (100.0f * 360.0f);
}

void Shooter::ReloadPID() {
}

void Shooter::ResetEncoders() {
}
<|endoftext|>


<commit_before>
#include <system.h>
#include <console.h>
#include <stdio.h>
#include <stdint.h>
#include <memory.h>
#include "video.h"

namespace badapple {

extern uint8_t vdatas[] asm("_binary_vdata_bin_start");
extern uint8_t vdatae[] asm("_binary_vdata_bin_end");

video::video(void) {
	printf("video raw data address = %d\n", (int) vdatas);

	cur_frame = count = 0;
	pool = (uint16_t *) 0x300000;

	uint8_t *raw_ptr = (uint8_t *) vdatas;
	uint16_t *pool_ptr = pool;
	uint16_t attrib;

	while (raw_ptr < vdatae) {
		uint8_t raw = *raw_ptr;
		for (int i = 0; i < 8; ++i) {
			attrib = (0xf << 8) | (raw & 1 ? ' ' : '*');
			raw = raw >> 1;
			*pool_ptr++ = attrib;
		}
		++raw_ptr;
		++count;
	}
}

bool video::has_next(void) {
	return cur_frame < count;
}

void video::next(void) {
	console::bkcopy(pool + cur_frame * 25*80);
	cur_frame += 1;
}

} /* badapple */<commit_msg>stupid bug fix<commit_after>
#include <system.h>
#include <console.h>
#include <stdio.h>
#include <stdint.h>
#include <memory.h>
#include "video.h"

namespace badapple {

extern uint8_t vdatas[] asm("_binary_vdata_bin_start");
extern uint8_t vdatae[] asm("_binary_vdata_bin_end");

video::video(void) {
	printf("video raw data address = %d.\n", (int) vdatas);

	cur_frame = count = 0;
	pool = (uint16_t *) 0x300000;

	uint8_t *raw_ptr = (uint8_t *) vdatas;
	uint16_t *pool_ptr = pool;
	uint16_t attrib;

	count = int(vdatae - vdatas) * 8 / 25 / 80;
	printf("video frame count = %d.\n", count);

	while (raw_ptr < vdatae) {
		uint8_t raw = *raw_ptr;
		for (int i = 0; i < 8; ++i) {
			attrib = (0xf << 8) | (raw & 1 ? ' ' : '*');
			raw = raw >> 1;
			*pool_ptr++ = attrib;
		}
		++raw_ptr;
	}
}

bool video::has_next(void) {
	return cur_frame < count;
}

void video::next(void) {
	console::bkcopy(pool + cur_frame * 25*80);
	cur_frame += 1;
}

} /* badapple */<|endoftext|>


<commit_before>#include <node.h>
#include <node_events.h>
#include <assert.h>
#include <string.h>
#include <zlib.h>

#define CHUNK 16384

using namespace v8;
using namespace node;

class Gzip : public EventEmitter {
 public:
  static void
  Initialize (v8::Handle<v8::Object> target)
  {
    HandleScope scope;

    Local<FunctionTemplate> t = FunctionTemplate::New(New);

    t->Inherit(EventEmitter::constructor_template);
    t->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(t, "init", GzipInit);
    NODE_SET_PROTOTYPE_METHOD(t, "deflate", GzipDeflate);
    NODE_SET_PROTOTYPE_METHOD(t, "end", GzipEnd);

    target->Set(String::NewSymbol("Gzip"), t->GetFunction());
  }

  int GzipInit(int level) {
    int ret;
    /* allocate deflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    ret = deflateInit2(&strm, level, Z_DEFLATED, 16+MAX_WBITS, 8, Z_DEFAULT_STRATEGY);
    return ret;
  }

  int GzipDeflate(char* data, int data_len, char** out, int* out_len) {
    int ret;
    char* temp;
    int i=1;

    if (data_len == 0)
      return 0;

    *out = NULL;
    *out_len = 0;
    ret = 0;

    while(data_len>0) {
      if (data_len>CHUNK) {
	strm.avail_in = CHUNK;
      } else {
	strm.avail_in = data_len;
      }

      strm.next_in = (Bytef*)data;
      do {
	temp = (char *)realloc(*out, CHUNK*i +1);
	if (temp == NULL) {
	  return Z_MEM_ERROR;
	}
	*out = temp;
	strm.avail_out = CHUNK;
        strm.next_out = (Bytef*)*out + *out_len;
	ret = deflate(&strm, Z_NO_FLUSH);
	assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
	*out_len += (CHUNK - strm.avail_out);
	i++;
      } while (strm.avail_out == 0);

      data += CHUNK;
      data_len -= CHUNK;
    }
    return ret;
  }

  int GzipEnd(char** out, int*out_len) {
    int ret;
    char* temp;
    int i = 1;

    *out = NULL;
    *out_len = 0;
    strm.avail_in = 0;
    strm.next_in = NULL;

    do {
      temp = (char *)realloc(*out, CHUNK*i);
      if (temp == NULL) {
	return Z_MEM_ERROR;
      }
      *out = temp;
      strm.avail_out = CHUNK;
      strm.next_out = (Bytef*)*out + *out_len;
      ret = deflate(&strm, Z_FINISH);
      assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
      *out_len += (CHUNK - strm.avail_out);
      i++;
    } while (strm.avail_out == 0);

    deflateEnd(&strm);
    return ret;
  }

 protected:

  static Handle<Value>
  New (const Arguments& args)
  {
    HandleScope scope;

    Gzip *gzip = new Gzip();
    gzip->Wrap(args.This());

    return args.This();
  }

  static Handle<Value>
  GzipInit (const Arguments& args)
  {
    Gzip *gzip = ObjectWrap::Unwrap<Gzip>(args.This());

    HandleScope scope;

    int level=Z_DEFAULT_COMPRESSION;

    int r = gzip->GzipInit(level);

    return scope.Close(Integer::New(r));
  }

  static Handle<Value>
  GzipDeflate(const Arguments& args) {
    Gzip *gzip = ObjectWrap::Unwrap<Gzip>(args.This());

    HandleScope scope;

    enum encoding enc = ParseEncoding(args[1]);
    ssize_t len = DecodeBytes(args[0], enc);

    if (len < 0) {
      Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
      return ThrowException(exception);
    }
    char* buf = new char[len];
    ssize_t written = DecodeWrite(buf, len, args[0], enc);
    assert(written == len);

    char* out;
    int out_size;
    int r = gzip->GzipDeflate(buf, len, &out, &out_size);

    if (out_size==0) {
      return scope.Close(String::New(""));
    }

    Local<Value> outString = Encode(out, out_size, BINARY);
    free(out);
    return scope.Close(outString);
  }

  static Handle<Value>
  GzipEnd(const Arguments& args) {
    Gzip *gzip = ObjectWrap::Unwrap<Gzip>(args.This());

    HandleScope scope;

    char* out;
    int out_size;
    bool hex_format = false;

    if (args.Length() > 0 && args[0]->IsString()) {
      String::Utf8Value format_type(args[1]->ToString());
    }

    int r = gzip->GzipEnd( &out, &out_size);

    if (out_size==0) {
      return String::New("");
    }
    Local<Value> outString = Encode(out, out_size, BINARY);
    free(out);
    return scope.Close(outString);

  }

  Gzip () : EventEmitter ()
  {
  }

  ~Gzip ()
  {
  }

 private:

  z_stream strm;
};

class Gunzip : public EventEmitter {
 public:
  static void
  Initialize (v8::Handle<v8::Object> target)
  {
    HandleScope scope;

    Local<FunctionTemplate> t = FunctionTemplate::New(New);

    t->Inherit(EventEmitter::constructor_template);
    t->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(t, "init", GunzipInit);
    NODE_SET_PROTOTYPE_METHOD(t, "inflate", GunzipInflate);
    NODE_SET_PROTOTYPE_METHOD(t, "end", GunzipEnd);

    target->Set(String::NewSymbol("Gunzip"), t->GetFunction());
  }

  int GunzipInit() {
    /* allocate inflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;
    int ret = inflateInit2(&strm, 16+MAX_WBITS);
    return ret;
  }

  int GunzipInflate(const char* data, int data_len, char** out, int* out_len) {
    int ret;
    char* temp;
    int i=1;

    if (data_len == 0)
      return 0;

    *out = NULL;
    *out_len = 0;

    while(data_len>0) {
      if (data_len>CHUNK) {
	strm.avail_in = CHUNK;
      } else {
	strm.avail_in = data_len;
      }

      strm.next_in = (Bytef*)data;

      do {
	temp = (char *)realloc(*out, CHUNK*i);
	if (temp == NULL) {
	  return Z_MEM_ERROR;
	}
	*out = temp;
        strm.avail_out = CHUNK;
	strm.next_out = (Bytef*)*out + *out_len;
	ret = inflate(&strm, Z_NO_FLUSH);
	assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
	switch (ret) {
	case Z_NEED_DICT:
	  ret = Z_DATA_ERROR;     /* and fall through */
	case Z_DATA_ERROR:
	case Z_MEM_ERROR:
	  (void)inflateEnd(&strm);
	  return ret;
	}
	*out_len += (CHUNK - strm.avail_out);
	i++;
      } while (strm.avail_out == 0);
      data += CHUNK;
      data_len -= CHUNK;
    }
    return ret;

  }

  void GunzipEnd() {
    inflateEnd(&strm);
  }

 protected:

  static Handle<Value>
  New(const Arguments& args) {
    HandleScope scope;

    Gunzip *gunzip = new Gunzip();
    gunzip->Wrap(args.This());

    return args.This();
  }

  static Handle<Value>
  GunzipInit(const Arguments& args) {
    Gunzip *gunzip = ObjectWrap::Unwrap<Gunzip>(args.This());

    HandleScope scope;

    int r = gunzip->GunzipInit();

    return scope.Close(Integer::New(r));
  }

  static Handle<Value>
  GunzipInflate(const Arguments& args) {
    Gunzip *gunzip = ObjectWrap::Unwrap<Gunzip>(args.This());

    HandleScope scope;

    enum encoding enc = ParseEncoding(args[1]);
    ssize_t len = DecodeBytes(args[0], enc);

    if (len < 0) {
      Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
      return ThrowException(exception);
    }

    char* buf = new char[len];
    ssize_t written = DecodeWrite(buf, len, args[0], BINARY);
    assert(written == len);

    char* out;
    int out_size;
    int r = gunzip->GunzipInflate(buf, len, &out, &out_size);

    Local<Value> outString = Encode(out, out_size, enc);
    free(out);
    return scope.Close(outString);
  }

  static Handle<Value>
  GunzipEnd(const Arguments& args) {
    Gunzip *gunzip = ObjectWrap::Unwrap<Gunzip>(args.This());

    HandleScope scope;

    gunzip->GunzipEnd();

    return scope.Close(String::New(""));
  }

  Gunzip () : EventEmitter ()
  {
  }

  ~Gunzip ()
  {
  }

 private:

 z_stream strm;

};

extern "C" void
init (Handle<Object> target)
{
  HandleScope scope;
  Gzip::Initialize(target);
  Gunzip::Initialize(target);
}
<commit_msg>Fix missing header for linux build<commit_after>#include <node.h>
#include <node_events.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <zlib.h>

#define CHUNK 16384

using namespace v8;
using namespace node;

class Gzip : public EventEmitter {
 public:
  static void
  Initialize (v8::Handle<v8::Object> target)
  {
    HandleScope scope;

    Local<FunctionTemplate> t = FunctionTemplate::New(New);

    t->Inherit(EventEmitter::constructor_template);
    t->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(t, "init", GzipInit);
    NODE_SET_PROTOTYPE_METHOD(t, "deflate", GzipDeflate);
    NODE_SET_PROTOTYPE_METHOD(t, "end", GzipEnd);

    target->Set(String::NewSymbol("Gzip"), t->GetFunction());
  }

  int GzipInit(int level) {
    int ret;
    /* allocate deflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    ret = deflateInit2(&strm, level, Z_DEFLATED, 16+MAX_WBITS, 8, Z_DEFAULT_STRATEGY);
    return ret;
  }

  int GzipDeflate(char* data, int data_len, char** out, int* out_len) {
    int ret;
    char* temp;
    int i=1;

    if (data_len == 0)
      return 0;

    *out = NULL;
    *out_len = 0;
    ret = 0;

    while(data_len>0) {
      if (data_len>CHUNK) {
	strm.avail_in = CHUNK;
      } else {
	strm.avail_in = data_len;
      }

      strm.next_in = (Bytef*)data;
      do {
	temp = (char *)realloc(*out, CHUNK*i +1);
	if (temp == NULL) {
	  return Z_MEM_ERROR;
	}
	*out = temp;
	strm.avail_out = CHUNK;
        strm.next_out = (Bytef*)*out + *out_len;
	ret = deflate(&strm, Z_NO_FLUSH);
	assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
	*out_len += (CHUNK - strm.avail_out);
	i++;
      } while (strm.avail_out == 0);

      data += CHUNK;
      data_len -= CHUNK;
    }
    return ret;
  }

  int GzipEnd(char** out, int*out_len) {
    int ret;
    char* temp;
    int i = 1;

    *out = NULL;
    *out_len = 0;
    strm.avail_in = 0;
    strm.next_in = NULL;

    do {
      temp = (char *)realloc(*out, CHUNK*i);
      if (temp == NULL) {
	return Z_MEM_ERROR;
      }
      *out = temp;
      strm.avail_out = CHUNK;
      strm.next_out = (Bytef*)*out + *out_len;
      ret = deflate(&strm, Z_FINISH);
      assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
      *out_len += (CHUNK - strm.avail_out);
      i++;
    } while (strm.avail_out == 0);

    deflateEnd(&strm);
    return ret;
  }

 protected:

  static Handle<Value>
  New (const Arguments& args)
  {
    HandleScope scope;

    Gzip *gzip = new Gzip();
    gzip->Wrap(args.This());

    return args.This();
  }

  static Handle<Value>
  GzipInit (const Arguments& args)
  {
    Gzip *gzip = ObjectWrap::Unwrap<Gzip>(args.This());

    HandleScope scope;

    int level=Z_DEFAULT_COMPRESSION;

    int r = gzip->GzipInit(level);

    return scope.Close(Integer::New(r));
  }

  static Handle<Value>
  GzipDeflate(const Arguments& args) {
    Gzip *gzip = ObjectWrap::Unwrap<Gzip>(args.This());

    HandleScope scope;

    enum encoding enc = ParseEncoding(args[1]);
    ssize_t len = DecodeBytes(args[0], enc);

    if (len < 0) {
      Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
      return ThrowException(exception);
    }
    char* buf = new char[len];
    ssize_t written = DecodeWrite(buf, len, args[0], enc);
    assert(written == len);

    char* out;
    int out_size;
    int r = gzip->GzipDeflate(buf, len, &out, &out_size);

    if (out_size==0) {
      return scope.Close(String::New(""));
    }

    Local<Value> outString = Encode(out, out_size, BINARY);
    free(out);
    return scope.Close(outString);
  }

  static Handle<Value>
  GzipEnd(const Arguments& args) {
    Gzip *gzip = ObjectWrap::Unwrap<Gzip>(args.This());

    HandleScope scope;

    char* out;
    int out_size;
    bool hex_format = false;

    if (args.Length() > 0 && args[0]->IsString()) {
      String::Utf8Value format_type(args[1]->ToString());
    }

    int r = gzip->GzipEnd( &out, &out_size);

    if (out_size==0) {
      return String::New("");
    }
    Local<Value> outString = Encode(out, out_size, BINARY);
    free(out);
    return scope.Close(outString);

  }

  Gzip () : EventEmitter ()
  {
  }

  ~Gzip ()
  {
  }

 private:

  z_stream strm;
};

class Gunzip : public EventEmitter {
 public:
  static void
  Initialize (v8::Handle<v8::Object> target)
  {
    HandleScope scope;

    Local<FunctionTemplate> t = FunctionTemplate::New(New);

    t->Inherit(EventEmitter::constructor_template);
    t->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(t, "init", GunzipInit);
    NODE_SET_PROTOTYPE_METHOD(t, "inflate", GunzipInflate);
    NODE_SET_PROTOTYPE_METHOD(t, "end", GunzipEnd);

    target->Set(String::NewSymbol("Gunzip"), t->GetFunction());
  }

  int GunzipInit() {
    /* allocate inflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;
    int ret = inflateInit2(&strm, 16+MAX_WBITS);
    return ret;
  }

  int GunzipInflate(const char* data, int data_len, char** out, int* out_len) {
    int ret;
    char* temp;
    int i=1;

    if (data_len == 0)
      return 0;

    *out = NULL;
    *out_len = 0;

    while(data_len>0) {
      if (data_len>CHUNK) {
	strm.avail_in = CHUNK;
      } else {
	strm.avail_in = data_len;
      }

      strm.next_in = (Bytef*)data;

      do {
	temp = (char *)realloc(*out, CHUNK*i);
	if (temp == NULL) {
	  return Z_MEM_ERROR;
	}
	*out = temp;
        strm.avail_out = CHUNK;
	strm.next_out = (Bytef*)*out + *out_len;
	ret = inflate(&strm, Z_NO_FLUSH);
	assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
	switch (ret) {
	case Z_NEED_DICT:
	  ret = Z_DATA_ERROR;     /* and fall through */
	case Z_DATA_ERROR:
	case Z_MEM_ERROR:
	  (void)inflateEnd(&strm);
	  return ret;
	}
	*out_len += (CHUNK - strm.avail_out);
	i++;
      } while (strm.avail_out == 0);
      data += CHUNK;
      data_len -= CHUNK;
    }
    return ret;

  }

  void GunzipEnd() {
    inflateEnd(&strm);
  }

 protected:

  static Handle<Value>
  New(const Arguments& args) {
    HandleScope scope;

    Gunzip *gunzip = new Gunzip();
    gunzip->Wrap(args.This());

    return args.This();
  }

  static Handle<Value>
  GunzipInit(const Arguments& args) {
    Gunzip *gunzip = ObjectWrap::Unwrap<Gunzip>(args.This());

    HandleScope scope;

    int r = gunzip->GunzipInit();

    return scope.Close(Integer::New(r));
  }

  static Handle<Value>
  GunzipInflate(const Arguments& args) {
    Gunzip *gunzip = ObjectWrap::Unwrap<Gunzip>(args.This());

    HandleScope scope;

    enum encoding enc = ParseEncoding(args[1]);
    ssize_t len = DecodeBytes(args[0], enc);

    if (len < 0) {
      Local<Value> exception = Exception::TypeError(String::New("Bad argument"));
      return ThrowException(exception);
    }

    char* buf = new char[len];
    ssize_t written = DecodeWrite(buf, len, args[0], BINARY);
    assert(written == len);

    char* out;
    int out_size;
    int r = gunzip->GunzipInflate(buf, len, &out, &out_size);

    Local<Value> outString = Encode(out, out_size, enc);
    free(out);
    return scope.Close(outString);
  }

  static Handle<Value>
  GunzipEnd(const Arguments& args) {
    Gunzip *gunzip = ObjectWrap::Unwrap<Gunzip>(args.This());

    HandleScope scope;

    gunzip->GunzipEnd();

    return scope.Close(String::New(""));
  }

  Gunzip () : EventEmitter ()
  {
  }

  ~Gunzip ()
  {
  }

 private:

 z_stream strm;

};

extern "C" void
init (Handle<Object> target)
{
  HandleScope scope;
  Gzip::Initialize(target);
  Gunzip::Initialize(target);
}
<|endoftext|>


<commit_before>//! Copyright (c) 2013 ASMlover. All rights reserved.
//!
//! Redistribution and use in source and binary forms, with or without
//! modification, are permitted provided that the following conditions
//! are met:
//!
//!  * Redistributions of source code must retain the above copyright
//!    notice, this list ofconditions and the following disclaimer.
//!
//!  * Redistributions in binary form must reproduce the above copyright
//!    notice, this list of conditions and the following disclaimer in
//!    the documentation and/or other materialsprovided with the
//!    distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#if defined(_WINDOWS_) || defined(_MSC_VER)
# ifndef _WINDOWS_
#   include <winsock2.h>
# endif
  typedef int socklen_t;
#elif defined(__linux__)
# include <sys/types.h>
# include <sys/socket.h>
# include <arpa/inet.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <unistd.h>
# include <fcntl.h>
#endif
#include "net.h"
#include "address.h"
#include "socket.h"

Socket::Socket(void)
  : fd_(kNetTypeInval)
{
}

Socket::~Socket(void)
{
  Close();
}

bool
Socket::SetOption(int level, int optname, int optval)
{
  if (kNetTypeInval == fd_)
    return false;

  if (kNetTypeError == setsockopt(fd_, level,
        optname,
#if defined(_WINDOWS_) || defined(_MSC_VER)
        (const char*)&optval,
#elif defined(__linux__)
        (const void*)&optval,
#endif
        sizeof(optval)))
    return false;

  return true;
}

bool
Socket::SetNonBlock(void)
{
  if (kNetTypeInval == fd_)
    return false;

#if defined(_WINDOWS_) || defined(_MSC_VER)
  u_long mode = 1;
  if (kNetTypeError == ioctlsocket(fd_, FIONBIO, &mode))
    return false;
#elif defined(__linux__)
  int opt = fcntl(fd_, F_GETFL);
  if (kNetTypeError == fd_)
    return false;
  if (kNetTypeError == fcntl(fd_, F_SETFL, opt | O_NONBLOCK))
    return false;
#endif

  return true;
}

bool
Socket::SetTcpNoDelay(bool nodelay)
{
  return SetOption(IPPROTO_TCP, TCP_NODELAY, (nodelay ? 1 : 0));
}

bool
Socket::SetReuseAddr(bool reuse)
{
  return SetOption(SOL_SOCKET, SO_REUSEADDR, (reuse ? 1 : 0));
}

bool
Socket::SetKeepAlive(bool keep)
{
  return SetOption(SOL_SOCKET, SO_KEEPALIVE, (keep ? 1 : 0));
}

bool
Socket::SetReadBuffer(int bytes)
{
  return SetOption(SOL_SOCKET, SO_RCVBUF, bytes);
}

bool
Socket::SetWriteBuffer(int bytes)
{
  return SetOption(SOL_SOCKET, SO_SNDBUF, bytes);
}

bool
Socket::SetSelfReadBuffer(int bytes)
{
  return rbuf_.Init(bytes);
}

bool
Socket::SetSelfWriteBuffer(int bytes)
{
  return wbuf_.Init(bytes);
}

bool
Socket::Open(void)
{
  fd_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (kNetTypeInval == fd_)
    return false;

  return true;
}

void
Socket::Close(void)
{
  if (kNetTypeInval == fd_) {
#if defined(_WINDOWS_) || defined(_MSC_VER)
    shutdown(fd_, SD_BOTH);
    closesocket(fd_);
#elif defined(__linux__)
    shutdown(fd_, SHUT_RDWR);
    close(fd_);
#endif
    fd_ = kNetTypeInval;
  }
}

bool
Socket::Bind(const char* ip, unsigned short port)
{
  if (kNetTypeInval == fd_)
    return false;

  struct sockaddr_in host_addr;
  host_addr.sin_addr.s_addr =
    (NULL == ip ? htonl(INADDR_ANY) : inet_addr(ip));
  host_addr.sin_family      = AF_INET;
  host_addr.sin_port        = htons(port);

  if (kNetTypeError == bind(fd_,
        (struct sockaddr*)&host_addr, sizeof(host_addr)))
    return false;

  return true;
}

bool
Socket::Listen(void)
{
  if (kNetTypeInval == fd_)
    return false;

  if (kNetTypeError == listen(fd_, SOMAXCONN))
    return false;

  return true;
}

bool
Socket::Accept(Socket* s, Address* addr)
{
  if (kNetTypeInval == fd_ || NULL == s)
    return false;

  struct sockaddr_in remote_addr;
  socklen_t addrlen = sizeof(remote_addr);
  int fd = accept(fd_, (struct sockaddr*)&remote_addr, &addrlen);
  if (kNetTypeInval == fd)
    return false;

  s->Attach(fd);
  if (NULL != addr)
    addr->Attach(&remote_addr);

  return true;
}

bool
Socket::Connect(const char* ip, unsigned short port)
{
  if (kNetTypeInval == fd_)
    return false;

  if (NULL == ip)
    ip = "127.0.0.1";
  struct sockaddr_in remote_addr;
  remote_addr.sin_addr.s_addr = inet_addr(ip);
  remote_addr.sin_family      = AF_INET;
  remote_addr.sin_port        = htons(port);
  if (kNetTypeError == connect(fd_,
        (struct sockaddr*)&remote_addr, sizeof(remote_addr)))
    return false;

  return true;
}

int
Socket::ReadBlock(int bytes, char* buffer)
{
  if (kNetTypeInval == fd_ || bytes <= 0 || NULL == buffer)
    return kNetTypeError;

  int ret = recv(fd_, buffer, bytes, 0);

  return ret;
}

int
Socket::WriteBlock(const char* buffer, int bytes)
{
  if (kNetTypeInval == fd_ || NULL == buffer || bytes <= 0)
    return kNetTypeError;

  int write_bytes = 0;
  int ret;
  while (write_bytes < bytes) {
    ret = send(fd_, buffer + write_bytes, bytes - write_bytes, 0);
    if (kNetTypeError == ret)
      return ret;

    write_bytes += ret;
  }

  return write_bytes;
}

int
Socket::Read(int bytes, char* buffer)
{
  if (kNetTypeInval == fd_ || bytes <= 0 || NULL == buffer)
    return kNetTypeError;

  return rbuf_.Get(bytes, buffer);
}

int
Socket::Write(const char* buffer, int bytes)
{
  if (kNetTypeInval == fd_ || NULL == buffer || bytes <= 0)
    return kNetTypeError;

  return wbuf_.Put(buffer, bytes);
}

int
Socket::DealWithAsyncRead(void)
{
  if (kNetTypeInval == fd_)
    return kNetTypeError;

  int read_bytes = 0;
  int ret;
  char* free_buffer = rbuf_.free_buffer();
  int   free_length = rbuf_.free_length();
  while (true) {
    if (0 == free_length) {
      rbuf_.Regrow();
      free_buffer = rbuf_.free_buffer();
      free_length = rbuf_.free_length();
    }

    ret = recv(fd_, free_buffer, free_length, 0);
    if (ret > 0) {
      rbuf_.Increment(ret);
      read_bytes += ret;
      if (ret < free_length)
        break;
    }
    else {
      return ret;
    }
  }

  return read_bytes;
}

int
Socket::DealWithAsyncWrite(void)
{
  if (kNetTypeInval == fd_)
    return kNetTypeError;

  int length = wbuf_.length();
  if (length <= 0)
    return 0;

  const char* buffer = wbuf_.buffer();
  int ret = send(fd_, buffer, length, 0);

  if (ret > 0)
    wbuf_.Decrement(ret);

  return ret;
}

bool
Socket::CheckValidMessageInReadBuffer(void)
{
  return true;
}
<commit_msg>updated socket module<commit_after>//! Copyright (c) 2013 ASMlover. All rights reserved.
//!
//! Redistribution and use in source and binary forms, with or without
//! modification, are permitted provided that the following conditions
//! are met:
//!
//!  * Redistributions of source code must retain the above copyright
//!    notice, this list ofconditions and the following disclaimer.
//!
//!  * Redistributions in binary form must reproduce the above copyright
//!    notice, this list of conditions and the following disclaimer in
//!    the documentation and/or other materialsprovided with the
//!    distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#if defined(_WINDOWS_) || defined(_MSC_VER)
# ifndef _WINDOWS_
#   include <winsock2.h>
# endif
  typedef int socklen_t;
#elif defined(__linux__)
# include <sys/types.h>
# include <sys/socket.h>
# include <arpa/inet.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <unistd.h>
# include <fcntl.h>
#endif
#include "net.h"
#include "address.h"
#include "socket.h"

Socket::Socket(void)
  : fd_(kNetTypeInval)
{
}

Socket::~Socket(void)
{
  Close();
}

bool
Socket::SetOption(int level, int optname, int optval)
{
  if (kNetTypeInval == fd_)
    return false;

  if (kNetTypeError == setsockopt(fd_, level,
        optname,
#if defined(_WINDOWS_) || defined(_MSC_VER)
        (const char*)&optval,
#elif defined(__linux__)
        (const void*)&optval,
#endif
        sizeof(optval)))
    return false;

  return true;
}

bool
Socket::SetNonBlock(void)
{
  if (kNetTypeInval == fd_)
    return false;

#if defined(_WINDOWS_) || defined(_MSC_VER)
  u_long mode = 1;
  if (kNetTypeError == ioctlsocket(fd_, FIONBIO, &mode))
    return false;
#elif defined(__linux__)
  int opt = fcntl(fd_, F_GETFL);
  if (kNetTypeError == fd_)
    return false;
  if (kNetTypeError == fcntl(fd_, F_SETFL, opt | O_NONBLOCK))
    return false;
#endif

  return true;
}

bool
Socket::SetTcpNoDelay(bool nodelay)
{
  return SetOption(IPPROTO_TCP, TCP_NODELAY, (nodelay ? 1 : 0));
}

bool
Socket::SetReuseAddr(bool reuse)
{
  return SetOption(SOL_SOCKET, SO_REUSEADDR, (reuse ? 1 : 0));
}

bool
Socket::SetKeepAlive(bool keep)
{
  return SetOption(SOL_SOCKET, SO_KEEPALIVE, (keep ? 1 : 0));
}

bool
Socket::SetReadBuffer(int bytes)
{
  return SetOption(SOL_SOCKET, SO_RCVBUF, bytes);
}

bool
Socket::SetWriteBuffer(int bytes)
{
  return SetOption(SOL_SOCKET, SO_SNDBUF, bytes);
}

bool
Socket::SetSelfReadBuffer(int bytes)
{
  return rbuf_.Init(bytes);
}

bool
Socket::SetSelfWriteBuffer(int bytes)
{
  return wbuf_.Init(bytes);
}

bool
Socket::Open(void)
{
  fd_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (kNetTypeInval == fd_)
    return false;

  return true;
}

void
Socket::Close(void)
{
  if (kNetTypeInval == fd_) {
#if defined(_WINDOWS_) || defined(_MSC_VER)
    shutdown(fd_, SD_BOTH);
    closesocket(fd_);
#elif defined(__linux__)
    shutdown(fd_, SHUT_RDWR);
    close(fd_);
#endif
    fd_ = kNetTypeInval;
  }
}

bool
Socket::Bind(const char* ip, unsigned short port)
{
  if (kNetTypeInval == fd_)
    return false;

  struct sockaddr_in host_addr;
  host_addr.sin_addr.s_addr =
    (NULL == ip ? htonl(INADDR_ANY) : inet_addr(ip));
  host_addr.sin_family      = AF_INET;
  host_addr.sin_port        = htons(port);

  if (kNetTypeError == bind(fd_,
        (struct sockaddr*)&host_addr, sizeof(host_addr)))
    return false;

  return true;
}

bool
Socket::Listen(void)
{
  if (kNetTypeInval == fd_)
    return false;

  if (kNetTypeError == listen(fd_, SOMAXCONN))
    return false;

  return true;
}

bool
Socket::Accept(Socket* s, Address* addr)
{
  if (kNetTypeInval == fd_ || NULL == s)
    return false;

  struct sockaddr_in remote_addr;
  socklen_t addrlen = sizeof(remote_addr);
  int fd = accept(fd_, (struct sockaddr*)&remote_addr, &addrlen);
  if (kNetTypeInval == fd)
    return false;

  s->Attach(fd);
  if (NULL != addr)
    addr->Attach(&remote_addr);

  return true;
}

bool
Socket::Connect(const char* ip, unsigned short port)
{
  if (kNetTypeInval == fd_)
    return false;

  if (NULL == ip)
    ip = "127.0.0.1";
  struct sockaddr_in remote_addr;
  remote_addr.sin_addr.s_addr = inet_addr(ip);
  remote_addr.sin_family      = AF_INET;
  remote_addr.sin_port        = htons(port);
  if (kNetTypeError == connect(fd_,
        (struct sockaddr*)&remote_addr, sizeof(remote_addr)))
    return false;

  return true;
}

int
Socket::ReadBlock(int bytes, char* buffer)
{
  if (kNetTypeInval == fd_ || bytes <= 0 || NULL == buffer)
    return kNetTypeError;

  int ret = recv(fd_, buffer, bytes, 0);

  return ret;
}

int
Socket::WriteBlock(const char* buffer, int bytes)
{
  if (kNetTypeInval == fd_ || NULL == buffer || bytes <= 0)
    return kNetTypeError;

  int write_bytes = 0;
  int ret;
  while (write_bytes < bytes) {
    ret = send(fd_, buffer + write_bytes, bytes - write_bytes, 0);
    if (kNetTypeError == ret)
      return ret;

    write_bytes += ret;
  }

  return write_bytes;
}

int
Socket::Read(int bytes, char* buffer)
{
  if (kNetTypeInval == fd_ || bytes <= 0 || NULL == buffer)
    return kNetTypeError;

  return rbuf_.Get(bytes, buffer);
}

int
Socket::Write(const char* buffer, int bytes)
{
  if (kNetTypeInval == fd_ || NULL == buffer || bytes <= 0)
    return kNetTypeError;

  return wbuf_.Put(buffer, bytes);
}

int
Socket::DealWithAsyncRead(void)
{
  if (kNetTypeInval == fd_)
    return kNetTypeError;

  int read_bytes = 0;
  int ret;
  char* free_buffer = rbuf_.free_buffer();
  int   free_length = rbuf_.free_length();
  while (true) {
    if (0 == free_length) {
      rbuf_.Regrow();
      free_buffer = rbuf_.free_buffer();
      free_length = rbuf_.free_length();
    }

    ret = recv(fd_, free_buffer, free_length, 0);
    if (ret > 0) {
      rbuf_.Increment(ret);
      read_bytes += ret;
      if (ret < free_length)
        break;
    }
    else if (0 == ret) {
      if (read_bytes > 0)
        break;
      else
        return ret;
    }
    else {
      return ret;
    }
  }

  return read_bytes;
}

int
Socket::DealWithAsyncWrite(void)
{
  if (kNetTypeInval == fd_)
    return kNetTypeError;

  int length = wbuf_.length();
  if (length <= 0)
    return 0;

  const char* buffer = wbuf_.buffer();
  int ret = send(fd_, buffer, length, 0);

  if (ret > 0)
    wbuf_.Decrement(ret);

  return ret;
}

bool
Socket::CheckValidMessageInReadBuffer(void)
{
  return true;
}
<|endoftext|>


<commit_before>//
// Source: Standard Input
// Translated from Basic to C++ using btran
// on Friday, May 24, 2019 at 23:59:57
//

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <ctime>
#include "basicfun.h"

int main(int argc, char **argv)
{
	int c = 0;
	int h = 0;
	int i = 0;
	int j = 0;
	int q = 0;
	int r = 0;
	int s = 0;
	int v = 0;
	int x;
	int z = 0;

	int w[26][26] = { 0 };
	int v_V1[26][26] = { 0 };

	// ARKABLE PROGRAM BY JACK HAUBER, LOOMIS SCHOOL, WINDS OR , CT
	// ODELED FOR B AS IC-PLUS BY DAVE AHL, DIGITAL
	std::cout <<
		"THIS PROGRAM PRINTS OUT A MAZE OF DIMENSIONS UP TO 23 X 23."
		<< std::endl;
	std::cout << "RUN THE PROGRAM AND THEN TRY TO NEGOTIATE THE MAZE!" <<
		std::endl;
	std::cout << std::endl;
	srand(time(0));
	for (i = 0; i <= 25; i++)
	{
		for (j = 0; j <= 25; j++)
		{
			w[i][j] = 0;
			v_V1[i][j] = 0;
		}
	}
L_120:;
	std::cout << "YOUR WIDTH? ";
	std::cin >> h;
	if (std::cin.fail()) { std::cin.clear();
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); }
	std::cout << "AND LENGTH? ";
	std::cin >> v;
	if (std::cin.fail()) { std::cin.clear();
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); }
	std::cout << std::endl;
	if (h < 2 || h > 23 || v < 2 || v > 23)
	{
		std::cout << "MEANINGLESS DIMENSIONS, TRY AGAIN" << std::endl;
		std::cout << std::endl;
		goto L_120;
	}

	std::cout << std::endl;
	std::cout << std::endl;
	q = 0;
	z = 0;
	x = (rand() % h + 1);
	for (i = 1; i <= h; i++)
	{
		if (i == x)
		{
			std::cout << ":  ";
		}
		else
		{
			std::cout << ":--";
		}
	}
	std::cout << ":" << std::endl;
	c = 1;
	w[x][1] = c;
	c = c + 1;
	r = x;
	s = 1;
	goto L_260;
L_210:;
	if (r != h)
	{
		r = r + 1;
	}
	else if (s != v)
	{
		r = 1;
		s = s + 1;
	}
	else
	{
		r = 1;
		s = 1;
	}
L_250:;
	if (w[r][s] == 0)
	{
		goto L_210;
	}
L_260:;
	if (r - 1 == 0)
	{
		goto L_530;
	}
	if (w[r - 1][s] != 0)
	{
		goto L_530;
	}
	if (s - 1 == 0)
	{
		goto L_390;
	}
	if (w[r][s - 1] != 0)
	{
		goto L_390;
	}
	if ((r != h) && (w[r + 1][s] == 0))
	{
		switch (rand() % 3)
		{
		case 0:
			goto L_790;
		case 1:
			goto L_820;
		case 2:
			goto L_860;
		}
	}

	if (s != v)
	{
		if (w[r][s + 1] != 0)
		{
			goto L_370;
		}
	}
	else if (z == 1)
	{
		goto L_370;
	}
	else
	{
		q = 1;
	}

	switch(rand() % 3)
	{
	case 0:
		goto L_790;
	case 1:
		goto L_820;
	case 2:
		goto L_910;
	}
L_370:;
	switch(rand() % 2)
	{
	case 0:
		goto L_790;
	case 1:
		goto L_820;
	}
L_390:;
	if (r == h)
	{
		goto L_470;
	}
	if (w[r + 1][s] != 0)
	{
		goto L_470;
	}
	if (s != v)
	{
		if (w[r][s + 1] != 0)
		{
			goto L_450;
		}
	}
	else
	{
		if (z == 1)
		{
			goto L_450;
		}
		q = 1;
	}

	switch(rand() % 3)
	{
	case 0:
		goto L_790;
	case 1:
		goto L_860;
	case 2:
		goto L_910;
	}
L_450:;
	switch(rand() % 2)
	{
	case 0:
		goto L_790;
	case 1:
		goto L_860;
	}
L_470:;
	if (s != v)
	{
		goto L_490;
	}
	if (z == 1)
	{
		goto L_790;
	}
	q = 1;
	goto L_500;
L_490:;
	if (w[r][s + 1] != 0)
	{
		goto L_790;
	}
L_500:;
	switch(rand() % 2)
	{
	case 0:
		goto L_790;
	case 1:
		goto L_910;
	}
L_530:;
	if (s - 1 == 0)
	{
		goto L_670;
	}
	if (w[r][s - 1] != 0)
	{
		goto L_670;
	}
	if (r == h)
	{
		goto L_610;
	}
	if (w[r + 1][s] != 0)
	{
		goto L_610;
	}
	if (s != v)
	{
		goto L_560;
	}
	if (z == 1)
	{
		goto L_590;
	}
	q = 1;
	goto L_570;
L_560:;
	if (w[r][s + 1] != 0)
	{
		goto L_590;
	}
L_570:;
	switch(rand() % 3)
	{
	case 0:
		goto L_820;
	case 1:
		goto L_860;
	case 2:
		goto L_910;
	}
L_590:;
	switch(rand() % 2)
	{
	case 0:
		goto L_820;
	case 1:
		goto L_860;
	}
L_610:;
	if (s != v)
	{
		if (w[r][s + 1] != 0)
		{
			goto L_820;
		}
	}
	else if (z == 1)
	{
		goto L_820;
	}
	else
	{
		q = 1;
	}

	switch(rand() % 2)
	{
	case 0:
		goto L_820;
	case 1:
		goto L_910;
	}
L_670:;
	if (r == h)
	{
		goto L_740;
	}
	if (w[r + 1][s] != 0)
	{
		goto L_740;
	}
	if (s != v)
	{
		goto L_700;
	}
	if (z == 1)
	{
		goto L_860;
	}
	q = 1;
	goto L_830;
L_700:;
	if (w[r][s + 1] != 0)
	{
		goto L_860;
	}
	switch(rand() % 2)
	{
	case 0:
		goto L_860;
	case 1:
		goto L_910;
	}
L_740:;
	if (s != v)
	{
		goto L_760;
	}
	if (z == 1)
	{
		goto L_210;
	}
	q = 1;
	goto L_910;
L_760:;
	if (w[r][s + 1] != 0)
	{
		goto L_210;
	}
	goto L_910;
L_790:;
	w[r - 1][s] = c;
	c = c + 1;
	v_V1[r - 1][s] = 2;
	r = r - 1;
	if (c == h * v + 1)
	{
		goto L_1010;
	}
	q = 0;
	goto L_260;
L_820:;
	w[r][s - 1] = c;
L_830:;
	c = c + 1;
	v_V1[r][s - 1] = 1;
	s = s - 1;
	if (c == h * v + 1)
	{
		goto L_1010;
	}
	q = 0;
	goto L_260;
L_860:;
	w[r + 1][s] = c;
	c = c + 1;
	if (v_V1[r][s] == 0)
	{
		v_V1[r][s] = 2;
	}
	else
	{
		v_V1[r][s] = 3;
	}

	r = r + 1;
	if (c == h * v + 1)
	{
		goto L_1010;
	}
	goto L_530;
L_910:;
	if (q == 1)
	{
		z = 1;
		if (v_V1[r][s] == 0)
		{
			v_V1[r][s] = 1;
			q = 0;
			r = 1;
			s = 1;
			goto L_250;
		}
		else
		{
			v_V1[r][s] = 3;
			q = 0;
			goto L_210;
		}
	}
	w[r][s + 1] = c;
	c = c + 1;
	if (v_V1[r][s] == 0)
	{
		v_V1[r][s] = 1;
	}
	else
	{
		v_V1[r][s] = 3;
	}
	s = s + 1;
	if (c == h * v + 1)
	{
		goto L_1010;
	}
	goto L_260;
L_1010:;
	for (j = 1; j <= v; j++)
	{
		std::cout << "I";
		for (i = 1; i <= h; i++)
		{
			if (v_V1[i][j] < 2)
			{
				std::cout << "  I";
			}
			else
			{
				std::cout << "   ";
			}
		}
		std::cout << std::endl;
		for (i = 1; i <= h; i++)
		{
			if (v_V1[i][j] == 0)
			{
				std::cout << ":--";
			}
			else if (v_V1[i][j] == 2)
			{
				std::cout << ":--";
			}
			else
			{
				std::cout << ":  ";
			}
		}
		std::cout << ":" << std::endl;
	}

	return EXIT_SUCCESS;
}
<commit_msg>Lose unnecessary code<commit_after>//
// Source: Standard Input
// Translated from Basic to C++ using btran
// on Friday, May 24, 2019 at 23:59:57
//

#include <iostream>
#include <cstdlib>
#include <ctime>
#include "basicfun.h"

int main(int argc, char **argv)
{
	int c = 0;
	int h = 0;
	int i = 0;
	int j = 0;
	int q = 0;
	int r = 0;
	int s = 0;
	int v = 0;
	int x;
	int z = 0;

	int w[26][26] = { 0 };
	int v_V1[26][26] = { 0 };

	// ARKABLE PROGRAM BY JACK HAUBER, LOOMIS SCHOOL, WINDS OR , CT
	// ODELED FOR B AS IC-PLUS BY DAVE AHL, DIGITAL
	std::cout <<
		"THIS PROGRAM PRINTS OUT A MAZE OF DIMENSIONS UP TO 23 X 23."
		<< std::endl;
	std::cout << "RUN THE PROGRAM AND THEN TRY TO NEGOTIATE THE MAZE!" <<
		std::endl;
	std::cout << std::endl;
	srand(time(0));
L_120:;
	std::cout << "YOUR WIDTH? ";
	std::cin >> h;
	if (std::cin.fail()) { std::cin.clear();
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); }
	std::cout << "AND LENGTH? ";
	std::cin >> v;
	if (std::cin.fail()) { std::cin.clear();
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); }
	std::cout << std::endl;
	if (h < 2 || h > 23 || v < 2 || v > 23)
	{
		std::cout << "MEANINGLESS DIMENSIONS, TRY AGAIN" << std::endl;
		std::cout << std::endl;
		goto L_120;
	}

	std::cout << std::endl;
	std::cout << std::endl;
	q = 0;
	z = 0;
	x = (rand() % h + 1);
	for (i = 1; i <= h; i++)
	{
		if (i == x)
		{
			std::cout << ":  ";
		}
		else
		{
			std::cout << ":--";
		}
	}
	std::cout << ":" << std::endl;
	c = 1;
	w[x][1] = c;
	c = c + 1;
	r = x;
	s = 1;
	goto L_260;
L_210:;
	if (r != h)
	{
		r = r + 1;
	}
	else if (s != v)
	{
		r = 1;
		s = s + 1;
	}
	else
	{
		r = 1;
		s = 1;
	}
L_250:;
	if (w[r][s] == 0)
	{
		goto L_210;
	}
L_260:;
	if (r - 1 == 0)
	{
		goto L_530;
	}
	if (w[r - 1][s] != 0)
	{
		goto L_530;
	}
	if (s - 1 == 0)
	{
		goto L_390;
	}
	if (w[r][s - 1] != 0)
	{
		goto L_390;
	}
	if ((r != h) && (w[r + 1][s] == 0))
	{
		switch (rand() % 3)
		{
		case 0:
			goto L_790;
		case 1:
			goto L_820;
		case 2:
			goto L_860;
		}
	}

	if (s != v)
	{
		if (w[r][s + 1] != 0)
		{
			goto L_370;
		}
	}
	else if (z == 1)
	{
		goto L_370;
	}
	else
	{
		q = 1;
	}

	switch(rand() % 3)
	{
	case 0:
		goto L_790;
	case 1:
		goto L_820;
	case 2:
		goto L_910;
	}
L_370:;
	switch(rand() % 2)
	{
	case 0:
		goto L_790;
	case 1:
		goto L_820;
	}
L_390:;
	if (r == h)
	{
		goto L_470;
	}
	if (w[r + 1][s] != 0)
	{
		goto L_470;
	}
	if (s != v)
	{
		if (w[r][s + 1] != 0)
		{
			goto L_450;
		}
	}
	else
	{
		if (z == 1)
		{
			goto L_450;
		}
		q = 1;
	}

	switch(rand() % 3)
	{
	case 0:
		goto L_790;
	case 1:
		goto L_860;
	case 2:
		goto L_910;
	}
L_450:;
	switch(rand() % 2)
	{
	case 0:
		goto L_790;
	case 1:
		goto L_860;
	}
L_470:;
	if (s != v)
	{
		goto L_490;
	}
	if (z == 1)
	{
		goto L_790;
	}
	q = 1;
	goto L_500;
L_490:;
	if (w[r][s + 1] != 0)
	{
		goto L_790;
	}
L_500:;
	switch(rand() % 2)
	{
	case 0:
		goto L_790;
	case 1:
		goto L_910;
	}
L_530:;
	if (s - 1 == 0)
	{
		goto L_670;
	}
	if (w[r][s - 1] != 0)
	{
		goto L_670;
	}
	if (r == h)
	{
		goto L_610;
	}
	if (w[r + 1][s] != 0)
	{
		goto L_610;
	}
	if (s != v)
	{
		goto L_560;
	}
	if (z == 1)
	{
		goto L_590;
	}
	q = 1;
	goto L_570;
L_560:;
	if (w[r][s + 1] != 0)
	{
		goto L_590;
	}
L_570:;
	switch(rand() % 3)
	{
	case 0:
		goto L_820;
	case 1:
		goto L_860;
	case 2:
		goto L_910;
	}
L_590:;
	switch(rand() % 2)
	{
	case 0:
		goto L_820;
	case 1:
		goto L_860;
	}
L_610:;
	if (s != v)
	{
		if (w[r][s + 1] != 0)
		{
			goto L_820;
		}
	}
	else if (z == 1)
	{
		goto L_820;
	}
	else
	{
		q = 1;
	}

	switch(rand() % 2)
	{
	case 0:
		goto L_820;
	case 1:
		goto L_910;
	}
L_670:;
	if (r == h)
	{
		goto L_740;
	}
	if (w[r + 1][s] != 0)
	{
		goto L_740;
	}
	if (s != v)
	{
		goto L_700;
	}
	if (z == 1)
	{
		goto L_860;
	}
	q = 1;
	goto L_830;
L_700:;
	if (w[r][s + 1] != 0)
	{
		goto L_860;
	}
	switch(rand() % 2)
	{
	case 0:
		goto L_860;
	case 1:
		goto L_910;
	}
L_740:;
	if (s != v)
	{
		goto L_760;
	}
	if (z == 1)
	{
		goto L_210;
	}
	q = 1;
	goto L_910;
L_760:;
	if (w[r][s + 1] != 0)
	{
		goto L_210;
	}
	goto L_910;
L_790:;
	w[r - 1][s] = c;
	c = c + 1;
	v_V1[r - 1][s] = 2;
	r = r - 1;
	if (c == h * v + 1)
	{
		goto L_1010;
	}
	q = 0;
	goto L_260;
L_820:;
	w[r][s - 1] = c;
L_830:;
	c = c + 1;
	v_V1[r][s - 1] = 1;
	s = s - 1;
	if (c == h * v + 1)
	{
		goto L_1010;
	}
	q = 0;
	goto L_260;
L_860:;
	w[r + 1][s] = c;
	c = c + 1;
	if (v_V1[r][s] == 0)
	{
		v_V1[r][s] = 2;
	}
	else
	{
		v_V1[r][s] = 3;
	}

	r = r + 1;
	if (c == h * v + 1)
	{
		goto L_1010;
	}
	goto L_530;
L_910:;
	if (q == 1)
	{
		z = 1;
		if (v_V1[r][s] == 0)
		{
			v_V1[r][s] = 1;
			q = 0;
			r = 1;
			s = 1;
			goto L_250;
		}
		else
		{
			v_V1[r][s] = 3;
			q = 0;
			goto L_210;
		}
	}
	w[r][s + 1] = c;
	c = c + 1;
	if (v_V1[r][s] == 0)
	{
		v_V1[r][s] = 1;
	}
	else
	{
		v_V1[r][s] = 3;
	}
	s = s + 1;
	if (c == h * v + 1)
	{
		goto L_1010;
	}
	goto L_260;
L_1010:;
	for (j = 1; j <= v; j++)
	{
		std::cout << "I";
		for (i = 1; i <= h; i++)
		{
			if (v_V1[i][j] < 2)
			{
				std::cout << "  I";
			}
			else
			{
				std::cout << "   ";
			}
		}
		std::cout << std::endl;
		for (i = 1; i <= h; i++)
		{
			if (v_V1[i][j] == 0)
			{
				std::cout << ":--";
			}
			else if (v_V1[i][j] == 2)
			{
				std::cout << ":--";
			}
			else
			{
				std::cout << ":  ";
			}
		}
		std::cout << ":" << std::endl;
	}

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "flutter/lib/ui/painting/vertices.h"

#include "lib/tonic/dart_binding_macros.h"
#include "lib/tonic/dart_library_natives.h"

namespace blink {

namespace {

void DecodePoints(const tonic::Float32List& coords, SkPoint* points) {
  for (int i = 0; i < coords.num_elements(); i += 2)
    points[i / 2] = SkPoint::Make(coords[i], coords[i + 1]);
}

template <typename T>
void DecodeInts(const tonic::Int32List& ints, T* out) {
  for (int i = 0; i < ints.num_elements(); i++)
    out[i] = ints[i];
}

}  // namespace

static void Vertices_constructor(Dart_NativeArguments args) {
  DartCallConstructor(&Vertices::Create, args);
}

IMPLEMENT_WRAPPERTYPEINFO(ui, Vertices);

#define FOR_EACH_BINDING(V) V(Vertices, init)

FOR_EACH_BINDING(DART_NATIVE_CALLBACK)

Vertices::Vertices() {}

Vertices::~Vertices() {}

void Vertices::RegisterNatives(tonic::DartLibraryNatives* natives) {
  natives->Register({{"Vertices_constructor", Vertices_constructor, 1, true},
                     FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}

fxl::RefPtr<Vertices> Vertices::Create() {
  return fxl::MakeRefCounted<Vertices>();
}

void Vertices::init(SkVertices::VertexMode vertex_mode,
                    const tonic::Float32List& positions,
                    const tonic::Float32List& texture_coordinates,
                    const tonic::Int32List& colors,
                    const tonic::Int32List& indices) {
  uint32_t builderFlags = 0;
  if (texture_coordinates.data())
    builderFlags |= SkVertices::kHasTexCoords_BuilderFlag;
  if (colors.data())
    builderFlags |= SkVertices::kHasColors_BuilderFlag;

  SkVertices::Builder builder(vertex_mode, positions.num_elements() / 2,
                              indices.num_elements(), builderFlags);
  if (positions.data())
    DecodePoints(positions, builder.positions());
  if (texture_coordinates.data())
    DecodePoints(texture_coordinates, builder.texCoords());
  if (colors.data())
    DecodeInts<SkColor>(colors, builder.colors());
  if (indices.data())
    DecodeInts<uint16_t>(indices, builder.indices());

  vertices_ = builder.detach();
}

}  // namespace blink
<commit_msg>Add debug asserts to using SkVertices::Builder (#5292)<commit_after>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "flutter/lib/ui/painting/vertices.h"

#include "lib/tonic/dart_binding_macros.h"
#include "lib/tonic/dart_library_natives.h"

namespace blink {

namespace {

void DecodePoints(const tonic::Float32List& coords, SkPoint* points) {
  for (int i = 0; i < coords.num_elements(); i += 2)
    points[i / 2] = SkPoint::Make(coords[i], coords[i + 1]);
}

template <typename T>
void DecodeInts(const tonic::Int32List& ints, T* out) {
  for (int i = 0; i < ints.num_elements(); i++)
    out[i] = ints[i];
}

}  // namespace

static void Vertices_constructor(Dart_NativeArguments args) {
  DartCallConstructor(&Vertices::Create, args);
}

IMPLEMENT_WRAPPERTYPEINFO(ui, Vertices);

#define FOR_EACH_BINDING(V) V(Vertices, init)

FOR_EACH_BINDING(DART_NATIVE_CALLBACK)

Vertices::Vertices() {}

Vertices::~Vertices() {}

void Vertices::RegisterNatives(tonic::DartLibraryNatives* natives) {
  natives->Register({{"Vertices_constructor", Vertices_constructor, 1, true},
                     FOR_EACH_BINDING(DART_REGISTER_NATIVE)});
}

fxl::RefPtr<Vertices> Vertices::Create() {
  return fxl::MakeRefCounted<Vertices>();
}

void Vertices::init(SkVertices::VertexMode vertex_mode,
                    const tonic::Float32List& positions,
                    const tonic::Float32List& texture_coordinates,
                    const tonic::Int32List& colors,
                    const tonic::Int32List& indices) {
  uint32_t builderFlags = 0;
  if (texture_coordinates.data())
    builderFlags |= SkVertices::kHasTexCoords_BuilderFlag;
  if (colors.data())
    builderFlags |= SkVertices::kHasColors_BuilderFlag;

  SkVertices::Builder builder(vertex_mode, positions.num_elements() / 2,
                              indices.num_elements(), builderFlags);

  // positions are required for SkVertices::Builder
  FXL_DCHECK(positions.data());
  if (positions.data())
    DecodePoints(positions, builder.positions());

  if (texture_coordinates.data()) {
    // SkVertices::Builder assumes equal numbers of elements
    FXL_DCHECK(positions.num_elements() == texture_coordinates.num_elements());
    DecodePoints(texture_coordinates, builder.texCoords());
  }
  if (colors.data()) {
    // SkVertices::Builder assumes equal numbers of elements
    FXL_DCHECK(positions.num_elements() == colors.num_elements());
    DecodeInts<SkColor>(colors, builder.colors());
  }

  if (indices.data())
    DecodeInts<uint16_t>(indices, builder.indices());

  vertices_ = builder.detach();
}

}  // namespace blink
<|endoftext|>


<commit_before>/// Functional stuff.
///
/// @file

#pragma once
#ifndef FUNCTIONAL_HPP__KG9RFBRT
#define FUNCTIONAL_HPP__KG9RFBRT

#include <utility>

//==========================================================================
namespace backnocles {
//==========================================================================

/// Inherit from given callables to provide an aggregated operator().
template<class... Funcs>
struct overload : Funcs...
{
  constexpr overload(Funcs&&... fs)
    : Funcs{std::forward<Funcs>(fs)}...
  {}
};

/// Overload maker.
template<class... Funcs>
auto make_overload(Funcs... fs)
{
  return overload<Funcs...>{std::forward<Funcs>(fs)...};
}

//==========================================================================
} // namespace

#endif /* include guard */
<commit_msg>fix make_overload() reference<commit_after>/// Functional stuff.
///
/// @file

#pragma once
#ifndef FUNCTIONAL_HPP__KG9RFBRT
#define FUNCTIONAL_HPP__KG9RFBRT

#include <utility>

//==========================================================================
namespace backnocles {
//==========================================================================

/// Inherit from given callables to provide an aggregated operator().
template<class... Funcs>
struct overload : Funcs...
{
  constexpr overload(Funcs&&... fs)
    : Funcs{std::forward<Funcs>(fs)}...
  {}
};

/// Overload maker.
template<class... Funcs>
auto make_overload(Funcs&&... fs)
{
  return overload<Funcs...>{std::forward<Funcs>(fs)...};
}

//==========================================================================
} // namespace

#endif /* include guard */
<|endoftext|>


<commit_before>/*
    Copyright (c) 2006 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "messagesearchprovider.h"
#include "messagesearchproviderthread.h"

#include <libakonadi/itemfetchjob.h>
#include <libakonadi/job.h>
#include <libakonadi/monitor.h>

#include <kmetadata/kmetadata.h>

#include <QtCore/QCoreApplication>

using namespace Akonadi;

Akonadi::MessageSearchProvider::MessageSearchProvider( const QString &id ) :
  SearchProviderBase( id )
{
  Monitor* monitor = new Monitor( this );
  monitor->monitorMimeType( "message/rfc822" );
  monitor->monitorMimeType( "message/news" );
  connect( monitor, SIGNAL(itemAdded(const Akonadi::DataReference&)), SLOT(itemChanged(const Akonadi::DataReference&)) );
  connect( monitor, SIGNAL(itemChanged(const Akonadi::DataReference&)), SLOT(itemChanged(const Akonadi::DataReference&)) );
  connect( monitor, SIGNAL(itemRemoved(const Akonadi::DataReference&)), SLOT(itemRemoved(const Akonadi::DataReference&)) );

  Nepomuk::KMetaData::ResourceManager::instance()->setAutoSync( true );
}

QList< QByteArray > Akonadi::MessageSearchProvider::supportedMimeTypes() const
{
  QList<QByteArray> mimeTypes;
  mimeTypes << "message/rfc822" << "message/news";
  return mimeTypes;
}

SearchProviderThread* Akonadi::MessageSearchProvider::workerThread()
{
  return new MessageSearchProviderThread( this );
}

void MessageSearchProvider::itemChanged(const Akonadi::DataReference & ref)
{
  ItemFetchJob *job = new ItemFetchJob( ref, this );
  connect( job, SIGNAL(done(Akonadi::Job*)), SLOT(itemReceived(Akonadi::Job*)) );
  job->start();
}

void MessageSearchProvider::itemRemoved(const Akonadi::DataReference & ref)
{
  Nepomuk::KMetaData::Resource r( QLatin1String("akonadi://") + QString::number( ref.persistanceID() ) );
  r.remove();
}

void MessageSearchProvider::itemReceived(Akonadi::Job * job)
{
  if ( job->error() || static_cast<ItemFetchJob*>( job )->items().count() == 0 ) {
    // TODO: erro handling
    qDebug() << "Job error:" << job->errorMessage();
  } else {
    Item *item = static_cast<ItemFetchJob*>( job )->items().first();
    Q_ASSERT( item );
    Nepomuk::KMetaData::Resource r( QLatin1String("akonadi://") + QString::number( item->reference().persistanceID() ) );
    // TODO
    r.setProperty( "Subject", "Test" );
  }
  job->deleteLater();
}

int main( int argc, char **argv )
{
  QCoreApplication app( argc, argv );
  Akonadi::SearchProviderBase::init<Akonadi::MessageSearchProvider>( argc, argv, QLatin1String("akonadi_message_searchprovider") );
  return app.exec();
}

#include "messagesearchprovider.moc"
<commit_msg>use the real data<commit_after>/*
    Copyright (c) 2006 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "messagesearchprovider.h"
#include "messagesearchproviderthread.h"

#include <libakonadi/messagefetchjob.h>
#include <libakonadi/job.h>
#include <libakonadi/monitor.h>

#include <kmime/kmime_message.h>

#include <kmetadata/kmetadata.h>

#include <QtCore/QCoreApplication>

using namespace Akonadi;

Akonadi::MessageSearchProvider::MessageSearchProvider( const QString &id ) :
  SearchProviderBase( id )
{
  Monitor* monitor = new Monitor( this );
  monitor->monitorMimeType( "message/rfc822" );
  monitor->monitorMimeType( "message/news" );
  connect( monitor, SIGNAL(itemAdded(const Akonadi::DataReference&)), SLOT(itemChanged(const Akonadi::DataReference&)) );
  connect( monitor, SIGNAL(itemChanged(const Akonadi::DataReference&)), SLOT(itemChanged(const Akonadi::DataReference&)) );
  connect( monitor, SIGNAL(itemRemoved(const Akonadi::DataReference&)), SLOT(itemRemoved(const Akonadi::DataReference&)) );

  Nepomuk::KMetaData::ResourceManager::instance()->setAutoSync( true );
}

QList< QByteArray > Akonadi::MessageSearchProvider::supportedMimeTypes() const
{
  QList<QByteArray> mimeTypes;
  mimeTypes << "message/rfc822" << "message/news";
  return mimeTypes;
}

SearchProviderThread* Akonadi::MessageSearchProvider::workerThread()
{
  return new MessageSearchProviderThread( this );
}

void MessageSearchProvider::itemChanged(const Akonadi::DataReference & ref)
{
  MessageFetchJob *job = new MessageFetchJob( ref, this );
  connect( job, SIGNAL(done(Akonadi::Job*)), SLOT(itemReceived(Akonadi::Job*)) );
  job->start();
}

void MessageSearchProvider::itemRemoved(const Akonadi::DataReference & ref)
{
  Nepomuk::KMetaData::Resource r( QLatin1String("akonadi://") + QString::number( ref.persistanceID() ) );
  r.remove();
}

void MessageSearchProvider::itemReceived(Akonadi::Job * job)
{
  if ( job->error() || static_cast<MessageFetchJob*>( job )->items().count() == 0 ) {
    // TODO: erro handling
    qDebug() << "Job error:" << job->errorMessage();
  } else {
    Message *msg = static_cast<MessageFetchJob*>( job )->messages().first();
    Q_ASSERT( msg && msg->mime() );
    Nepomuk::KMetaData::EMail r( QLatin1String("akonadi://") + QString::number( msg->reference().persistanceID() ) );
    if ( msg->mime()->subject( false ) )
      r.setProperty( "Subject", msg->mime()->subject()->asUnicodeString() );
    if ( msg->mime()->date( false ) )
      r.setProperty( "Date", msg->mime()->date()->dateTime().dateTime() );
    if ( msg->mime()->from( false ) )
      r.setProperty( "From", msg->mime()->from()->prettyAddresses() );
    if ( msg->mime()->to( false ) )
      r.setProperty( "To", msg->mime()->to()->prettyAddresses() );
    if ( msg->mime()->cc( false ) )
      r.setProperty( "Cc", msg->mime()->cc()->prettyAddresses() );
    if ( msg->mime()->bcc( false ) )
      r.setProperty( "Bcc", msg->mime()->bcc()->prettyAddresses() );
    if ( msg->mime()->messageID( false ) )
      r.setProperty( "Message-Id", msg->mime()->messageID()->asUnicodeString() );
  }
  job->deleteLater();
}

int main( int argc, char **argv )
{
  QCoreApplication app( argc, argv );
  Akonadi::SearchProviderBase::init<Akonadi::MessageSearchProvider>( argc, argv, QLatin1String("akonadi_message_searchprovider") );
  return app.exec();
}

#include "messagesearchprovider.moc"
<|endoftext|>


<commit_before>#include "dominator_tree.h"

#define likely(x)      __builtin_expect(!!(x), 1)
#define unlikely(x)    __builtin_expect(!!(x), 0)

namespace harb {

DominatorTree::DominatorTree(RubyHeapObj *root, int32_t num_nodes)
  : root(root), num_nodes(num_nodes + 1), count(0) {
  arr = new int32_t[num_nodes];
  rev = new int32_t[num_nodes];
  label = new int32_t[num_nodes];
  sdom = new int32_t[num_nodes];
  dom = new int32_t[num_nodes];
  parent = new int32_t[num_nodes];
  dsu = new int32_t[num_nodes];
  objs = new RubyHeapObj*[num_nodes];

  reverse_graph = new std::vector<int32_t>*[num_nodes];
  bucket = new std::vector<int32_t>*[num_nodes];
  tree = new std::vector<int32_t>*[num_nodes];

  for (int32_t i = 0; i < this->num_nodes; ++i) {
    reverse_graph[i] = new std::vector<int32_t>();
    bucket[i] = new std::vector<int32_t>();
    tree[i] = new std::vector<int32_t>();
  }

  progress = new harb::Progress("generating dominator tree", num_nodes * 3);
}

DominatorTree::~DominatorTree() {
  delete objs;

  for (int32_t i = 0; i < this->num_nodes; ++i) {
    delete tree[i];
  }

  delete tree;
}

void DominatorTree::dfs_child(RubyHeapObj *obj, RubyHeapObj *child) {
  int32_t u = obj->get_index();
  int32_t w = child->get_index();

  if (!arr[w]) {
    dfs(child);
    parent[arr[w]] = arr[u];
  }

  reverse_graph[arr[w]]->push_back(arr[u]);
}

void DominatorTree::dfs(RubyHeapObj *obj) {
  count++;
  arr[obj->get_index()] = count;
  rev[count] = obj->get_index();
  label[count] = count;
  sdom[count] = count;
  dsu[count] = count;
  objs[obj->get_index()] = obj;

  progress->increment();

  if (unlikely(obj == root)) {
    for(auto it = obj->get_root_children()->cbegin(); it != obj->get_root_children()->cend(); it++) {
      dfs_child(obj, *it);
    }
  } else if(obj->has_refs_to()) {
    for (uint32_t i = 0; obj->get_refs_to(i) != NULL; ++i) {
      dfs_child(obj, obj->get_refs_to(i));
    }
  }
}

int32_t DominatorTree::find(int32_t u, int32_t x) {
  if (u == dsu[u]) {
    return x ? -1 : u;
  }

  int32_t v = find(dsu[u], x + 1);
  if (v < 0) {
    return u;
  }

  if (sdom[label[dsu[u]]] < sdom[label[u]]) {
    label[u] = label[dsu[u]];
  }

  dsu[u] = v;
  return x ? v : label[u];
}

void DominatorTree::_union(int32_t u, int32_t v) {
  dsu[v] = u;
}

void DominatorTree::calculate_sdom() {
  for (int32_t i = count; i >= 1; i--) {
    for (uint32_t j = 0; j < reverse_graph[i]->size(); j++) {
      sdom[i] = std::min(sdom[i], sdom[find((*reverse_graph[i])[j])]);
    }

    if (i > 1) {
      bucket[sdom[i]]->push_back(i);
    }

    for (uint32_t j = 0; j < bucket[i]->size(); j++) {
      int32_t w = (*bucket[i])[j];
      int32_t v = find(w);

      if (sdom[v] == sdom[w]) {
        dom[w] = sdom[w];
      } else {
        dom[w] = v;
      }
    }

    if (i > 1) {
      _union(parent[i], i);
    }

    progress->increment();
  }
}

void DominatorTree::cleanup_intermediate_state() {
  delete arr;
  delete rev;
  delete label;
  delete sdom;
  delete parent;
  delete dsu;

  for (int32_t i = 0; i < this->num_nodes; ++i) {
    delete reverse_graph[i];
    delete bucket[i];
  }
  delete reverse_graph;
  delete bucket;

  delete progress;
}

void DominatorTree::calculate() {
  progress->start();

  dfs(root);

  progress->update(num_nodes);

  calculate_sdom();

  progress->update(num_nodes * 2);

  for (int32_t i = 2; i <= count; i++) {
    if (dom[i] != sdom[i]) {
      dom[i] = dom[dom[i]];
    }

    tree[rev[i]]->push_back(rev[dom[i]]);
    tree[rev[dom[i]]]->push_back(rev[i]);
    progress->increment();
  }

  cleanup_intermediate_state();

  progress->complete();
}

void DominatorTree::retained_size(RubyHeapObj *obj, size_t &size) {
  size += obj->is_root_object() ? 0 : obj->get_memsize();

  if (obj != root) {
    auto t = tree[obj->get_index()];
    if (t->size() == 1) {
      return;
    } else {
      for (size_t i = 1; i < t->size(); i++) {
        RubyHeapObj *obj = objs[(*t)[i]];
        retained_size(obj, size);
      }
    }
  }
}

}
<commit_msg>Small dominator tree fixes<commit_after>#include "dominator_tree.h"

#define likely(x)      __builtin_expect(!!(x), 1)
#define unlikely(x)    __builtin_expect(!!(x), 0)

namespace harb {

DominatorTree::DominatorTree(RubyHeapObj *root, int32_t num_nodes)
  : root(root), num_nodes(num_nodes + 1), count(0) {
  progress = new harb::Progress("generating dominator tree", num_nodes * 3);
  progress->start();

  arr = new int32_t[num_nodes];
  rev = new int32_t[num_nodes];
  label = new int32_t[num_nodes];
  sdom = new int32_t[num_nodes];
  dom = new int32_t[num_nodes];
  parent = new int32_t[num_nodes];
  dsu = new int32_t[num_nodes];
  objs = new RubyHeapObj*[num_nodes];

  reverse_graph = new std::vector<int32_t>*[num_nodes];
  bucket = new std::vector<int32_t>*[num_nodes];
  tree = new std::vector<int32_t>*[num_nodes];

  for (int32_t i = 0; i < this->num_nodes; ++i) {
    reverse_graph[i] = new std::vector<int32_t>();
    bucket[i] = new std::vector<int32_t>();
    tree[i] = new std::vector<int32_t>();
  }
}

DominatorTree::~DominatorTree() {
  delete[] objs;

  for (int32_t i = 0; i < this->num_nodes; ++i) {
    delete tree[i];
  }

  delete[] tree;

  delete progress;
}

void DominatorTree::dfs_child(RubyHeapObj *obj, RubyHeapObj *child) {
  int32_t u = obj->get_index();
  int32_t w = child->get_index();

  if (!arr[w]) {
    dfs(child);
    parent[arr[w]] = arr[u];
  }

  reverse_graph[arr[w]]->push_back(arr[u]);
}

void DominatorTree::dfs(RubyHeapObj *obj) {
  count++;
  arr[obj->get_index()] = count;
  rev[count] = obj->get_index();
  label[count] = count;
  sdom[count] = count;
  dsu[count] = count;
  objs[obj->get_index()] = obj;

  progress->increment();

  if (unlikely(obj == root)) {
    for(auto it = obj->get_root_children()->cbegin(); it != obj->get_root_children()->cend(); it++) {
      dfs_child(obj, *it);
    }
  } else if(obj->has_refs_to()) {
    for (uint32_t i = 0; obj->get_refs_to(i) != NULL; ++i) {
      dfs_child(obj, obj->get_refs_to(i));
    }
  }
}

int32_t DominatorTree::find(int32_t u, int32_t x) {
  if (u == dsu[u]) {
    return x ? -1 : u;
  }

  int32_t v = find(dsu[u], x + 1);
  if (v < 0) {
    return u;
  }

  if (sdom[label[dsu[u]]] < sdom[label[u]]) {
    label[u] = label[dsu[u]];
  }

  dsu[u] = v;
  return x ? v : label[u];
}

void DominatorTree::_union(int32_t u, int32_t v) {
  dsu[v] = u;
}

void DominatorTree::calculate_sdom() {
  for (int32_t i = count; i >= 1; i--) {
    for (uint32_t j = 0; j < reverse_graph[i]->size(); j++) {
      sdom[i] = std::min(sdom[i], sdom[find((*reverse_graph[i])[j])]);
    }

    if (i > 1) {
      bucket[sdom[i]]->push_back(i);
    }

    for (uint32_t j = 0; j < bucket[i]->size(); j++) {
      int32_t w = (*bucket[i])[j];
      int32_t v = find(w);

      if (sdom[v] == sdom[w]) {
        dom[w] = sdom[w];
      } else {
        dom[w] = v;
      }
    }

    if (i > 1) {
      _union(parent[i], i);
    }

    progress->increment();
  }
}

void DominatorTree::cleanup_intermediate_state() {
  delete[] arr;
  delete[] rev;
  delete[] label;
  delete[] sdom;
  delete[] parent;
  delete[] dsu;

  for (int32_t i = 0; i < this->num_nodes; ++i) {
    delete reverse_graph[i];
    delete bucket[i];
  }
  delete[] reverse_graph;
  delete[] bucket;
}

void DominatorTree::calculate() {
  progress->start();

  dfs(root);

  progress->update(num_nodes);

  calculate_sdom();

  progress->update(num_nodes * 2);

  for (int32_t i = 2; i <= count; i++) {
    if (dom[i] != sdom[i]) {
      dom[i] = dom[dom[i]];
    }

    tree[rev[i]]->push_back(rev[dom[i]]);
    tree[rev[dom[i]]]->push_back(rev[i]);
    progress->increment();
  }

  cleanup_intermediate_state();

  progress->complete();
}

void DominatorTree::retained_size(RubyHeapObj *obj, size_t &size) {
  size += obj->is_root_object() ? 0 : obj->get_memsize();

  if (obj != root) {
    auto t = tree[obj->get_index()];
    if (t->size() == 1) {
      return;
    } else {
      for (size_t i = 1; i < t->size(); i++) {
        RubyHeapObj *obj = objs[(*t)[i]];
        retained_size(obj, size);
      }
    }
  }
}

}
<|endoftext|>


<commit_before>#include <ncurses.h>

#include "configuration.hh"
#include "key_aliases.hh"

#include "basic_commands.hh"
#include "command_listeners.hh"
#include "mode.hh"
#include "../plugins/vick-compile/src/compile.hh"
#include "../plugins/vick-move/src/move.hh"
#include "../plugins/vick-insert-mode/src/insert_mode.hh"
#include "../plugins/vick-open-line/src/open_line.hh"
#include "../plugins/vick-join/src/join.hh"
#include "../plugins/vick-find/src/find.hh"
#include "../plugins/vick-linear-change-manager/src/linear-change-manager.hh"
#include "prefix.hh"
#include "prefix_key.hh"

namespace vick {

char QUIT_KEY = _control_g;

int TAB_SIZE = 8;

void (*PUSH_BACK_CHANGE)(contents&, std::shared_ptr<change>) =
    vick::linear_change_manager::push_back_change;

std::string DELIMINATORS = "!@#$%^&*()-_=+[]{}\\|;:'\",.<>/?`~";

bool use_colors()
{
    static const constexpr bool use_colors = true;
    return use_colors && has_colors();
}

void init_conf()
{
    init_pair(1, COLOR_WHITE, COLOR_BLUE);
}

void add_listeners()
{
    /* global_normal_map binds */ {
        global_normal_map['j'] = move::mvb;
        global_normal_map['k'] = move::mvd;
        global_normal_map['l'] = move::mvu;
        global_normal_map[';'] = move::mvf;

        global_normal_map['1'] = prefix_key_1;
        global_normal_map['2'] = prefix_key_2;
        global_normal_map['3'] = prefix_key_3;
        global_normal_map['4'] = prefix_key_4;
        global_normal_map['5'] = prefix_key_5;
        global_normal_map['6'] = prefix_key_6;
        global_normal_map['7'] = prefix_key_7;
        global_normal_map['8'] = prefix_key_8;
        global_normal_map['9'] = prefix_key_9;
        prefix_key_times_ten = '0';

        global_normal_map['^'] = move::mvsol;
        global_normal_map['0'] = move::mvsot;
        global_normal_map['$'] = move::mveol;

        global_normal_map['|'] = move::mvcol;
        global_normal_map['\\'] = move::mvline;

        global_normal_map[':'] = command_executor;

        global_normal_map['G'] = move::mveop;

        global_normal_map['w'] = move::mvfw;
        global_normal_map['W'] = move::mvfww;
        global_normal_map['e'] = move::mvfeow;
        global_normal_map['E'] = move::mvfeoww;
        global_normal_map['b'] = move::mvbw;
        global_normal_map['B'] = move::mvbww;

        global_normal_map['f'] = find::move_forward_find_i;
        global_normal_map['F'] = find::move_backward_find_i;
        global_normal_map['t'] = find::move_forward_until_match_i;
        global_normal_map['T'] = find::move_backward_until_match_i;

        global_normal_map['r'] = replace_character;

        global_normal_map['i'] = insert_mode::enter_insert_mode;
        global_normal_map['a'] = insert_mode::enter_append_mode;
        global_normal_map['R'] = insert_mode::enter_replace_mode;

        global_normal_map['o'] = open_line::open_line_below;
        global_normal_map['O'] = open_line::open_line_above;

        global_normal_map['J'] = join::join_two_lines;

        global_normal_map['u'] = linear_change_manager::undo_change;
        global_normal_map[_control_r] = linear_change_manager::redo_change;

        global_normal_map['.'] = linear_change_manager::reapply_change;
    }

    /* Example config for prefix key */ {
        prefix prefix_g("g");

        // binds inside g (``gg``)
        prefix_g.push_back('g', move::mvsop);

        // put this last as it copies by value
        global_normal_map['g'] = prefix_g;
    }
}

void add_commands(std::map<
    std::string, std::function<boost::optional<std::shared_ptr<change> >(
                     contents&, boost::optional<int>)> >& commandMap)
{
    commandMap["q"] = quit_command;
    commandMap["quit"] = quit_command;
    commandMap["keytest"] = key_test_command;
    commandMap["colortest"] = color_test_command;
}

}
<commit_msg>Remove ``_`` from being a DELIMINATOR by default<commit_after>#include <ncurses.h>

#include "configuration.hh"
#include "key_aliases.hh"

#include "basic_commands.hh"
#include "command_listeners.hh"
#include "mode.hh"
#include "../plugins/vick-compile/src/compile.hh"
#include "../plugins/vick-move/src/move.hh"
#include "../plugins/vick-insert-mode/src/insert_mode.hh"
#include "../plugins/vick-open-line/src/open_line.hh"
#include "../plugins/vick-join/src/join.hh"
#include "../plugins/vick-find/src/find.hh"
#include "../plugins/vick-linear-change-manager/src/linear-change-manager.hh"
#include "prefix.hh"
#include "prefix_key.hh"

namespace vick {

char QUIT_KEY = _control_g;

int TAB_SIZE = 8;

void (*PUSH_BACK_CHANGE)(contents&, std::shared_ptr<change>) =
    vick::linear_change_manager::push_back_change;

// I personally find _ an annoying deliminator as it doesn't split
// variables / tokens in many languages.
std::string DELIMINATORS = "!@#$%^&*()-"/*_*/"=+[]{}\\|;:'\",.<>/?`~";

bool use_colors()
{
    static const constexpr bool use_colors = true;
    return use_colors && has_colors();
}

void init_conf()
{
    init_pair(1, COLOR_WHITE, COLOR_BLUE);
}

void add_listeners()
{
    /* global_normal_map binds */ {
        global_normal_map['j'] = move::mvb;
        global_normal_map['k'] = move::mvd;
        global_normal_map['l'] = move::mvu;
        global_normal_map[';'] = move::mvf;

        global_normal_map['1'] = prefix_key_1;
        global_normal_map['2'] = prefix_key_2;
        global_normal_map['3'] = prefix_key_3;
        global_normal_map['4'] = prefix_key_4;
        global_normal_map['5'] = prefix_key_5;
        global_normal_map['6'] = prefix_key_6;
        global_normal_map['7'] = prefix_key_7;
        global_normal_map['8'] = prefix_key_8;
        global_normal_map['9'] = prefix_key_9;
        prefix_key_times_ten = '0';

        global_normal_map['^'] = move::mvsol;
        global_normal_map['0'] = move::mvsot;
        global_normal_map['$'] = move::mveol;

        global_normal_map['|'] = move::mvcol;
        global_normal_map['\\'] = move::mvline;

        global_normal_map[':'] = command_executor;

        global_normal_map['G'] = move::mveop;

        global_normal_map['w'] = move::mvfw;
        global_normal_map['W'] = move::mvfww;
        global_normal_map['e'] = move::mvfeow;
        global_normal_map['E'] = move::mvfeoww;
        global_normal_map['b'] = move::mvbw;
        global_normal_map['B'] = move::mvbww;

        global_normal_map['f'] = find::move_forward_find_i;
        global_normal_map['F'] = find::move_backward_find_i;
        global_normal_map['t'] = find::move_forward_until_match_i;
        global_normal_map['T'] = find::move_backward_until_match_i;

        global_normal_map['r'] = replace_character;

        global_normal_map['i'] = insert_mode::enter_insert_mode;
        global_normal_map['a'] = insert_mode::enter_append_mode;
        global_normal_map['R'] = insert_mode::enter_replace_mode;

        global_normal_map['o'] = open_line::open_line_below;
        global_normal_map['O'] = open_line::open_line_above;

        global_normal_map['J'] = join::join_two_lines;

        global_normal_map['u'] = linear_change_manager::undo_change;
        global_normal_map[_control_r] = linear_change_manager::redo_change;

        global_normal_map['.'] = linear_change_manager::reapply_change;
    }

    /* Example config for prefix key */ {
        prefix prefix_g("g");

        // binds inside g (``gg``)
        prefix_g.push_back('g', move::mvsop);

        // put this last as it copies by value
        global_normal_map['g'] = prefix_g;
    }
}

void add_commands(std::map<
    std::string, std::function<boost::optional<std::shared_ptr<change> >(
                     contents&, boost::optional<int>)> >& commandMap)
{
    commandMap["q"] = quit_command;
    commandMap["quit"] = quit_command;
    commandMap["keytest"] = key_test_command;
    commandMap["colortest"] = color_test_command;
}

}
<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2011, 2012, 2013, 2014
Raffaello D. Di Napoli

This file is part of Application-Building Components (henceforth referred to as ABC).

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

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

You should have received a copy of the GNU General Public License along with ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abc/testing/test_case.hxx>
#include <abc/trace.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::test::exception_polymorphism

namespace abc {

namespace test {

class exception_polymorphism :
   public testing::test_case {

   typedef environment_error    derived1_error;
   typedef io_error             derived2_error;
   typedef file_not_found_error derived3_error;

public:

   /** See testing::test_case::title().
   */
   virtual istr title() {
      return istr(SL("abc::exception - polymorphism"));
   }

   /** See testing::test_case::run().
   */
   virtual void run() {
      ABC_TRACE_FN((this));

      ABC_TESTING_ASSERT_THROWS(exception, throw_exception());
      ABC_TESTING_ASSERT_THROWS(generic_error, throw_generic_error());
      ABC_TESTING_ASSERT_THROWS(derived1_error, throw_derived1_error());
      ABC_TESTING_ASSERT_THROWS(derived1_error, throw_derived2_error());
      ABC_TESTING_ASSERT_THROWS(derived2_error, throw_derived2_error());
      ABC_TESTING_ASSERT_THROWS(derived1_error, throw_derived3_error(2351));
//    ABC_TESTING_ASSERT_THROWS(derived2_error, throw_derived3_error(2351));
      ABC_TESTING_ASSERT_THROWS(derived3_error, throw_derived3_error(2351));
   }

   void throw_exception() {
      ABC_TRACE_FN((this));

      ABC_THROW(exception, ());
   }

   void throw_generic_error() {
      ABC_TRACE_FN((this));

      ABC_THROW(generic_error, ());
   }

   void throw_derived1_error() {
      ABC_TRACE_FN((this));

      ABC_THROW(derived1_error, ());
   }

   void throw_derived2_error() {
      ABC_TRACE_FN((this));

      ABC_THROW(derived2_error, ());
   }

   void throw_derived3_error(int i) {
      ABC_TRACE_FN((this, i));

      ABC_THROW(derived3_error, ());
   }
};

} //namespace test

} //namespace abc

ABC_TESTING_REGISTER_TEST_CASE(abc::test::exception_polymorphism)

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::test::exception_from_os_hard_error

namespace abc {

namespace test {

class exception_from_os_hard_error :
   public testing::test_case {
public:

   /** See testing::test_case::title().
   */
   virtual istr title() {
      return istr(SL("abc::exception - conversion of hard OS errors into C++ exceptions"));
   }

   /** See testing::test_case::run().
   */
   virtual void run() {
      ABC_TRACE_FN((this));

      bool bCaughtCorrect;
      istr sResult;

      bCaughtCorrect = false;
      try {
         int * p(nullptr);
         *p = 1;
         sResult = SL("dereferenced nullptr, but no exception thrown");
      } catch (null_pointer_error const &) {
         sResult = SL("dereferenced nullptr and caught abc::null_pointer_error");
         bCaughtCorrect = true;
      } catch (memory_address_error const &) {
         sResult = SL("dereferenced nullptr, but caught abc::memory_address_error");
      } catch (...) {
         sResult = SL("dereferenced nullptr, but caught unknown exception");
      }
      assert_true(ABC_SOURCE_LOCATION(), bCaughtCorrect, sResult);

      bCaughtCorrect = false;
      try {
         int * p(nullptr);
         // Under POSIX, this also counts as second test for SIGSEGV, checking that the handler is
         // still in place after its first activation above.
         *++p = 1;
         sResult = SL("dereferenced invalid pointer, but no exception thrown");
      } catch (null_pointer_error const &) {
         sResult = SL("dereferenced invalid pointer, but caught abc::null_pointer_error");
      } catch (memory_address_error const &) {
         sResult = SL("dereferenced invalid pointer and caught abc::memory_address_error");
         bCaughtCorrect = true;
      } catch (...) {
         sResult = SL("dereferenced invalid pointer, but caught unknown exception");
      }
      assert_true(ABC_SOURCE_LOCATION(), bCaughtCorrect, sResult);

      // Enable alignment checking if the architecture supports it.
#ifdef __GNUC__
   #if defined(__i386__)
      __asm__(
         "pushf\n"
         "orl $0x00040000,(%esp)\n"
         "popf"
      );
      #define ABC_ALIGN_CHECK
   #elif defined(__x86_64__)
      __asm__(
         "pushf\n"
         "orl $0x0000000000040000,(%rsp)\n"
         "popf"
      );
      #define ABC_ALIGN_CHECK
   #endif
#endif

#ifdef ABC_ALIGN_CHECK
      bCaughtCorrect = false;
      try {
         // Create an int (with another one following it) and a pointer to it.
         int i[2];
         void * p(&i[0]);
         // Misalign the pointer, partly entering the second int.
         p = static_cast<int8_t *>(p) + 1;
         *static_cast<int *>(p) = 1;
         sResult = SL("unaligned memory access, but no exception thrown");
      } catch (memory_access_error const &) {
         sResult = SL("unaligned memory access and caught abc::memory_access_error");
         bCaughtCorrect = true;
      } catch (memory_address_error const &) {
         sResult = SL("unaligned memory access, but caught abc::memory_address_error");
      } catch (...) {
         sResult = SL("unaligned memory access, but caught unknown exception");
      }
      assert_true(ABC_SOURCE_LOCATION(), bCaughtCorrect, sResult);

      // Disable alignment checking back.
#ifdef __GNUC__
   #if defined(__i386__)
      __asm__(
         "pushf\n"
         "andl $0xfffbffff,(%esp)\n"
         "popf"
      );
   #elif defined(__x86_64__)
      __asm__(
         "pushf\n"
         "andl $0xfffffffffffbffff,(%rsp)\n"
         "popf"
      );
   #endif
#endif
#endif //ifdef ABC_ALIGN_CHECK

      bCaughtCorrect = false;
      try {
         // Non-obvious division by zero that can’t be detected at compile time: sResult always has
         // a NUL terminator at its end, so use that as a zero divider.
         int iQuot(1 / int(sResult[intptr_t(sResult.size())]));
         // The call to istr::format() makes use of the result of the quotient, so it shouldn’t be
         // optimized away.
         istr(SL("{}")).format(iQuot);
         sResult = SL("divided by zero, but no exception thrown");
      } catch (division_by_zero_error const &) {
         sResult = SL("divided by zero and caught abc::division_by_zero_error");
         bCaughtCorrect = true;
      } catch (arithmetic_error const &) {
         sResult = SL("divided by zero, but caught abc::arithmetic_error");
      } catch (...) {
         sResult = SL("divided by zero, but caught unknown exception");
      }
      assert_true(ABC_SOURCE_LOCATION(), bCaughtCorrect, sResult);
   }
};

} //namespace test

} //namespace abc

ABC_TESTING_REGISTER_TEST_CASE(abc::test::exception_from_os_hard_error)

////////////////////////////////////////////////////////////////////////////////////////////////////

<commit_msg>Use ABC_TESTING_ASSERT_THROWS() instead of custom testing code in abc::test::exception_from_os_hard_error<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2011, 2012, 2013, 2014
Raffaello D. Di Napoli

This file is part of Application-Building Components (henceforth referred to as ABC).

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

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

You should have received a copy of the GNU General Public License along with ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abc/testing/test_case.hxx>
#include <abc/trace.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::test::exception_polymorphism

namespace abc {

namespace test {

class exception_polymorphism :
   public testing::test_case {

   typedef environment_error    derived1_error;
   typedef io_error             derived2_error;
   typedef file_not_found_error derived3_error;

public:

   /** See testing::test_case::title().
   */
   virtual istr title() {
      return istr(SL("abc::exception - polymorphism"));
   }

   /** See testing::test_case::run().
   */
   virtual void run() {
      ABC_TRACE_FN((this));

      ABC_TESTING_ASSERT_THROWS(exception, throw_exception());
      ABC_TESTING_ASSERT_THROWS(generic_error, throw_generic_error());
      ABC_TESTING_ASSERT_THROWS(derived1_error, throw_derived1_error());
      ABC_TESTING_ASSERT_THROWS(derived1_error, throw_derived2_error());
      ABC_TESTING_ASSERT_THROWS(derived2_error, throw_derived2_error());
      ABC_TESTING_ASSERT_THROWS(derived1_error, throw_derived3_error(2351));
//    ABC_TESTING_ASSERT_THROWS(derived2_error, throw_derived3_error(2351));
      ABC_TESTING_ASSERT_THROWS(derived3_error, throw_derived3_error(2351));
   }

   void throw_exception() {
      ABC_TRACE_FN((this));

      ABC_THROW(exception, ());
   }

   void throw_generic_error() {
      ABC_TRACE_FN((this));

      ABC_THROW(generic_error, ());
   }

   void throw_derived1_error() {
      ABC_TRACE_FN((this));

      ABC_THROW(derived1_error, ());
   }

   void throw_derived2_error() {
      ABC_TRACE_FN((this));

      ABC_THROW(derived2_error, ());
   }

   void throw_derived3_error(int i) {
      ABC_TRACE_FN((this, i));

      ABC_THROW(derived3_error, ());
   }
};

} //namespace test

} //namespace abc

ABC_TESTING_REGISTER_TEST_CASE(abc::test::exception_polymorphism)

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::test::exception_from_os_hard_error

namespace abc {

namespace test {

class exception_from_os_hard_error :
   public testing::test_case {
public:

   /** See testing::test_case::title().
   */
   virtual istr title() {
      return istr(SL("abc::exception - conversion of hard OS errors into C++ exceptions"));
   }

   /** See testing::test_case::run().
   */
   virtual void run() {
      ABC_TRACE_FN((this));

      {
         int * p(nullptr);
         ABC_TESTING_ASSERT_THROWS(null_pointer_error, *p = 1);

         // Under POSIX, this also counts as second test for SIGSEGV, checking that the handler is
         // still in place after its first activation above.
         ABC_TESTING_ASSERT_THROWS(memory_address_error, *++p = 1);
      }

      // Enable alignment checking if the architecture supports it.
#ifdef ABC_ALIGN_CHECK
#ifdef __GNUC__
   #if defined(__i386__)
      __asm__(
         "pushf\n"
         "orl $0x00040000,(%esp)\n"
         "popf"
      );
      #define ABC_ALIGN_CHECK
   #elif defined(__x86_64__)
      __asm__(
         "pushf\n"
         "orl $0x0000000000040000,(%rsp)\n"
         "popf"
      );
      #define ABC_ALIGN_CHECK
   #endif
#endif

      {
         // Create an int (with another one following it) and a pointer to it.
         int i[2];
         void * p(&i[0]);
         // Misalign the pointer, partly entering the second int.
         p = static_cast<int8_t *>(p) + 1;
         ABC_TESTING_ASSERT_THROWS(memory_access_error, *static_cast<int *>(p) = 1);
      }

      // Disable alignment checking back.
#ifdef __GNUC__
   #if defined(__i386__)
      __asm__(
         "pushf\n"
         "andl $0xfffbffff,(%esp)\n"
         "popf"
      );
   #elif defined(__x86_64__)
      __asm__(
         "pushf\n"
         "andl $0xfffffffffffbffff,(%rsp)\n"
         "popf"
      );
   #endif
#endif
#endif //ifdef ABC_ALIGN_CHECK

      {
         // Non-obvious division by zero that can’t be detected at compile time: sEmpty always has
         // a NUL terminator at its end, so use that as a zero divider.
         istr sEmpty;
         int iZero(sEmpty[0]), iOne(1);
         ABC_TESTING_ASSERT_THROWS(division_by_zero_error, iOne /= iZero);
         // The call to istr::format() makes use of the quotient, so it shouldn’t be optimized away.
         istr(SL("{}")).format(iOne);
      }
   }
};

} //namespace test

} //namespace abc

ABC_TESTING_REGISTER_TEST_CASE(abc::test::exception_from_os_hard_error)

////////////////////////////////////////////////////////////////////////////////////////////////////

<|endoftext|>