Example #1
0
/*
    This function is actually somewhat wasteful since it
    allocates a large buffer for the bitmap and then writes that
    out a byte at a time. This can definintely be done better.
*/
void Bitmap::WriteFile(const std::string &filename) const
{
    std::vector<uint8_t> rawdata(filesize_);
    uint8_t *raw = &rawdata[0];

    int len = 0;
    memcpy(raw, &bf_, sizeof(bfheader_t));
    len += sizeof(bfheader_t);
    memcpy(raw + len, &bi_, sizeof(biheader_t));
    len += sizeof(biheader_t);

    for (int y = 0; y < height_; y++) {
        int c = 0;
        for (int x = 0; x < width_; x++) {
            memcpy(raw + len, &data_[y * bi_.width + x], sizeof(b24bitpixel_t));
            c += sizeof(b24bitpixel_t);
            len += sizeof(b24bitpixel_t);
        }
        if (c % 4 != 0) {
            memset(raw + len, 0xFF, 4 - (c % 4));
            len += (4 - (c % 4));
        }
    }

    // Actually write the huge buffer we made.
    std::ofstream file(filename, std::ios::out | std::ios::binary);
    for (int i = 0; i < filesize_; i++) {
        file << raw[i];
    }
    file.close();
    return;
}
int main() {
arma::mat rawdata;
rawdata.load(data.c_str());
arma::mat X;
X=rawdata(arma::span(0, numExp-1), arma::span(0, numFeat-1));
int m = numExp;
int n = numFeat;
arma::mat mu(nCl,n);
mu.randu();

//bring inital mu into correct range
for (int i=0; i<n; i++) {
  mu.col(i) = X.col(i).min() + (X.col(i).max()-X.col(i).min())*mu.col(i);
}

arma::mat cinit(nCl,1);
cinit.zeros();
arma::mat cloop;
arma::mat c(m,1);  //vector which assign each example to a cluster
int numC;
for (int k=0; k<numIter; k++) {
  //E-Step:
  c.zeros();
  for (int i=0; i<m; i++) {
    cloop = cinit;
    for (int j=0; j<nCl; j++) {
      cloop.row(j) = (X.row(i)-mu.row(j))*trans(X.row(i)-mu.row(j));
    }
    c.row(i) = cloop.index_min();
  }
  //M-Step:
  mu.zeros();
  for (int j=0; j<nCl; j++) {
    numC=0;
    for (int i=0; i<m; i++) {
      if (c(i,0)==j) {
        numC += 1;
        mu.row(j) += X.row(i);
      }
    }
    if(numC==0) {mu.row(j).zeros();} //no training examples were assigned to this cluster (maybe too many clusters?)
    mu.row(j) = mu.row(j)/numC;
  }
}

  //output data files to be used for plotting
  std::ofstream of_X("X_kMeans.out");
  std::ofstream of_c("c_kMeans.out");
  std::ofstream of_mu("mu_kMeans.out");
  for (int i=0;i<X.n_rows;i++) {
    of_X << X.row(i) << std::endl;
    of_c << c.row(i) << std::endl;
  }
  for (int i=0;i<mu.n_rows;i++) {
    of_mu << mu.row(i) << std::endl;
  }

}
Example #3
0
void StringData::append(const char* s, int len) {
  assert(!isStatic() && getCount() <= 1);

  if (len == 0) return;
  if (UNLIKELY(uint32_t(len) > MaxSize)) {
    throw InvalidArgumentException("len > 2^31-2", len);
  }
  if (UNLIKELY(size_t(m_len) + size_t(len) > MaxSize)) {
    throw FatalErrorException(0, "String length exceeded 2^31-2: %zu",
                              size_t(len) + size_t(m_len));
  }

  const uint32_t newLen = m_len + len;

  /*
   * In case we're being to asked to append our own string, we need to
   * load the old pointer value (it might change when we reserve
   * below).
   *
   * We don't allow appending with an interior pointers here, although
   * we may be asked to append less than the whole string.
   */
  auto const oldDataPtr = rawdata();
  assert(uintptr_t(s) <= uintptr_t(rawdata()) ||
         uintptr_t(s) >= uintptr_t(rawdata() + capacity()));
  assert(s != rawdata() || len <= m_len);

  auto const mslice = UNLIKELY(isShared()) ? escalate(newLen)
                                           : reserve(newLen);
  if (UNLIKELY(s == oldDataPtr)) s = mslice.ptr;

  /*
   * memcpy is safe even if it's a self append---the regions will be
   * disjoint, since s can't point past our oldDataPtr, and len is
   * smaller than the old length.
   */
  memcpy(mslice.ptr + m_len, s, len);

  setSize(newLen);
  assert(checkSane());
}
Example #4
0
HOT_FUNC
StringData::StringData(SharedVariant *shared)
  : _count(0) {
  ASSERT(shared);
  shared->incRef();
  m_hash = 0;
  m_len = shared->stringLength();
  m_cdata = shared->stringData();
  m_big.shared = shared;
  m_big.cap = m_len | IsShared;
  TAINT_OBSERVER_REGISTER_MUTATED(m_taint_data, rawdata());
}
Example #5
0
void StringData::initLiteral(const char* data, int len) {
  if (uint32_t(len) > MaxSize) {
    throw InvalidArgumentException("len>=2^30", len);
  }
  // Do not copy literals, this StringData can have a shorter lifetime than
  // the literal, and the client can count on this->data() giving back
  // the literal ptr with the longer lifetime. Sketchy!
  m_hash = 0;
  _count = 0;
  m_len = len;
  m_cdata = data;
  m_big.cap = len | IsLiteral;
  ASSERT(checkSane());
  TAINT_OBSERVER_REGISTER_MUTATED(m_taint_data, rawdata());
}
Example #6
0
void StringData::initAttachDeprecated(const char* data, int len) {
  if (uint32_t(len) > MaxSize) {
    throw InvalidArgumentException("len>=2^30", len);
  }
  // Don't copy small strings here either because the caller sometimes
  // assumes he can mess with data while this string is still alive,
  // and we want to free it eagerly. Sketchy!
  m_hash = 0;
  _count = 0;
  m_len = len;
  m_cdata = data;
  m_big.cap = len | IsMalloc;
  ASSERT(checkSane());
  TAINT_OBSERVER_REGISTER_MUTATED(m_taint_data, rawdata());
}
Example #7
0
set<string> LoadAllTokens(string& filename)
{
    ifstream rawdata(filename.c_str());
    set<string> tokens;
    istream_iterator<string> rawitr(rawdata);
    istream_iterator<string> eos;
    insert_iterator<set<string> > tkitr(tokens,tokens.begin());
    while(rawitr!=eos)
    {
        *tkitr=*rawitr;
        ++tkitr;
        ++rawitr;
    }
    return tokens;
}
Example #8
0
bool StringData::checkSane() const {
  static_assert(sizeof(Format) == 8, "enum Format is wrong size");
  static_assert(offsetof(StringData, _count) == FAST_REFCOUNT_OFFSET,
                "_count at wrong offset");
  static_assert(MaxSmallSize == sizeof(StringData) -
                        offsetof(StringData, m_small) - 1, "layout bustage");
  ASSERT(uint32_t(size()) <= MaxSize);
  ASSERT(uint32_t(capacity()) <= MaxSize);
  ASSERT(size() <= capacity());
  ASSERT(rawdata()[size()] == 0); // all strings must be null-terminated
  if (isSmall()) {
    ASSERT(m_data == m_small && m_len <= MaxSmallSize);
  } else {
    ASSERT(m_data && m_data != m_small);
  }
  return true;
}
Example #9
0
HOT_FUNC
int StringData::compare(const StringData *v2) const {
  assert(v2);

  if (v2 == this) return 0;

  int ret = numericCompare(v2);
  if (ret < -1) {
    int len1 = size();
    int len2 = v2->size();
    int len = len1 < len2 ? len1 : len2;
    ret = memcmp(rawdata(), v2->rawdata(), len);
    if (ret) return ret;
    if (len1 == len2) return 0;
    return len < len1 ? 1 : -1;
  }
  return ret;
}
Example #10
0
HOT_FUNC
int StringData::compare(const StringData *v2) const {
  ASSERT(v2);

  if (v2 == this) return 0;

  int ret = numericCompare(v2);
  if (ret < -1) {
    int len1 = size();
    int len2 = v2->size();
    int len = len1 < len2 ? len1 : len2;
    // No taint absorption on self-contained string ops like compare
    ret = memcmp(rawdata(), v2->rawdata(), len);
    if (ret) return ret;
    if (len1 == len2) return 0;
    return len < len1 ? 1 : -1;
  }
  return ret;
}
Example #11
0
bool Vehicle::read_params(string file) {

	std::ifstream stream(file);
	if(!stream) {
		return false;
	}

	std::string rawdata((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());
	nlohmann::json data = nlohmann::json::parse(rawdata);

	if(data.count("gains")) {
		params.gains.p = Point(data["gains"]["p"][0], data["gains"]["p"][1], data["gains"]["p"][2]);
		params.gains.i = Point(data["gains"]["i"][0], data["gains"]["i"][1], data["gains"]["i"][2]);
		params.gains.d = Point(data["gains"]["d"][0], data["gains"]["d"][1], data["gains"]["d"][2]);
	}

	if(data.count("hoverPoint")) {
		params.hoverPoint = data["hoverPoint"];
	}


	if(data.count("latency")) {
		params.latency = data["latency"];
	}

	if(data.count("mocapYawOffset")) {
		params.mocapYawOffset = ((double) data["mocapYawOffset"]) * (M_PI / 180.0);
	}
	else {
		params.mocapYawOffset = 0;
	}

	if(data.count("orientationMismatchCorrection")) {
		params.orientationMismatchCorrection = (bool) data["orientationMismatchCorrection"];
	}
	else {
		params.orientationMismatchCorrection = false;
	}

	return true;
}
Example #12
0
HOT_FUNC
void StringData::initAttach(const char* data, int len) {
  if (uint32_t(len) > MaxSize) {
    throw InvalidArgumentException("len>=2^30", len);
  }
  m_hash = 0;
  _count = 0;
  if (uint32_t(len) <= MaxSmallSize) {
    memcpy(m_small, data, len);
    m_len = len;
    m_data = m_small;
    m_small[len] = 0;
    m_small[MaxSmallSize] = 0;
    free((void*)data);
  } else {
    m_len = len;
    m_cdata = data;
    m_big.cap = len | IsMalloc;
  }
  ASSERT(checkSane());
  TAINT_OBSERVER_REGISTER_MUTATED(m_taint_data, rawdata());
}
Example #13
0
void StringData::append(const char *s, int len) {
  ASSERT(!isStatic()); // never mess around with static strings!
  if (len == 0) return;
  if (UNLIKELY(uint32_t(len) > MaxSize)) {
    throw InvalidArgumentException("len>=2^30", len);
  }
  if (UNLIKELY(len + m_len > MaxSize)) {
    throw FatalErrorException(0, "String length exceeded 2^30 - 1: %u",
                              len + m_len);
  }
  int newlen;
  // TODO: t1122987: in any of the cases below where we need a bigger buffer,
  // we can probably assume we're in a concat-loop and pick a good buffer
  // size to avoid O(N^2) copying cost.
  if (isShared() || isLiteral()) {
    // buffer is immutable, don't modify it.
    // We are mutating, so we don't need to repropagate our own taint
    StringSlice r = slice();
    char* newdata = string_concat(r.ptr, r.len, s, len, newlen);
    if (isShared()) m_big.shared->decRef();
    m_len = newlen;
    m_data = newdata;
    m_big.cap = newlen | IsMalloc;
    m_hash = 0;
  } else if (rawdata() == s) {
    // appending ourself to ourself, be conservative.
    // We are mutating, so we don't need to repropagate our own taint
    StringSlice r = slice();
    char *newdata = string_concat(r.ptr, r.len, s, len, newlen);
    releaseData();
    m_len = newlen;
    m_data = newdata;
    m_big.cap = newlen | IsMalloc;
    m_hash = 0;
  } else if (isSmall()) {
    // we're currently small but might not be after append.
    // We are mutating, so we don't need to repropagate our own taint
    int oldlen = m_len;
    newlen = oldlen + len;
    if (unsigned(newlen) <= MaxSmallSize) {
      // win.
      memcpy(&m_small[oldlen], s, len);
      m_small[newlen] = 0;
      m_small[MaxSmallSize] = 0;
      m_len = newlen;
      m_data = m_small;
      m_hash = 0;
    } else {
      // small->big string transition.
      char *newdata = string_concat(m_small, oldlen, s, len, newlen);
      m_len = newlen;
      m_data = newdata;
      m_big.cap = newlen | IsMalloc;
      m_hash = 0;
    }
  } else {
    // generic "big string concat" path.  realloc buffer.
    int oldlen = m_len;
    char* oldp = m_data;
    ASSERT((oldp > s && oldp - s > len) ||
           (oldp < s && s - oldp > oldlen)); // no overlapping
    newlen = oldlen + len;
    char* newdata = (char*) realloc(oldp, newlen + 1);
    memcpy(newdata + oldlen, s, len);
    newdata[newlen] = 0;
    m_len = newlen;
    m_data = newdata;
    m_big.cap = newlen | IsMalloc;
    m_hash = 0;
  }
  ASSERT(uint32_t(newlen) <= MaxSize);
  TAINT_OBSERVER_REGISTER_MUTATED(m_taint_data, rawdata());
  ASSERT(checkSane());
}
Example #14
0
int64_t StringData::toInt64(int base /* = 10 */) const {
  return strtoll(rawdata(), nullptr, base);
}
Example #15
0
bool UIDirect3D9Window::HandleRawInput(MSG *Message, long *Result)
{
    // check the raw data size
    UINT size = 0;
    GetRawInputData((HRAWINPUT)Message->lParam, RID_INPUT, NULL, &size, sizeof(RAWINPUTHEADER));

    if (size < 2)
    {
        LOG(VB_GENERAL, LOG_ERR, "Failed to get raw input data");
        return false;
    }

    // retrieve the raw data
    QByteArray buffer(size, 0);
    if (size == GetRawInputData((HRAWINPUT)Message->lParam, RID_INPUT, buffer.data(), &size, sizeof(RAWINPUTHEADER)))
    {
        RAWINPUT* rawinput = (RAWINPUT*)buffer.data();
        // HID and valid data size
        if (rawinput->header.dwType == RIM_TYPEHID && rawinput->data.hid.dwCount > 0)
        {
            // retrieve the device info to filter on usage page
            RID_DEVICE_INFO deviceinfo;
            memset(&deviceinfo, 0, sizeof(RID_DEVICE_INFO));
            uint devsize = sizeof(RID_DEVICE_INFO);
            deviceinfo.cbSize = devsize;
            if (GetRawInputDeviceInfo(rawinput->header.hDevice, RIDI_DEVICEINFO, (void*)&deviceinfo, &devsize) > 0 &&
                deviceinfo.dwType == RIM_TYPEHID)
            {
                bool mcebutton = deviceinfo.hid.usUsagePage == 0xFFBC && deviceinfo.hid.usUsage == 0x88;
                bool consumer  = deviceinfo.hid.usUsagePage == 0x000C && deviceinfo.hid.usUsage == 0x01;

                if (mcebutton || consumer)
                {
                    LOG(VB_GUI, LOG_DEBUG, QString("HID device: vendor %1 product %2 version %3 page 0x%4 usage 0x%5")
                        .arg(deviceinfo.hid.dwVendorId).arg(deviceinfo.hid.dwProductId).arg(deviceinfo.hid.dwVersionNumber)
                        .arg(deviceinfo.hid.usUsagePage, 0, 16).arg(deviceinfo.hid.usUsage, 0,16));

                    QByteArray rawdata((const char*)&rawinput->data.hid.bRawData, (int)rawinput->data.hid.dwSizeHid);
                    int button = 0;
                    // first byte contains other info
                    for (int i = 1; i < rawdata.size(); ++i)
                        button += ((quint8)rawdata[i]) << ((i -1) * 8);

                    if (button && consumer && (button != AC_PROGRAM_GUIDE && button != AC_PROPERTIES))
                    {
                        LOG(VB_GENERAL, LOG_INFO, QString("Ignoring consumer control button 0x%1")
                            .arg(button, 0, 16));
                        button = 0;
                    }

                    int key = 0;
                    QString context;
                    if (button && mcebutton)
                    {
                        context = "HID Vendor Control";

                        switch (button)
                        {
                            case MS_GREENBUTTON:    key = Qt::Key_OfficeHome; break;
                            case MS_DVDMENU:        key = Qt::Key_Menu; break;
                            case MS_LIVETV:         key = Qt::Key_Messenger; break;
                            case MS_ZOOM:           key = Qt::Key_Zoom; break;
                            case MS_EJECT:          key = Qt::Key_Eject; break;
                            case MS_CLOSEDCAPTION:  key = Qt::Key_Subtitle; break;
                            case MS_RESERVED3:      key = Qt::Key_F27; break;
                            case MS_SUBAUDIO:       key = Qt::Key_AudioCycleTrack; break;
                            case MS_EXT0:           key = Qt::Key_Launch5; break;
                            case MS_EXT1:           key = Qt::Key_Launch6; break;
                            case MS_EXT2:           key = Qt::Key_Launch7; break;
                            case MS_EXT3:           key = Qt::Key_Launch8; break;
                            case MS_EXT4:           key = Qt::Key_Launch9; break;
                            case MS_EXT5:           key = Qt::Key_LaunchA; break;
                            case MS_EXT6:           key = Qt::Key_LaunchB; break;
                            case MS_EXT7:           key = Qt::Key_LaunchC; break;
                            case MS_EXT8:           key = Qt::Key_LaunchD; break;
                            case MS_EXTRAS:         key = Qt::Key_AudioForward; break;
                            case MS_EXTRASAPP:      key = Qt::Key_AudioRepeat; break;
                            case MS_10:             key = Qt::Key_Flip; break;
                            case MS_11:             key = Qt::Key_Hangup; break;
                            case MS_12:             key = Qt::Key_VoiceDial; break;
                            case MS_RESERVED5:      key = Qt::Key_F29; break;
                            case MS_CHANNELINPUT:   key = Qt::Key_C; break; // see TorcCECDevice for consistency
                            case MS_DVDTOPMENU:     key = Qt::Key_TopMenu; break;
                            case MS_MUSIC:          key = Qt::Key_Music; break;
                            case MS_RECORDEDTV:     key = Qt::Key_Execute; break;
                            case MS_PICTURES:       key = Qt::Key_Pictures; break;
                            case MS_VIDEOS:         key = Qt::Key_Video; break;
                            case MS_DVDANGLE:       key = Qt::Key_F24; break; // see TorcCECDevice for consistency
                            case MS_DVDAUDIO:       key = Qt::Key_Plus; break; // see TorcCECDevice for consistency
                            case MS_DVDSUBTITLE:    key = Qt::Key_Time; break;
                            case MS_RESERVED1:      key = Qt::Key_F25; break;
                            case MS_FMRADIO:        key = Qt::Key_LastNumberRedial; break;
                            case MS_TELETEXT:       key = Qt::Key_F7; break;
                            case MS_TELETEXT_RED:   key = Qt::Key_F2; break; // see TorcCECDevice for consistency
                            case MS_TELETEXT_GREEN: key = Qt::Key_F3; break;
                            case MS_TELETEXT_YELLOW: key = Qt::Key_F4; break;
                            case MS_TELETEXT_BLUE:  key = Qt::Key_F5; break;
                            case MS_RESERVED2:      key = Qt::Key_F26; break;
                            case MS_EXT11:          key = Qt::Key_LaunchG; break;
                            case MS_RESERVED4:      key = Qt::Key_F28; break;
                            case MS_EXT9:           key = Qt::Key_LaunchE; break;
                            case MS_EXT10:          key = Qt::Key_LaunchF; break;
                        }
                    }
                    else if (button && consumer)
                    {
                        context = "HID Consumer Control";

                        switch (button)
                        {
                            case AC_PROPERTIES:     key = Qt::Key_I; break;
                            case AC_PROGRAM_GUIDE:  key = Qt::Key_S; break;
                        }
                    }

                    if (key)
                    {
                        QKeyEvent *keyevent = new QKeyEvent(QEvent::KeyPress, key, TORC_KEYEVENT_MODIFIERS, context);

                        if (gLocalContext->GetUIObject())
                            QApplication::postEvent(gLocalContext->GetUIObject(), keyevent);

                        *Result = 0;
                        LOG(VB_GENERAL, LOG_INFO, QString("WM_INPUT: button 0x%1").arg(button, 0, 16));
                        return true;
                    }
                }
            }
            else
            {
                LOG(VB_GENERAL, LOG_ERR, "Failed to get device info");
            }
        }
    }
    else
    {
        LOG(VB_GENERAL, LOG_ERR, "Failed to retrieve raw input data");
    }

    return false;
}
Example #16
0
void StringData::setChar(int offset, char ch) {
  ASSERT(offset >= 0 && offset < size() && !isStatic());
  if (isImmutable()) escalate();
  ((char*)rawdata())[offset] = ch;
  m_hash = 0;
}
Example #17
0
int64 StringData::toInt64(int base /* = 10 */) const {
  // Taint absorbtion unnecessary; taint is recreated later for numerics
  return strtoll(rawdata(), NULL, base);
}