Exemple #1
0
/*
void ResrouceRim(const char* filename, PDP8::CpuState& cpu) {
   std::vector<char> data = GetResource(filename);
    PDP8::LoadRim(data,cpu);
}
void ResrouceBin(const char* filename, PDP8::CpuState& cpu) {
   std::vector<char> data = GetResource(filename);
    PDP8::LoadBin(data,cpu);
}
*/
std::vector<char>  MainWindow::getResource(const char* filename) {

	QFile s(filename);
	if (s.open(QFile::ReadOnly)) {
		QByteArray bytes = s.readAll();
		std::vector<char> data(bytes.begin(), bytes.end());
		return data;
	}
	throw std::runtime_error("F**K YOU");
}
Exemple #2
0
string const to_local8bit(docstring const & s)
{
	// This conversion can fail, depending on input.
	if (s.empty())
		return string();
	QByteArray const local = toqstr(s).toLocal8Bit();
	if (local.isEmpty())
		throw to_local8bit_failure();
	return string(local.begin(), local.end());
}
Exemple #3
0
void VersionEditor::onPasswordEdited(QString pass){
	QByteArray tmp = pass.toUtf8();
	ui->password = Kdbx::XorredBuffer::fromRaw(SafeVector<uint8_t>(tmp.begin(), tmp.end()), safeGetRandomBytes(tmp.size(), this));

	if (ui->showPasswordButton->isChecked()){
		ui->passwordLabel->setText(pass);
	}else{
		ui->passwordLabel->setText(QString(pass.size(), QChar('*')));
	}
}
Exemple #4
0
void bgPNG::getb(const QByteArray &b)
{
  qDebug("[bgPNG getb: %d, %08x]", num, (uint)th->currentThreadId());
  stat = 1;
  vector<uchar> v(b.size()); // filled by '\0' x n
  for(QByteArray::ConstIterator it = b.begin(); it != b.end(); it++)
    v.push_back(*it);
  for(vector<uchar>::iterator it = v.begin(); it != v.end(); it++)
    cout << setw(2) << setfill('0') << hex << right << (uint)*it << ", ";
  cout << endl;
}
void ReceiveThread::run()
{
    QByteArray dataArray;
    while(true)
    {
        serialPort->waitForReadyRead(-1);
        dataArray = serialPort->readAll();
        for(QByteArray::Iterator iter = dataArray.begin(); iter != dataArray.end(); iter++)
        {
            emit receivedDataByte(*iter);
        }
    }
}
void SeedManager::addTorrent(QString torrent) {
    QSettings s(settingsPath + torrent, QSettings::IniFormat);
    QByteArray data = s.value("data").toByteArray();
    libtorrent::entry e = libtorrent::bdecode(data.begin(), data.end());
    libtorrent::torrent_info *inf = new libtorrent::torrent_info(e);
    const libtorrent::torrent_handle h =
            session->add_torrent(inf, s.value("path").toString().toStdString(), e);

    h.set_upload_mode(true);
    h.auto_managed(false);
    if (h.is_paused())
        h.resume();

    torrentNames[h.name()] = torrent;
}
bool TestNode::invokePath (const QString &path, const QStringList &, int, HttpClient *client) {
	if (path == "/get") {
		client->write ("Works.");
	} else if (path == "/post") {
		auto func = [](HttpClient *client) {
			QByteArray data = client->readAll ();
			std::reverse (data.begin (), data.end ());
			client->write (data);
		};
		
		client->setSlotInfo (SlotInfo (Callback::fromLambda (func)));
	}
	
	// 
	return true;
}
void decode_kio_internal(Decoder *dec, QByteArray::ConstIterator &iit,
                         QByteArray::ConstIterator &iend,
                         QByteArray &out)
{
    out.resize(outbufsize);
    QByteArray::Iterator oit = out.begin();
    QByteArray::ConstIterator oend = out.end();

    while(!dec->decode(iit, iend, oit, oend))
        if(oit == oend) return;

    while(!dec->finish(oit, oend))
        if(oit == oend) return;

    out.truncate(oit - out.begin());
}
Exemple #9
0
static void inplace_crlf2lf(QByteArray &in)
{
    if (in.isEmpty()) {
        return;
    }
    QByteArray &out = in;  // inplace
    const char *s = in.begin();
    const char *const end = in.end();
    char *d = out.begin();
    char last = '\0';
    while (s < end) {
        if (*s == '\n' && last == '\r') {
            --d;
        }
        *d++ = last = *s++;
    }
    out.resize(d - out.begin());
}
void encode_decode_kio(bool encode, const Codec *codec,
                       const QByteArray &infile_buffer, QFile &outfile)
{

    Encoder *enc = 0;
    Decoder *dec = 0;

    // Get an encoder. This one you have to delete!
    if(encode)
    {
        enc = codec->makeEncoder(withCRLF);
        assert(enc);
    }
    else
    {
        dec = codec->makeDecoder(withCRLF);
        assert(dec);
    }

    QByteArray::ConstIterator iit = infile_buffer.begin();
    QByteArray::ConstIterator iend = infile_buffer.end();

    QByteArray out;
    do
    {
        out = QByteArray();
        if(encode)
            encode_kio_internal(enc, iit, iend, out);
        else
            decode_kio_internal(dec, iit, iend, out);
        if(writing && out.size())
        {
            Q_LONG written = outfile.writeBlock(out);
            assert(written == (Q_LONG)out.size());
        }
    }
    while(out.size());

    if(encode)
        delete enc;
    else
        delete dec;
}
Exemple #11
0
static void append_lf2crlf(QByteArray &out, const QByteArray &in)
{
    if (in.isEmpty()) {
        return;
    }
    const unsigned int oldOutSize = out.size();
    out.resize(oldOutSize + 2 * in.size());
    const char *s = in.begin();
    const char *const end = in.end();
    char *d = out.begin() + oldOutSize;
    char last = '\0';
    while (s < end) {
        if (*s == '\n' && last != '\r') {
            *d++ = '\r';
        }
        *d++ = last = *s++;
    }
    out.resize(d - out.begin());
}
QString BaseTranscode::transcode(const QString  &  inalphOrig,  const QString  &  outalph, QByteArray input, bool caseSensitive){
	QString inalph=caseSensitive?inalphOrig:inalphOrig.toLower();

	const unsigned int inbase=inalph.size();
	const unsigned int outbase=outalph.size();
	QString ret;
	InfInt acc=0;
	InfInt base=1;
	for(QByteArray::iterator it=input.begin(),end=input.end();it!=end;++it){
		unsigned char num=*it;
		acc+=base*num;
		base*=inbase;
	}
	while (acc > 0) {
		unsigned int remainder = (acc % outbase).toInt();
		acc /= outbase;
		ret=QString(outalph.at(remainder)) % ret;
	}
	return ret;
}
Exemple #13
0
QByteArray KMail::Util::lf2crlf(const QByteArray &src)
{
    const char *s = src.data();
    if(!s)
        return QByteArray();

    QByteArray result(2 * src.size());    // maximal possible length
    QByteArray::Iterator d = result.begin();
    // we use cPrev to make sure we insert '\r' only there where it is missing
    char cPrev = '?';
    const char *end = src.end();
    while(s != end)
    {
        if(('\n' == *s) && ('\r' != cPrev))
            *d++ = '\r';
        cPrev = *s;
        *d++ = *s++;
    }
    result.truncate(d - result.begin());   // does not add trailing NUL, as expected
    return result;
}
Exemple #14
0
void ParamsParser::parse(wexus::HTTPRequest *req, QVariantMap &out)
{
  assert(req);

  if (!req->query().isEmpty())
    decodeAndParse(req->query().begin(), req->query().end(), out);

  // parse the post data
  if (req->contentLength() > 0) {
    // read the content length into a string and then process that
    // TODO optimizes this in the future to iterate over the Device
    // santify check this resize operation???
    QByteArray ary = req->input()->read(req->contentLength());

    decodeAndParse(ary.begin(), ary.end(), out);
  }

  /*IODeviceIterator ii(req->input());
  IODeviceIterator endii;

  decodeAndParse(ii, endii);*/
}
Discovery::Announce Discovery::Announce::fromBinary(const QByteArray &data) {
	Announce rc;

	if (data.startsWith(QByteArray("BSYNC\0", 6))) {
		libtorrent::entry e = libtorrent::bdecode(data.begin()+6, data.end());
		libtorrent::entry::dictionary_type dict = e.dict();

		MessageType m = (MessageType) dict.at("m").integer();
		std::string peerId = dict.at("peer").string();
		std::string shareHash = dict.at("share").string();
		PeerAddress localAddress, externalAddress;
		if (dict.count("la")) {
			localAddress = PeerAddress::fromBinary(dict.at("la").string());
		}
		if (dict.count("a")) {
			externalAddress = PeerAddress::fromBinary(dict.at("a").string());
		}


		rc = Announce(Secret::fromShareHash(shareHash), Peer(QByteArray(peerId.data(), peerId.length()), localAddress, externalAddress));
	}

	return rc;
}
Exemple #16
0
QString unescaped(const QByteArray& str)
{
  QString ret;
  int cnt = 0;
  for(auto i = str.begin(); i < str.end(); ++i)
  {
    if(cnt++ != 0)
    {
    }
    if(*i == '\\')
    {
      char nxt = *++i;
      if(nxt == 'n')
        ret += '\n';
      else if(nxt == 't')
        ret += '\t';
      else if(nxt == 'f')
        ret += '\f';
      else if(nxt == 'v')
        ret += '\v';
      else if(nxt == 'r')
        ret += '\r';
      else if(nxt == '0')
        ret += '\0';
      else if(nxt == 'b')
        ret += '\b';
      else if(nxt == 'a')
        ret += '\a';
      else if(nxt == 'x' || nxt == 'X' || nxt == 'u' || nxt == 'U')
      {
        quint32 x = 0;
        for(++i; ; ++i)
        {
          x *= 16;
          if(i == str.end())
            break;
          else if(*i >= 'a' && *i <= 'f')
            x += (*i - 'a' + 10);
          else if(*i >= 'A' && *i <= 'F')
            x += (*i - 'A' + 10);
          else if(*i >= '0' && *i <= '9')
            x += (*i - '0');
          else
            break;
        }
        --i;
        x /= 16;
        ret += QString::fromUcs4(&x, 1);
      }
      else if(nxt == 'd' || nxt == 'D')
      {
        quint32 x = 0;
        for(++i; ; ++i)
        {
          x *= 10;
          if(i == str.end())
            break;
          else if(*i >= '0' && *i <= '9')
            x += (*i - '0');
          else
            break;
        }
        --i;
        x /= 10;
        ret += QString::fromUcs4(&x, 1);
      }
      else if(nxt == 'o' || nxt == 'O')
      {
        quint32 x = 0;
        for(++i; ; ++i)
        {
          x *= 8;
          if(i == str.end())
            break;
          else if(*i >= '0' && *i <= '7')
            x += (*i - '0');
          else
            break;
        }
        --i;
        x /= 8;
        ret += QString::fromUcs4(&x, 1);
      }
      else if(nxt == 'y' || nxt == 'Y')
      {
        quint32 x = 0;
        for(++i; ; ++i)
        {
          x *= 2;
          if(i == str.end())
            break;
          else if(*i >= '0' && *i <= '1')
            x += (*i - '0');
          else
            break;
        }
        --i;
        x /= 2;
        ret += QString::fromUcs4(&x, 1);
      }
      else
        ret += nxt;
    }
    else
      ret += *i;
  }
  return ret;
}
QStringList FileIo::makePackage(QString const& _deploymentFolder)
{

	Json::Value manifest;
	Json::Value entries(Json::arrayValue);

	QUrl folder(_deploymentFolder);
	QString path(folder.path());
	QDir deployDir = QDir(path);

	dev::RLPStream rlpStr;
	int k = 1;
	std::vector<bytes> files;
	for (auto item: deployDir.entryInfoList(QDir::Files))
	{
		QFile qFile(item.filePath());
		if (qFile.open(QIODevice::ReadOnly))
		{
			k++;
			QFileInfo fileInfo = QFileInfo(qFile.fileName());
			Json::Value jsonValue;
			std::string path = fileInfo.fileName() == "index.html" ? "/" : fileInfo.fileName().toStdString();
			jsonValue["path"] = path; //TODO: Manage relative sub folder
			jsonValue["file"] = "/" + fileInfo.fileName().toStdString();
			jsonValue["contentType"] = "text/html"; //TODO: manage multiple content type
			QByteArray a = qFile.readAll();
			bytes data = bytes(a.begin(), a.end());
			files.push_back(data);
			jsonValue["hash"] = toHex(dev::sha3(data).ref());
			entries.append(jsonValue);
		}
		qFile.close();
	}
	rlpStr.appendList(k);

	std::stringstream jsonStr;
	jsonStr << manifest;
	QByteArray b =  QString::fromStdString(jsonStr.str()).toUtf8();
	rlpStr.append(bytesConstRef((const unsigned char*)b.data(), b.size()));

	for (unsigned int k = 0; k < files.size(); k++)
		rlpStr.append(files.at(k));

	manifest["entries"] = entries;
	bytes dapp = rlpStr.out();
	dev::h256 dappHash = dev::sha3(dapp);
	//encrypt
	KeyPair key(dappHash);
	Secp256k1 enc;
	enc.encrypt(key.pub(), dapp);

	QUrl url(_deploymentFolder + "package.dapp");
	QFile compressed(url.path());
	QByteArray qFileBytes((char*)dapp.data(), dapp.size());
	if (compressed.open(QIODevice::WriteOnly))
	{
		compressed.write(qFileBytes);
		compressed.flush();
	}
	else
		error(tr("Error creating package.dapp"));
	compressed.close();
	QStringList ret;
	ret.append(QString::fromStdString(toHex(dappHash.ref())));
	ret.append(qFileBytes.toBase64());
	return ret;
}
void Preprocessor::processString(const QByteArray &str) {
    pp proc(d->env);
    d->initPP(proc);

    proc(str.begin(), str.end(), std::back_inserter(d->result));
}
Exemple #19
0
void YZPrinter::doPrint( )
{
    const double fontsize = 10.0;
    PSDoc *doc = PS_new();
    if (!doc)
        return ;
    QByteArray p = m_path.toLatin1();
    PS_open_file(doc, p.data());
    PS_set_info(doc, "Creator", "Yzis");
    PS_set_info(doc, "Author", "");
    PS_set_info(doc, "Title", p.data());
    // Set so it'll fit on both A4 and letter paper;
    // some of us live in the US, with archaic paper sizes. ;-)
    PS_set_info(doc, "BoundingBox", "0 0 596 792");
    int font;
    font = PS_findfont(doc, "Fixed", "", 0);
    dbg() << "findfont returned " << font << endl;
    if ( !font ) return ; //no font => abort

    QPrinter lpr(QPrinter::PrinterResolution);
    QPainter p( &lpr );

    QFont f( "fixed" );
    f.setFixedPitch( true );
    f.setStyleHint( QFont::TypeWriter );
    p.setFont( f );

    unsigned int height = lpr.height();
    unsigned int width = lpr.width();

    unsigned int linespace = p.fontMetrics().lineSpacing();
    unsigned int maxwidth = p.fontMetrics().maxWidth();

    p.end();

    PS_set_value(doc, "leading", linespace);

    unsigned int clipw = width / maxwidth - 1;
    unsigned int cliph = height / linespace - 1;

    unsigned int oldLinesVis = mView->getLinesVisible( );
    unsigned int oldColumnsVis = mView->getColumnsVisible( );

    //should be current's view setting no ? XXX
    bool number = mView->getLocalBooleanOption( "number" );
    unsigned int marginLeft = 0;

    double red, green, blue;

    if ( number ) {
        marginLeft = ( 2 + QString::number( mView->buffer()->lineCount() ).length() );
    }

    YOptionValue* ov_wrap = mView->getLocalOption( "wrap" );
    bool oldWrap = ov_wrap->boolean();
    ov_wrap->setBoolean( true );

    mView->setVisibleArea( clipw - marginLeft, cliph, false );
    unsigned int totalHeight = mView->drawTotalHeight();
    mView->setVisibleArea( clipw - marginLeft, totalHeight, false );
    mView->initDraw( 0, 0, 0, 0 );

    unsigned int lastLineNumber = 0;
    unsigned int pageNumber = 0;

    QRect titleRect( 0, 0, width, linespace + linespace / 2 );

    unsigned int topY = titleRect.height() + linespace;
    unsigned int curY = topY;
    unsigned int curX;

    cliph = ( height - topY ) / linespace;
    int nbPages = totalHeight / cliph + ( totalHeight % cliph ? 1 : 0 );
    PS_begin_page(doc, 596, 792);
    PS_setfont(doc, font, fontsize);
    PS_set_parameter(doc, "hyphenation", "false");
    PS_set_parameter(doc, "linebreak", "true");
    PS_set_parameter(doc, "parbreak", "false");
    PS_set_value(doc, "parindent", 0.0);
    PS_set_value(doc, "numindentlines", 0.0);

    while ( mView->drawNextLine( ) ) {
        if ( curY == topY ) {
            if ( pageNumber ) {
                PS_end_page(doc);
                PS_begin_page(doc, 596, 792);
                PS_setfont(doc, font, fontsize);
                PS_set_value(doc, "leading", linespace);
            }
            ++pageNumber;
            convertColor(Qt::black, red, green, blue);
            PS_setcolor(doc, "fillstroke", "rgb", red, green, blue, 0.0);
            QByteArray n = ( ' ' + mView->buffer()->fileName() ).toLatin1();
            PS_show_boxed(doc, n.data(),
                          titleRect.x(), titleRect.y(), titleRect.width(),
                          titleRect.height(), "left", "");
            QByteArray nb = ( QString::number( pageNumber ) + '/' + QString::number( nbPages ) + ' ' ).toLatin1();
            PS_show_boxed(doc,
                          nb.data(),
                          titleRect.x(), titleRect.y(), titleRect.width(),
                          titleRect.height(), "right", "");
        }
        if ( number ) {
            unsigned int lineNumber = mView->drawLineNumber();
            if ( lineNumber != lastLineNumber ) {
                //p.setPen( Qt::gray );
                convertColor(Qt::gray, red, green, blue);
                PS_setcolor(doc, "fillstroke", "rgb", red, green, blue, 0.0);
                PS_moveto(doc, 0, curY);
                QByteArray m = QString::number( lineNumber ).rightJustified( marginLeft - 1, ' ' ).toLatin1();
                PS_show(doc, m.data());
                lastLineNumber = lineNumber;
            }
        }
        curX = marginLeft * maxwidth;
        while ( mView->drawNextCol( ) ) {
            QColor c = mView->drawColor( );
            if ( c.isValid() && c != Qt::white )
                convertColor(mView->drawColor(), red, green, blue);
            else
                convertColor(Qt::black, red, green, blue);
            PS_setcolor(doc, "fillstroke", "rgb", red, green, blue, 0.0);
            char buf[2] = {
                              0, 0
                          };
            buf[0] = mView->drawChar().toLatin1();
            PS_show_xy(doc, buf, curX, curY);
            curX += mView->drawLength( ) * maxwidth;
        }
        curY += linespace * mView->drawHeight();
        if ( curY >= cliph * linespace + topY ) {
            // draw Rect
            convertColor(Qt::black, red, green, blue);
            PS_setcolor(doc, "fillstroke", "rgb", red, green, blue, 0.0);
            PS_rect(doc, 0, 0, width, curY);
            if ( number ) {
                PS_moveto(doc, marginLeft*maxwidth - maxwidth / 2, titleRect.height());
                PS_lineto(doc, marginLeft*maxwidth - maxwidth / 2, curY);
            }
            PS_moveto(doc, titleRect.x(), titleRect.height());
            PS_lineto(doc, titleRect.width(), titleRect.height());
            curY = topY;
        }
    }
    if ( curY != topY ) {
        // draw Rect
        convertColor(Qt::black, red, green, blue);
        PS_setcolor(doc, "fillstroke", "rgb", red, green, blue, 0.0);
        PS_rect(doc, 0, 0, width, curY);
        if ( number ) {
            PS_moveto(doc, marginLeft*maxwidth - maxwidth / 2, titleRect.height());
            PS_lineto(doc, marginLeft*maxwidth - maxwidth / 2, curY);
        }
        PS_moveto(doc, titleRect.x(), titleRect.height());
        PS_lineto(doc, titleRect.width(), titleRect.height());
    }
    PS_end_page(doc);
    PS_deletefont(doc, font);
    PS_close(doc);
    PS_delete(doc);
    PS_shutdown();

    ov_wrap->setBoolean( oldWrap );
    mView->setVisibleArea( oldColumnsVis, oldLinesVis, false );
}
bool KDEAccountsFormat::loadAll( KABC::AddressBook *book,
                              KABC::Resource *resource,
                              QFile *file )
{
    if ( !book || !file ) // eh?
        return false;

    QString uuid = "KDEAccountsEntry.";
    int id = 0;

    QByteArray array = file->readAll();
    file->close();

    QByteArray::ConstIterator it = array.begin();
    QByteArray::ConstIterator end = array.end();
    QByteArray::ConstIterator startLine;
    QString line;
    char eol = '\n';
    char delim = ' ';

    for ( ; it < end; it++ )
    {
        startLine = it;

        for ( ; it && it < end && *it != eol; it++ )
        { } // find eol

        uint length = it - startLine;
        line = QString::fromUtf8( startLine, length ).simplified();

        QString nickName;
        QString name;
        QString email;

        int firstSpace = line.indexOf( delim );
        if ( firstSpace > 0 )
        {
            nickName = line.left( firstSpace );

            int lastSpace = line.lastIndexOf( delim );
            if ( lastSpace > firstSpace )
            {
                email = line.mid( lastSpace +1 );

                int start = firstSpace + 1;
                int length = lastSpace - start;
                name = line.mid( start, length );

                if ( !email.isEmpty() )
                {
                    KABC::Addressee address;
                    address.setNickName( nickName  );
                    address.setNameFromString( name );
                    address.setOrganization("KDE Project");
                    address.insertCategory("KDE Developer");
                    address.insertEmail( email  );
                    address.setUid( uuid + QString::number( id++ ));

                    address.setResource( resource );
                    book->insertAddressee( address );
                }
            }
        }
    }

    return true;
}
Exemple #21
0
string FileName::toFilesystemEncoding() const
{
	// This doesn't work on Windows for non ascii file names.
	QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
	return string(encoded.begin(), encoded.end());
}
Exemple #22
0
string const to_filesystem8bit(docstring const & s)
{
	QByteArray const encoded = QFile::encodeName(toqstr(s));
	return string(encoded.begin(), encoded.end());
}
std::vector<char> Connection::converByteToVector(const QByteArray &array)
{
    return std::vector<char>(array.begin(),array.end());
}