• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ buf函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中buf函数的典型用法代码示例。如果您正苦于以下问题:C++ buf函数的具体用法?C++ buf怎么用?C++ buf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了buf函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: stri_encode_from_marked

/**
 * Convert character vector between marked encodings and the encoding provided
 *
 * @param str     input character vector or list of raw vectors
 * @param to    target encoding, \code{NULL} or \code{""} for default enc
 * @param to_raw single logical, should list of raw vectors be returned?
 * @return a converted character vector or list of raw vectors
 *
 * @version 0.1-?? (Marek Gagolewski, 2013-11-12)
 *
 * @version 0.2-1 (Marek Gagolewski, 2014-03-28)
 *          use StriUcnv
 *
 * @version 0.2-1 (Marek Gagolewski, 2014-04-01)
 *          calc required buf size a priori
 *
 * @version 0.3-1 (Marek Gagolewski, 2014-11-04)
 *    Issue #112: str_prepare_arg* retvals were not PROTECTed from gc
 */
SEXP stri_encode_from_marked(SEXP str, SEXP to, SEXP to_raw)
{
    PROTECT(str = stri_prepare_arg_string(str, "str"));
    const char* selected_to   = stri__prepare_arg_enc(to, "to", true); /* this is R_alloc'ed */
    bool to_raw_logical = stri__prepare_arg_logical_1_notNA(to_raw, "to_raw");

    STRI__ERROR_HANDLER_BEGIN(1)
    R_len_t str_n = LENGTH(str);
    StriContainerUTF16 str_cont(str, str_n);

    // get the number of strings to convert; if == 0, then you know what's the result
    if (str_n <= 0) return Rf_allocVector(to_raw_logical?VECSXP:STRSXP, 0);

    // Open converters
    StriUcnv ucnv(selected_to);
    UConverter* uconv_to = ucnv.getConverter(true /*register_callbacks*/);

    // Get target encoding mark
    cetype_t encmark_to = to_raw_logical?CE_BYTES:ucnv.getCE();

    // Prepare out val
    SEXP ret;
    STRI__PROTECT(ret = Rf_allocVector(to_raw_logical?VECSXP:STRSXP, str_n));

    // calculate required buf size
    R_len_t bufsize = 0;
    for (R_len_t i=0; i<str_n; ++i) {
        if (!str_cont.isNA(i) && str_cont.get(i).length() > bufsize)
            bufsize = str_cont.get(i).length();
    }
    bufsize = UCNV_GET_MAX_BYTES_FOR_STRING(bufsize, ucnv_getMaxCharSize(uconv_to));
    // "The calculated size is guaranteed to be sufficient for this conversion."
    String8buf buf(bufsize);

    for (R_len_t i=0; i<str_n; ++i) {
        if (str_cont.isNA(i)) {
            if (to_raw_logical) SET_VECTOR_ELT(ret, i, R_NilValue);
            else                SET_STRING_ELT(ret, i, NA_STRING);
            continue;
        }

        R_len_t curn_tmp = str_cont.get(i).length();
        const UChar* curs_tmp = str_cont.get(i).getBuffer(); // The buffer contents is (probably) not NUL-terminated.
        if (!curs_tmp)
            throw StriException(MSG__INTERNAL_ERROR);

        UErrorCode status = U_ZERO_ERROR;
        ucnv_resetFromUnicode(uconv_to);
        R_len_t bufneed = ucnv_fromUChars(uconv_to, buf.data(), buf.size(),
                                          curs_tmp, curn_tmp, &status);
        if (bufneed <= buf.size()) {
            STRI__CHECKICUSTATUS_THROW(status, {/* do nothing special on err */})
        }
        else {// larger buffer needed [this shouldn't happen?]
            buf.resize(bufneed, false/*destroy contents*/);
            status = U_ZERO_ERROR;
            bufneed = ucnv_fromUChars(uconv_to, buf.data(), buf.size(),
                                      curs_tmp, curn_tmp, &status);
            STRI__CHECKICUSTATUS_THROW(status, {/* do nothing special on err */})
        }

        if (to_raw_logical) {
            SEXP outobj;
            STRI__PROTECT(outobj = Rf_allocVector(RAWSXP, bufneed));
            memcpy(RAW(outobj), buf.data(), (size_t)bufneed);
            SET_VECTOR_ELT(ret, i, outobj);
            STRI__UNPROTECT(1);
        }
        else {
            SET_STRING_ELT(ret, i,
                           Rf_mkCharLenCE(buf.data(), bufneed, encmark_to));
        }
    }

    STRI__UNPROTECT_ALL
    return ret;

    STRI__ERROR_HANDLER_END({/* nothing special on error */})
}
开发者ID:balagopalraj,项目名称:clearlinux,代码行数:98,代码来源:stri_encoding_conversion.cpp


示例2: CV_Assert

void cv::mixChannels( const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, const int* fromTo, size_t npairs )
{
    if( npairs == 0 )
        return;
    CV_Assert( src && nsrcs > 0 && dst && ndsts > 0 && fromTo && npairs > 0 );
    
    size_t i, j, k, esz1 = dst[0].elemSize1();
    int depth = dst[0].depth();

    AutoBuffer<uchar> buf((nsrcs + ndsts + 1)*(sizeof(Mat*) + sizeof(uchar*)) + npairs*(sizeof(uchar*)*2 + sizeof(int)*6));
    const Mat** arrays = (const Mat**)(uchar*)buf;
    uchar** ptrs = (uchar**)(arrays + nsrcs + ndsts);
    const uchar** srcs = (const uchar**)(ptrs + nsrcs + ndsts + 1);
    uchar** dsts = (uchar**)(srcs + npairs);
    int* tab = (int*)(dsts + npairs);
    int *sdelta = (int*)(tab + npairs*4), *ddelta = sdelta + npairs;
    
    for( i = 0; i < nsrcs; i++ )
        arrays[i] = &src[i];
    for( i = 0; i < ndsts; i++ )
        arrays[i + nsrcs] = &dst[i];
    ptrs[nsrcs + ndsts] = 0;
    
    for( i = 0; i < npairs; i++ )
    {
        int i0 = fromTo[i*2], i1 = fromTo[i*2+1];
        if( i0 >= 0 )
        {
            for( j = 0; j < nsrcs; i0 -= src[j].channels(), j++ )
                if( i0 < src[j].channels() )
                    break;
            CV_Assert(j < nsrcs && src[j].depth() == depth);
            tab[i*4] = (int)j; tab[i*4+1] = (int)(i0*esz1);
            sdelta[i] = src[j].channels();
        }
        else
        {
            tab[i*4] = (int)(nsrcs + ndsts); tab[i*4+1] = 0;
            sdelta[i] = 0;
        }
        
        for( j = 0; j < ndsts; i1 -= dst[j].channels(), j++ )
            if( i1 < dst[j].channels() )
                break;
        CV_Assert(i1 >= 0 && j < ndsts && dst[j].depth() == depth);
        tab[i*4+2] = (int)(j + nsrcs); tab[i*4+3] = (int)(i1*esz1);
        ddelta[i] = dst[j].channels();
    }

    NAryMatIterator it(arrays, ptrs, (int)(nsrcs + ndsts));
    int total = (int)it.size, blocksize = std::min(total, (int)((BLOCK_SIZE + esz1-1)/esz1));
    MixChannelsFunc func = mixchTab[depth];
    
    for( i = 0; i < it.nplanes; i++, ++it )
    {
        for( k = 0; k < npairs; k++ )
        {
            srcs[k] = ptrs[tab[k*4]] + tab[k*4+1];
            dsts[k] = ptrs[tab[k*4+2]] + tab[k*4+3];
        }
        
        for( int j = 0; j < total; j += blocksize )
        {
            int bsz = std::min(total - j, blocksize);
            func( srcs, sdelta, dsts, ddelta, bsz, (int)npairs );
            
            if( j + blocksize < total )
                for( k = 0; k < npairs; k++ )
                {
                    srcs[k] += blocksize*sdelta[k]*esz1;
                    dsts[k] += blocksize*ddelta[k]*esz1;
                }
        }
    }
}
开发者ID:colombc,项目名称:Sankore-ThirdParty,代码行数:75,代码来源:convert.cpp


示例3: wxSplitPath

// this function is called a *lot* of times (as I learned after seeing from
// profiler output that it is called ~12000 times from Mahogany start up code!)
// so it is important to optimize it - in particular, avoid using generic
// string functions here and do everything manually because it is faster
//
// I still kept the old version to be able to check that the optimized code has
// the same output as the non optimized version.
void wxRegConfig::SetPath(const wxString& strPath)
{
    // remember the old path
    wxString strOldPath = m_strPath;

#ifdef WX_DEBUG_SET_PATH // non optimized version kept here for testing
    wxString m_strPathAlt;

    {
        wxArrayString aParts;

        // because GetPath() returns "" when we're at root, we must understand
        // empty string as "/"
        if ( strPath.empty() || (strPath[0] == wxCONFIG_PATH_SEPARATOR) ) {
            // absolute path
            wxSplitPath(aParts, strPath);
        }
        else {
            // relative path, combine with current one
            wxString strFullPath = GetPath();
            strFullPath << wxCONFIG_PATH_SEPARATOR << strPath;
            wxSplitPath(aParts, strFullPath);
        }

        // recombine path parts in one variable
        wxString strRegPath;
        m_strPathAlt.Empty();
        for ( size_t n = 0; n < aParts.Count(); n++ ) {
            strRegPath << '\\' << aParts[n];
            m_strPathAlt << wxCONFIG_PATH_SEPARATOR << aParts[n];
        }
    }
#endif // 0

    // check for the most common case first
    if ( strPath.empty() )
    {
        m_strPath = wxCONFIG_PATH_SEPARATOR;
    }
    else // not root
    {
        // construct the full path
        wxString strFullPath;
        if ( strPath[0u] == wxCONFIG_PATH_SEPARATOR )
        {
            // absolute path
            strFullPath = strPath;
        }
        else // relative path
        {
            strFullPath.reserve(2*m_strPath.length());

            strFullPath << m_strPath;
            if ( strFullPath.Len() == 0 ||
                 strFullPath.Last() != wxCONFIG_PATH_SEPARATOR )
                strFullPath << wxCONFIG_PATH_SEPARATOR;
            strFullPath << strPath;
        }

        // simplify it: we need to handle ".." here

        // count the total number of slashes we have to know if we can go upper
        size_t totalSlashes = 0;

        // position of the last slash to be able to backtrack to it quickly if
        // needed, but we set it to -1 if we don't have a valid position
        //
        // we only remember the last position which means that we handle ".."
        // quite efficiently but not "../.." - however the latter should be
        // much more rare, so it is probably ok
        int posLastSlash = -1;

        const wxChar *src = strFullPath.c_str();
        size_t len = strFullPath.length();
        const wxChar *end = src + len;

        wxStringBufferLength buf(m_strPath, len);
        wxChar *dst = buf;
        wxChar *start = dst;

        for ( ; src < end; src++, dst++ )
        {
            if ( *src == wxCONFIG_PATH_SEPARATOR )
            {
                // check for "/.."

                // note that we don't have to check for src < end here as
                // *end == 0 so can't be '.'
                if ( src[1] == wxT('.') && src[2] == wxT('.') &&
                     (src + 3 == end || src[3] == wxCONFIG_PATH_SEPARATOR) )
                {
                    if ( !totalSlashes )
                    {
//.........这里部分代码省略.........
开发者ID:chromylei,项目名称:third_party,代码行数:101,代码来源:regconf.cpp


示例4: LOG

StorageReply::UP
ProtocolSerialization::decodeReply(mbus::BlobRef data, const api::StorageCommand& cmd) const
{
    LOG(spam, "Decode %d bytes of data.", data.size());
    if (data.size() < sizeof(int32_t)) {
        std::ostringstream ost;
        ost << "Request of size " << data.size() << " is not big enough to be "
            "able to store a request.";
        throw vespalib::IllegalArgumentException(ost.str(), VESPA_STRLOC);
    }

    document::ByteBuffer buf(data.data(), data.size());
    int type;
    buf.getIntNetwork(type);
    SRep::UP reply;
    switch (type) {
    case api::MessageType::PUT_REPLY_ID:
        reply = onDecodePutReply(cmd, buf); break;
    case api::MessageType::UPDATE_REPLY_ID:
        reply = onDecodeUpdateReply(cmd, buf); break;
    case api::MessageType::GET_REPLY_ID:
        reply = onDecodeGetReply(cmd, buf); break;
    case api::MessageType::REMOVE_REPLY_ID:
        reply = onDecodeRemoveReply(cmd, buf); break;
    case api::MessageType::REVERT_REPLY_ID:
        reply = onDecodeRevertReply(cmd, buf); break;
    case api::MessageType::CREATEBUCKET_REPLY_ID:
        reply = onDecodeCreateBucketReply(cmd, buf); break;
    case api::MessageType::DELETEBUCKET_REPLY_ID:
        reply = onDecodeDeleteBucketReply(cmd, buf); break;
    case api::MessageType::MERGEBUCKET_REPLY_ID:
        reply = onDecodeMergeBucketReply(cmd, buf); break;
    case api::MessageType::GETBUCKETDIFF_REPLY_ID:
        reply = onDecodeGetBucketDiffReply(cmd, buf); break;
    case api::MessageType::APPLYBUCKETDIFF_REPLY_ID:
        reply = onDecodeApplyBucketDiffReply(cmd, buf); break;
    case api::MessageType::REQUESTBUCKETINFO_REPLY_ID:
        reply = onDecodeRequestBucketInfoReply(cmd, buf); break;
    case api::MessageType::NOTIFYBUCKETCHANGE_REPLY_ID:
        reply = onDecodeNotifyBucketChangeReply(cmd, buf); break;
    case api::MessageType::SPLITBUCKET_REPLY_ID:
        reply = onDecodeSplitBucketReply(cmd, buf); break;
    case api::MessageType::JOINBUCKETS_REPLY_ID:
        reply = onDecodeJoinBucketsReply(cmd, buf); break;
    case api::MessageType::VISITOR_CREATE_REPLY_ID:
        reply = onDecodeCreateVisitorReply(cmd, buf); break;
    case api::MessageType::VISITOR_DESTROY_REPLY_ID:
        reply = onDecodeDestroyVisitorReply(cmd, buf); break;
    case api::MessageType::REMOVELOCATION_REPLY_ID:
        reply = onDecodeRemoveLocationReply(cmd, buf); break;
    case api::MessageType::SETBUCKETSTATE_REPLY_ID:
        reply = onDecodeSetBucketStateReply(cmd, buf); break;
    default:
    {
        std::ostringstream ost;
        ost << "Unknown message type " << type;
        throw vespalib::IllegalArgumentException(ost.str(), VESPA_STRLOC);
    }
    }
    return std::make_unique<StorageReply>(std::move(reply));
}
开发者ID:songhtdo,项目名称:vespa,代码行数:61,代码来源:protocolserialization.cpp


示例5: buf

Buffer AbstractData::encode() const {
  Buffer buf(get_buffers_size());
  encode_buffers(0, &buf);
  return buf;
}
开发者ID:mody,项目名称:cpp-driver,代码行数:5,代码来源:abstract_data.cpp


示例6: parseVDMX

// Parse a TrueType VDMX table.
//   yMax: (output) the ascender value from the table
//   yMin: (output) the descender value from the table (negative!)
//   vdmx: the table bytes
//   vdmxLength: length of @vdmx, in bytes
//   targetPixelSize: the pixel size of the font (e.g. 16)
//
// Returns true iff a suitable match are found. Otherwise, *yMax and *yMin are
// untouched. size_t must be 32-bits to avoid overflow.
//
// See http://www.microsoft.com/opentype/otspec/vdmx.htm
bool parseVDMX(int* yMax, int* yMin,
               const uint8_t* vdmx, size_t vdmxLength,
               unsigned targetPixelSize)
{
    Buffer buf(vdmx, vdmxLength);

    // We ignore the version. Future tables should be backwards compatible with
    // this layout.
    uint16_t numRatios;
    if (!buf.skip(4) || !buf.readU16(&numRatios))
        return false;

    // Now we have two tables. Firstly we have @numRatios Ratio records, then a
    // matching array of @numRatios offsets. We save the offset of the beginning
    // of this second table.
    //
    // Range 6 <= x <= 262146
    unsigned long offsetTableOffset =
        buf.offset() + 4 /* sizeof struct ratio */ * numRatios;

    unsigned desiredRatio = 0xffffffff;
    // We read 4 bytes per record, so the offset range is
    //   6 <= x <= 524286
    for (unsigned i = 0; i < numRatios; ++i) {
        uint8_t xRatio, yRatio1, yRatio2;

        if (!buf.skip(1)
            || !buf.readU8(&xRatio)
            || !buf.readU8(&yRatio1)
            || !buf.readU8(&yRatio2))
            return false;

        // This either covers 1:1, or this is the default entry (0, 0, 0)
        if ((xRatio == 1 && yRatio1 <= 1 && yRatio2 >= 1)
            || (xRatio == 0 && yRatio1 == 0 && yRatio2 == 0)) {
            desiredRatio = i;
            break;
        }
    }

    if (desiredRatio == 0xffffffff) // no ratio found
        return false;

    // Range 10 <= x <= 393216
    buf.setOffset(offsetTableOffset + sizeof(uint16_t) * desiredRatio);

    // Now we read from the offset table to get the offset of another array
    uint16_t groupOffset;
    if (!buf.readU16(&groupOffset))
        return false;
    // Range 0 <= x <= 65535
    buf.setOffset(groupOffset);

    uint16_t numRecords;
    if (!buf.readU16(&numRecords) || !buf.skip(sizeof(uint16_t)))
        return false;

    // We read 6 bytes per record, so the offset range is
    //   4 <= x <= 458749
    for (unsigned i = 0; i < numRecords; ++i) {
        uint16_t pixelSize;
        if (!buf.readU16(&pixelSize))
            return false;
        // the entries are sorted, so we can abort early if need be
        if (pixelSize > targetPixelSize)
            return false;

        if (pixelSize == targetPixelSize) {
            int16_t tempYMax, tempYMin;
            if (!buf.readS16(&tempYMax)
                || !buf.readS16(&tempYMin))
                return false;
            *yMin = tempYMin;
            *yMax = tempYMax;
            return true;
        }
        if (!buf.skip(2 * sizeof(int16_t)))
            return false;
    }

    return false;
}
开发者ID:Jamesducque,项目名称:mojo,代码行数:93,代码来源:VDMXParser.cpp


示例7: selection_handler

static void
selection_handler( GtkWidget *WXUNUSED(widget),
                   GtkSelectionData *selection_data,
                   guint WXUNUSED(info),
                   guint WXUNUSED(time),
                   gpointer signal_data )
{
    wxClipboard * const clipboard = wxTheClipboard;
    if ( !clipboard )
        return;

    wxDataObject * const data = clipboard->GTKGetDataObject(
        gtk_selection_data_get_selection(selection_data));
    if ( !data )
        return;

    // ICCCM says that TIMESTAMP is a required atom.
    // In particular, it satisfies Klipper, which polls
    // TIMESTAMP to see if the clipboards content has changed.
    // It shall return the time which was used to set the data.
    if (gtk_selection_data_get_target(selection_data) == g_timestampAtom)
    {
        guint timestamp = GPOINTER_TO_UINT (signal_data);
        gtk_selection_data_set(selection_data,
                               GDK_SELECTION_TYPE_INTEGER,
                               32,
                               (guchar*)&(timestamp),
                               sizeof(timestamp));
        wxLogTrace(TRACE_CLIPBOARD,
                   wxT("Clipboard TIMESTAMP requested, returning timestamp=%u"),
                   timestamp);
        return;
    }

    wxDataFormat format(gtk_selection_data_get_target(selection_data));

    wxLogTrace(TRACE_CLIPBOARD,
               wxT("clipboard data in format %s, GtkSelectionData is target=%s type=%s selection=%s timestamp=%u"),
               format.GetId().c_str(),
               wxString::FromAscii(wxGtkString(gdk_atom_name(gtk_selection_data_get_target(selection_data)))).c_str(),
               wxString::FromAscii(wxGtkString(gdk_atom_name(gtk_selection_data_get_data_type(selection_data)))).c_str(),
               wxString::FromAscii(wxGtkString(gdk_atom_name(gtk_selection_data_get_selection(selection_data)))).c_str(),
               GPOINTER_TO_UINT( signal_data )
               );

    if ( !data->IsSupportedFormat( format ) )
        return;

    int size = data->GetDataSize( format );
    if ( !size )
        return;

    wxCharBuffer buf(size - 1); // it adds 1 internally (for NUL)

    // text data must be returned in UTF8 if format is wxDF_UNICODETEXT
    if ( !data->GetDataHere(format, buf.data()) )
        return;

    // use UTF8_STRING format if requested in Unicode build but just plain
    // STRING one in ANSI or if explicitly asked in Unicode
#if wxUSE_UNICODE
    if (format == wxDataFormat(wxDF_UNICODETEXT))
    {
        gtk_selection_data_set_text(
            selection_data,
            (const gchar*)buf.data(),
            size );
    }
    else
#endif // wxUSE_UNICODE
    {
        gtk_selection_data_set(
            selection_data,
            GDK_SELECTION_TYPE_STRING,
            8*sizeof(gchar),
            (const guchar*)buf.data(),
            size );
    }
}
开发者ID:Kaoswerk,项目名称:newton-dynamics,代码行数:79,代码来源:clipbrd.cpp


示例8: m_cg

void HostListItem::paintCell(QPainter * p, const QColorGroup & cg, int column, int width, int align )
{
  QColorGroup m_cg( cg );

  // TODO: reuse icons?
  if( column == HostListItem::Video )
  {
    if( m_video ) { // video ?
      if( m_read_only )
        setPixmap( HostListItem::Video, SmallIcon("nmm_option_on_readonly")  );
      else
        setPixmap( HostListItem::Video, SmallIcon("nmm_option_on")  );
    }
    else
      if( ! m_read_only)
        setPixmap( HostListItem::Video, SmallIcon("nmm_option_off") );
  }
  else if( column == HostListItem::Audio )
  {
    if( m_audio ) {// audio ?
      if( m_read_only )
        setPixmap( HostListItem::Audio, SmallIcon("nmm_option_on_readonly")  );
      else
        setPixmap( HostListItem::Audio, SmallIcon("nmm_option_on")  );
    }
    else
      if( ! m_read_only)
        setPixmap( HostListItem::Audio, SmallIcon("nmm_option_off") );
  }
  else if( column ==  HostListItem::Status )
  {
    QFont font( p->font() );
    if( ! m_status  ) // Unknown
    {
      font.setBold( false );
      setText( HostListItem::Status , i18n("Unknown") );
    }
    else if( m_status == NmmEngine::STATUS_OK )
    {
      font.setBold( false );
      m_cg.setColor( QColorGroup::Text, Qt::darkGreen );
      setText( HostListItem::Status , i18n("OK") );
    }
    else { // error
      font.setBold( true );
      m_cg.setColor( QColorGroup::Text, Qt::red );
      setText( HostListItem::Status , i18n("Failed") );
    }
    p->setFont( font );
  }
  else if( column == HostListItem::Volume )
  {
    QPixmap buf( width, height() );
    QColor bg = listView()->viewport()->backgroundColor();
    buf.fill( bg );

    bitBlt( &buf, 0, 0, pixmapVolume( PixInset ) );

    // Draw gradient
    static int padding = 7;
    static int vol; // pixelposition
    if( this == ((HostList*)listView())->m_hoveredVolume )
    {
      vol = listView()->viewportToContents( listView()->viewport()->mapFromGlobal( QCursor::pos() ) ).x();
      vol -= listView()->header()->sectionPos( HostListItem::Volume );
    }
    else
      vol = (m_volume / 2) + 56;

    //std::cerr << "rel vol = " << vol << std::endl;

    static int center = 56;
    if( vol > center ) {
      bitBlt( &buf, 0, 0, pixmapVolume( PixRight ), 0, 0, vol + 1 /* TODO: why + 1??? */ );
    }
    else if ( vol < center ) {
      bitBlt( &buf, vol, 0, pixmapVolume( PixLeft ), vol, 0, 56 );
    }
    else
    {}

    // Calculate actual volume string from pixelposition
    vol = volumeAtPosition( vol );
    QString vol_text; 
    if( vol > 0 )
      vol_text = "+";
    vol_text += QString::number( vol );
    vol_text += "%";

    // Draw relative volume number
    QPainter p_number(&buf);
    p_number.setPen( cg.buttonText() );
    QFont font;
    font.setPixelSize( 9 );
    p_number.setFont( font );
    const QRect rect( 40, 0, 34, 15 );
    p_number.drawText( rect, Qt::AlignRight | Qt::AlignVCenter, vol_text );
    p_number.end();
    //bitBlt( p_number.device(), 0, 0, &buf );

//.........这里部分代码省略.........
开发者ID:tmarques,项目名称:waheela,代码行数:101,代码来源:HostListItem.cpp


示例9: MakeObjectFilename

// --------------------------------------------------------------------------
//
// Function
//		Name:    HousekeepStoreAccount::ScanDirectory(int64_t)
//		Purpose: Private. Scan a directory for potentially deleteable
//			 items, and add them to the list. Returns true if the
//			 scan should continue.
//		Created: 11/12/03
//
// --------------------------------------------------------------------------
bool HousekeepStoreAccount::ScanDirectory(int64_t ObjectID,
	BackupStoreInfo& rBackupStoreInfo)
{
#ifndef WIN32
	if((--mCountUntilNextInterprocessMsgCheck) <= 0)
	{
		mCountUntilNextInterprocessMsgCheck =
			POLL_INTERPROCESS_MSG_CHECK_FREQUENCY;

		// Check for having to stop
		// Include account ID here as the specified account is locked
		if(mpHousekeepingCallback && mpHousekeepingCallback->CheckForInterProcessMsg(mAccountID))
		{
			// Need to abort now
			return false;
		}
	}
#endif

	// Get the filename
	std::string objectFilename;
	MakeObjectFilename(ObjectID, objectFilename);

	// Open it.
	std::auto_ptr<RaidFileRead> dirStream(RaidFileRead::Open(mStoreDiscSet,
		objectFilename));

	// Add the size of the directory on disc to the size being calculated
	int64_t originalDirSizeInBlocks = dirStream->GetDiscUsageInBlocks();
	mBlocksInDirectories += originalDirSizeInBlocks;
	mBlocksUsed += originalDirSizeInBlocks;

	// Read the directory in
	BackupStoreDirectory dir;
	BufferedStream buf(*dirStream);
	dir.ReadFromStream(buf, IOStream::TimeOutInfinite);
	dir.SetUserInfo1_SizeInBlocks(originalDirSizeInBlocks);
	dirStream->Close();

	// Is it empty?
	if(dir.GetNumberOfEntries() == 0)
	{
		// Add it to the list of directories to potentially delete
		mEmptyDirectories.push_back(dir.GetObjectID());
	}

	// Calculate reference counts first, before we start requesting
	// files to be deleted.
	// BLOCK
	{
		BackupStoreDirectory::Iterator i(dir);
		BackupStoreDirectory::Entry *en = 0;

		while((en = i.Next()) != 0)
		{
			// This directory references this object
			mapNewRefs->AddReference(en->GetObjectID());
		}
	}

	// BLOCK
	{
		// Remove any files which are marked for removal as soon
		// as they become old or deleted.
		bool deletedSomething = false;
		do
		{
			// Iterate through the directory
			deletedSomething = false;
			BackupStoreDirectory::Iterator i(dir);
			BackupStoreDirectory::Entry *en = 0;
			while((en = i.Next(BackupStoreDirectory::Entry::Flags_File)) != 0)
			{
				int16_t enFlags = en->GetFlags();
				if((enFlags & BackupStoreDirectory::Entry::Flags_RemoveASAP) != 0
					&& (en->IsDeleted() || en->IsOld()))
				{
					// Delete this immediately.
					DeleteFile(ObjectID, en->GetObjectID(), dir,
						objectFilename, rBackupStoreInfo);
					
					// flag as having done something
					deletedSomething = true;

					// Must start the loop from the beginning again, as iterator is now
					// probably invalid.
					break;
				}
			}
		} while(deletedSomething);
//.........这里部分代码省略.........
开发者ID:jamesog,项目名称:boxbackup,代码行数:101,代码来源:HousekeepStoreAccount.cpp


示例10: LoadMtl

	std::string LoadMtl(
		std::map<std::string, material_t>& material_map,
		const char* filename,
		const char* mtl_basepath)
	{
		material_map.clear();
		std::stringstream err;

		std::string filepath;

		if (mtl_basepath) {
			filepath = std::string(mtl_basepath) + std::string(filename);
		}
		else {
			filepath = std::string(filename);
		}

		std::ifstream ifs(filepath.c_str());
		if (!ifs) {
			err << "Cannot open file [" << filepath << "]" << std::endl;
			return err.str();
		}

		material_t material;

		int maxchars = 8192;  // Alloc enough size.
		std::vector<char> buf(maxchars);  // Alloc enough size.
		while (ifs.peek() != -1) {
			ifs.getline(&buf[0], maxchars);

			std::string linebuf(&buf[0]);

			// Trim newline '\r\n' or '\r'
			if (linebuf.size() > 0) {
				if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1);
			}
			if (linebuf.size() > 0) {
				if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1);
			}

			// Skip if empty line.
			if (linebuf.empty()) {
				continue;
			}

			// Skip leading space.
			const char* token = linebuf.c_str();
			token += strspn(token, " \t");

			assert(token);
			if (token[0] == '\0') continue; // empty line

			if (token[0] == '#') continue;  // comment line

			// new mtl
			if ((0 == strncmp(token, "newmtl", 6)) && isSpace((token[6]))) {
				// flush previous material.
				material_map.insert(std::pair<std::string, material_t>(material.name, material));

				// initial temporary material
				InitMaterial(material);

				// set new mtl name
				char namebuf[4096];
				token += 7;
				sscanf(token, "%s", namebuf);
				material.name = namebuf;
				continue;
			}

			// ambient
			if (token[0] == 'K' && token[1] == 'a' && isSpace((token[2]))) {
				token += 2;
				float r, g, b;
				parseFloat3(r, g, b, token);
				material.ambient[0] = r;
				material.ambient[1] = g;
				material.ambient[2] = b;
				continue;
			}

			// diffuse
			if (token[0] == 'K' && token[1] == 'd' && isSpace((token[2]))) {
				token += 2;
				float r, g, b;
				parseFloat3(r, g, b, token);
				material.diffuse[0] = r;
				material.diffuse[1] = g;
				material.diffuse[2] = b;
				continue;
			}

			// specular
			if (token[0] == 'K' && token[1] == 's' && isSpace((token[2]))) {
				token += 2;
				float r, g, b;
				parseFloat3(r, g, b, token);
				material.specular[0] = r;
				material.specular[1] = g;
				material.specular[2] = b;
//.........这里部分代码省略.........
开发者ID:losmescaleros,项目名称:RayCast,代码行数:101,代码来源:obj2pbrt.cpp


示例11: LoadObj

	std::string
		LoadObj(
		std::vector<shape_t>& shapes,
		const char* filename,
		const char* mtl_basepath)
	{

		shapes.clear();

		std::stringstream err;

		std::ifstream ifs(filename);
		if (!ifs) {
			err << "Cannot open file [" << filename << "]" << std::endl;
			return err.str();
		}

		std::vector<float> v;
		std::vector<float> vn;
		std::vector<float> vt;
		std::vector<std::vector<vertex_index> > faceGroup;
		std::string name;

		// material
		std::map<std::string, material_t> material_map;
		material_t material;

		int maxchars = 8192;  // Alloc enough size.
		std::vector<char> buf(maxchars);  // Alloc enough size.
		while (ifs.peek() != -1) {
			ifs.getline(&buf[0], maxchars);

			std::string linebuf(&buf[0]);

			// Trim newline '\r\n' or '\r'
			if (linebuf.size() > 0) {
				if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1);
			}
			if (linebuf.size() > 0) {
				if (linebuf[linebuf.size() - 1] == '\n') linebuf.erase(linebuf.size() - 1);
			}

			// Skip if empty line.
			if (linebuf.empty()) {
				continue;
			}

			// Skip leading space.
			const char* token = linebuf.c_str();
			token += strspn(token, " \t");

			assert(token);
			if (token[0] == '\0') continue; // empty line

			if (token[0] == '#') continue;  // comment line

			// vertex
			if (token[0] == 'v' && isSpace((token[1]))) {
				token += 2;
				float x, y, z;
				parseFloat3(x, y, z, token);
				v.push_back(x);
				v.push_back(y);
				v.push_back(z);
				continue;
			}

			// normal
			if (token[0] == 'v' && token[1] == 'n' && isSpace((token[2]))) {
				token += 3;
				float x, y, z;
				parseFloat3(x, y, z, token);
				vn.push_back(x);
				vn.push_back(y);
				vn.push_back(z);
				continue;
			}

			// texcoord
			if (token[0] == 'v' && token[1] == 't' && isSpace((token[2]))) {
				token += 3;
				float x, y;
				parseFloat2(x, y, token);
				vt.push_back(x);
				vt.push_back(y);
				continue;
			}

			// face
			if (token[0] == 'f' && isSpace((token[1]))) {
				token += 2;
				token += strspn(token, " \t");

				std::vector<vertex_index> face;
				while (!isNewLine(token[0])) {
					vertex_index vi = parseTriple(token, v.size() / 3, vn.size() / 3, vt.size() / 2);
					face.push_back(vi);
					int n = strspn(token, " \t\r");
					token += n;
				}
//.........这里部分代码省略.........
开发者ID:losmescaleros,项目名称:RayCast,代码行数:101,代码来源:obj2pbrt.cpp


示例12: buf

void grid_renderer<T>::process(line_symbolizer const& sym,
                               mapnik::feature_impl & feature,
                               proj_transform const& prj_trans)
{
    using pixfmt_type = typename grid_renderer_base_type::pixfmt_type;
    using color_type = typename grid_renderer_base_type::pixfmt_type::color_type;
    using renderer_type = agg::renderer_scanline_bin_solid<grid_renderer_base_type>;
    using conv_types = boost::mpl::vector<clip_line_tag, transform_tag,
                                          offset_transform_tag, affine_transform_tag,
                                          simplify_tag, smooth_tag, dash_tag, stroke_tag>;
    agg::scanline_bin sl;

    grid_rendering_buffer buf(pixmap_.raw_data(), common_.width_, common_.height_, common_.width_);
    pixfmt_type pixf(buf);

    grid_renderer_base_type renb(pixf);
    renderer_type ren(renb);

    ras_ptr->reset();

    agg::trans_affine tr;
    auto transform = get_optional<transform_type>(sym, keys::geometry_transform);
    if (transform)
    {
        evaluate_transform(tr, feature, common_.vars_, *transform, common_.scale_factor_);
    }

    box2d<double> clipping_extent = common_.query_extent_;

    bool clip = get<value_bool>(sym, keys::clip, feature, common_.vars_, true);
    double width = get<value_double>(sym, keys::stroke_width, feature, common_.vars_,1.0);
    double offset = get<value_double>(sym, keys::offset, feature, common_.vars_,0.0);
    double simplify_tolerance = get<value_double>(sym, keys::simplify_tolerance, feature, common_.vars_,0.0);
    double smooth = get<value_double>(sym, keys::smooth, feature, common_.vars_,false);
    bool has_dash = has_key<dash_array>(sym, keys::stroke_dasharray);

    if (clip)
    {
        double padding = (double)(common_.query_extent_.width()/pixmap_.width());
        double half_stroke = width/2.0;
        if (half_stroke > 1)
            padding *= half_stroke;
        if (std::fabs(offset) > 0)
            padding *= std::fabs(offset) * 1.2;
        padding *= common_.scale_factor_;
        clipping_extent.pad(padding);
    }

    vertex_converter<box2d<double>, grid_rasterizer, line_symbolizer,
                     CoordTransform, proj_transform, agg::trans_affine, conv_types, feature_impl>
        converter(clipping_extent,*ras_ptr,sym,common_.t_,prj_trans,tr,feature,common_.vars_,common_.scale_factor_);
    if (clip) converter.set<clip_line_tag>(); // optional clip (default: true)
    converter.set<transform_tag>(); // always transform
    if (std::fabs(offset) > 0.0) converter.set<offset_transform_tag>(); // parallel offset
    converter.set<affine_transform_tag>(); // optional affine transform
    if (simplify_tolerance > 0.0) converter.set<simplify_tag>(); // optional simplify converter
    if (smooth > 0.0) converter.set<smooth_tag>(); // optional smooth converter
    if (has_dash) converter.set<dash_tag>();
    converter.set<stroke_tag>(); //always stroke

    for ( geometry_type & geom : feature.paths())
    {
        if (geom.size() > 1)
        {
            converter.apply(geom);
        }
    }

    // render id
    ren.color(color_type(feature.id()));
    ras_ptr->filling_rule(agg::fill_non_zero);
    agg::render_scanlines(*ras_ptr, sl, ren);

    // add feature properties to grid cache
    pixmap_.add_feature(feature);

}
开发者ID:Jiangyangyang,项目名称:mapnik,代码行数:77,代码来源:process_line_symbolizer.cpp


示例13: ServerHandler

DWORD ServerHandler()
{

    bool running = true;

    // Socket handler
    SOCKET socketHnd;
    // Winsock data
    WSADATA wsaData;

    // Check for error
    if (WSAStartup(WSCK_V2, &wsaData))
    {
        errorFlags &= ERR_STARTUP;
        running = false;
    }

    // We want version 2
    if (wsaData.wVersion != WSCK_V2)
    {
        errorFlags &= ERR_WRONGVERSION;
        running = false;
    }

    // For TCP...
    SOCKADDR_IN sckAddr;
    sckAddr.sin_family = AF_INET;
    sckAddr.sin_port = htons(9009);	// Port 9009, will probably change to load from a config file later
    sckAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen from connections from ANY computer

    // Create the socket
    socketHnd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (socketHnd == INVALID_SOCKET)
    {
        errorFlags &= ERR_SOCKETERR;
        running = false;
    }

    if (bind(socketHnd, (LPSOCKADDR)&sckAddr, sizeof(sckAddr)) == SOCKET_ERROR)
    {
        errorFlags &= ERR_BINDERR;
        running = false;
    }

    if (running && errorFlags == 0)
    {
        MessageBoxA(NULL, "Server initialized, close this window to begin listening!", "Info", MB_ICONINFORMATION);
        // Listen with one backlog max
        listen(socketHnd, 1);
    }

    // player X and Y, 4 bytes at 0049E654 and 0049E658
    DWORD *playerX;
    DWORD *playerY;

    DWORD *playerMapID;

    PACKETHEADER PID;
    while (running)
    {
        playerX = (DWORD*)0x0049E654;
        playerY = (DWORD*)0x0049E658;

        playerMapID = (DWORD*)0x004A57F0;

        // Ctrl + F12 unloads the DLL
        if (GetKeyState(VK_CONTROL) && GetKeyState(VK_F12))
            running = false;

        // If polled to exit then stop running
        if (poll_exit)
            running = false;

        /*=========================================
        /* Data sending
        /*=========================================*/
        Buffer buf(13);	// 13 bytes in length
        buf.WriteByte(ID_LOC);
        buf.WriteInt((int)&playerX);
        buf.WriteInt((int)&playerY);
        buf.WriteInt((int)&playerMapID);

        send(socketHnd, (char*)buf.GetBytes(), buf.GetLength(), 0);
        //buf.Clear();

        Buffer buf2(80);
        // Pass the old buffer pointer
        recv(socketHnd, (char*)buf2.GetBytes(), sizeof(buf2.GetBytes())-1, 0);

        // Sleep to allow execution of other threads (and limit actions to about 30 FPS)
        Sleep(34);
    }

    //MessageBoxA(NULL, "test", "test", NULL);

    WSACleanup();

    //if (errorFlags > 0)
    //{
//.........这里部分代码省略.........
开发者ID:sampeto,项目名称:doukutsunetto,代码行数:101,代码来源:main.cpp


示例14: log_debug

void
LoadVariablesThread::completeLoad()
{
#ifdef DEBUG_LOAD_VARIABLES
    log_debug("completeLoad called");
#endif


	// TODO: how to set _bytesTotal ?

	// this is going to override any previous setting,
	// better do this inside a subclass (in a separate thread)
	_bytesLoaded = 0;
	_bytesTotal = _stream->size();

	std::string toparse;

	const size_t chunkSize = 1024;
	boost::scoped_array<char> buf(new char[chunkSize]);
	unsigned int parsedLines = 0;
	// TODO: use read_string ?
	while ( size_t bytesRead = _stream->read(buf.get(), chunkSize) )
	{
#ifdef DEBUG_LOAD_VARIABLES
            log_debug("Read %u bytes", bytesRead);
#endif

		if ( _bytesLoaded )
		{
			std::string chunk(buf.get(), bytesRead);
			toparse += chunk;
		}
		else
		{
			size_t dataSize = bytesRead;
			utf8::TextEncoding encoding;
			char* ptr = utf8::stripBOM(buf.get(), dataSize,
					encoding);
			if ( encoding != utf8::encUTF8 &&
			     encoding != utf8::encUNSPECIFIED )
			{
                  log_unimpl(_("%s to UTF8 conversion in "
					    "MovieClip.loadVariables "
                                         "input parsing"),
					    utf8::textEncodingName(encoding));
			}
			std::string chunk(ptr, dataSize);
			toparse += chunk;
		}

#ifdef DEBUG_LOAD_VARIABLES
		log_debug("toparse: %s", toparse);
#endif

		// parse remainder
		size_t lastamp = toparse.rfind('&');
		if ( lastamp != std::string::npos )
		{
			std::string parseable = toparse.substr(0, lastamp);
#ifdef DEBUG_LOAD_VARIABLES
			log_debug("parseable: %s", parseable);
#endif
			parse(parseable);
			toparse = toparse.substr(lastamp+1);
#ifdef DEBUG_LOAD_VARIABLES
			log_debug("toparse nextline: %s", toparse);
#endif
			++parsedLines;
		}

		_bytesLoaded += bytesRead;

		// eof, get out !
		if ( _stream->eof() ) break;

		if ( cancelRequested() ) {
                    log_debug("Cancelling LoadVariables download thread...");
			_stream.reset();
			return;
		}
	}

	if ( ! toparse.empty() ) {
		parse(toparse);
	}

	try {
		_stream->go_to_end();
	}
        catch (IOException& ex) {
        log_error(_("Stream couldn't seek to end: %s"), ex.what());
	}
	
    _bytesLoaded = _stream->tell();
	if ( _bytesTotal !=  _bytesLoaded ) {
            log_error(_("Size of 'variables' stream advertised to be %d bytes,"
                          " but turned out to be %d bytes."),
			_bytesTotal, _bytesLoaded);
		_bytesTotal = _bytesLoaded;
	}
//.........这里部分代码省略.........
开发者ID:ascendancy721,项目名称:gnash,代码行数:101,代码来源:LoadVariablesThread.cpp


示例15: size

void Vector<T>::append(const T *v, unsigned vSize) {
    unsigned oldSize = size();
    setSize(oldSize + vSize);
    memcpy(buf() + oldSize, v, vSize * sizeof(T));
}
开发者ID:preda,项目名称:pepper,代码行数:5,代码来源:Vector.cpp


示例16: buf

void RigidBody::SetNetAngularVelocityAttr(const PODVector<unsigned char>& value)
{
    float maxVelocity = physicsWorld_ ? physicsWorld_->GetMaxNetworkAngularVelocity() : DEFAULT_MAX_NETWORK_ANGULAR_VELOCITY;
    MemoryBuffer buf(value);
    SetAngularVelocity(buf.ReadPackedVector3(maxVelocity));
}
开发者ID:oda3174964,项目名称:Urho3D,代码行数:6,代码来源:RigidBody.cpp


示例17: sendReply

void sendReply ( void *state ) {

	StateStatsdb *st = (StateStatsdb *)state;

	if ( g_errno ) {
		g_httpServer.sendErrorReply(st->m_socket,
					    500,mstrerror(g_errno));
		return;
	}

	TcpSocket *s = st->m_socket;

	SafeBuf buf( 1024*32 , "tmpbuf0" );
	SafeBuf tmpBuf( 1024 , "tmpbuf1" );

	//
	// take these out until we need them!
	//
	/*
	// print the top of the page
	tmpBuf.safePrintf( 
			  //"<style type=\"text/css\">"
			  //"@import url(/styles/statsdb.css);</style>\n"
		"<script type=\"text/javascript\" "
		"src=\"/scr 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ buf2str函数代码示例发布时间:2022-05-30
下一篇:
C++ bucket函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap