bool Server_reader::put_encoded_data(Stream_buffer encoded, bool dont_parse_get_params){ POSEIDON_PROFILE_ME; m_queue.splice(encoded); bool has_next_request = true; do { const bool expecting_new_line = (m_size_expecting == content_length_expecting_endl); if(expecting_new_line){ std::ptrdiff_t lf_offset = 0; Stream_buffer::Enumeration_cookie cookie; for(;;){ const void *data, *pos; std::size_t size; if(!m_queue.enumerate_chunk(&data, &size, cookie)){ lf_offset = -1; break; } pos = std::memchr(data, '\n', size); if(pos){ lf_offset += static_cast<const char *>(pos) - static_cast<const char *>(data); break; } lf_offset += static_cast<std::ptrdiff_t>(size); } if(lf_offset < 0){ // 没找到换行符。 const AUTO(max_line_length, Main_config::get<std::size_t>("http_max_header_line_length", 8192)); POSEIDON_THROW_UNLESS(m_queue.size() <= max_line_length, Exception, status_bad_request); // XXX 用一个别的状态码? break; } m_size_expecting = static_cast<std::size_t>(lf_offset) + 1; } else { if(m_queue.size() < m_size_expecting){ break; } } AUTO(expected, m_queue.cut_off(boost::numeric_cast<std::size_t>(m_size_expecting))); if(expecting_new_line){ expected.unput(); // '\n' if(expected.back() == '\r'){ expected.unput(); } } switch(m_state){ boost::uint64_t temp64; case state_first_header: if(!expected.empty()){ m_request_headers = Request_headers(); m_content_length = 0; m_content_offset = 0; std::string line = expected.dump_string(); for(AUTO(it, line.begin()); it != line.end(); ++it){ const unsigned ch = static_cast<unsigned char>(*it); POSEIDON_THROW_UNLESS((0x20 <= ch) && (ch <= 0x7E), Basic_exception, Rcnts::view("Invalid HTTP request header")); } AUTO(pos, line.find(' ')); POSEIDON_THROW_UNLESS(pos != std::string::npos, Exception, status_bad_request); line.at(pos) = 0; m_request_headers.verb = get_verb_from_string(line.c_str()); POSEIDON_THROW_UNLESS(m_request_headers.verb != verb_invalid_verb, Exception, status_not_implemented); line.erase(0, pos + 1); pos = line.find(' '); POSEIDON_THROW_UNLESS(pos != std::string::npos, Exception, status_bad_request); m_request_headers.uri.assign(line, 0, pos); line.erase(0, pos + 1); long ver_end = 0; char ver_major_str[16], ver_minor_str[16]; POSEIDON_THROW_UNLESS(std::sscanf(line.c_str(), "HTTP/%15[0-9].%15[0-9]%ln", ver_major_str, ver_minor_str, &ver_end) == 2, Exception, status_bad_request); POSEIDON_THROW_UNLESS(static_cast<std::size_t>(ver_end) == line.size(), Exception, status_bad_request); m_request_headers.version = boost::numeric_cast<unsigned>(std::strtoul(ver_major_str, NULLPTR, 10) * 10000 + std::strtoul(ver_minor_str, NULLPTR, 10)); POSEIDON_THROW_UNLESS(m_request_headers.version <= 10001, Exception, status_version_not_supported); if(!dont_parse_get_params){ pos = m_request_headers.uri.find('?'); if(pos != std::string::npos){ Buffer_istream is; is.set_buffer(Stream_buffer(m_request_headers.uri.data() + pos + 1, m_request_headers.uri.size() - pos - 1)); url_decode_params(is, m_request_headers.get_params); m_request_headers.uri.erase(pos); } } m_size_expecting = content_length_expecting_endl; m_state = state_headers; } else { m_size_expecting = content_length_expecting_endl; // m_state = state_first_header; } break; case state_headers: if(!expected.empty()){ const AUTO(headers, m_request_headers.headers.size()); const AUTO(max_headers, Main_config::get<std::size_t>("http_max_headers_per_request", 64)); POSEIDON_THROW_UNLESS(headers <= max_headers, Exception, status_bad_request); // XXX 用一个别的状态码? std::string line = expected.dump_string(); AUTO(pos, line.find(':')); POSEIDON_THROW_UNLESS(pos != std::string::npos, Exception, status_bad_request); Rcnts key(line.data(), pos); line.erase(0, pos + 1); std::string value(trim(STD_MOVE(line))); m_request_headers.headers.append(STD_MOVE(key), STD_MOVE(value)); m_size_expecting = content_length_expecting_endl; // m_state = state_headers; } else { const AUTO_REF(transfer_encoding, m_request_headers.headers.get("Transfer-Encoding")); if(transfer_encoding.empty() || (::strcasecmp(transfer_encoding.c_str(), "identity") == 0)){ const AUTO_REF(content_length, m_request_headers.headers.get("Content-Length")); if(content_length.empty()){ m_content_length = 0; } else { char *eptr; m_content_length = ::strtoull(content_length.c_str(), &eptr, 10); POSEIDON_THROW_UNLESS(*eptr == 0, Exception, status_bad_request); POSEIDON_THROW_UNLESS(m_content_length <= content_length_max, Exception, status_payload_too_large); } } else if(::strcasecmp(transfer_encoding.c_str(), "chunked") == 0){ m_content_length = content_length_chunked; } else { POSEIDON_LOG_WARNING("Inacceptable Transfer-Encoding: ", transfer_encoding); POSEIDON_THROW(Basic_exception, Rcnts::view("Inacceptable Transfer-Encoding")); } on_request_headers(STD_MOVE(m_request_headers), m_content_length); if(m_content_length == content_length_chunked){ m_size_expecting = content_length_expecting_endl; m_state = state_chunk_header; } else { m_size_expecting = std::min<boost::uint64_t>(m_content_length, 4096); m_state = state_identity; } } break; case state_identity: temp64 = std::min<boost::uint64_t>(expected.size(), m_content_length - m_content_offset); if(temp64 > 0){ on_request_entity(m_content_offset, expected.cut_off(boost::numeric_cast<std::size_t>(temp64))); } m_content_offset += temp64; if(m_content_offset < m_content_length){ m_size_expecting = std::min<boost::uint64_t>(m_content_length - m_content_offset, 4096); // m_state = state_identity; } else { has_next_request = on_request_end(m_content_offset, VAL_INIT); m_size_expecting = content_length_expecting_endl; m_state = state_first_header; } break; case state_chunk_header: if(!expected.empty()){ m_chunk_size = 0; m_chunk_offset = 0; m_chunked_trailer.clear(); std::string line = expected.dump_string(); char *eptr; m_chunk_size = ::strtoull(line.c_str(), &eptr, 16); POSEIDON_THROW_UNLESS((*eptr == 0) || (*eptr == ' '), Exception, status_bad_request); POSEIDON_THROW_UNLESS(m_chunk_size <= content_length_max, Exception, status_payload_too_large); if(m_chunk_size == 0){ m_size_expecting = content_length_expecting_endl; m_state = state_chunked_trailer; } else { m_size_expecting = std::min<boost::uint64_t>(m_chunk_size, 4096); m_state = state_chunk_data; } } else { // chunk-data 后面应该有一对 CRLF。我们在这里处理这种情况。 m_size_expecting = content_length_expecting_endl; // m_state = state_chunk_header; } break; case state_chunk_data: temp64 = std::min<boost::uint64_t>(expected.size(), m_chunk_size - m_chunk_offset); assert(temp64 > 0); on_request_entity(m_content_offset, expected.cut_off(boost::numeric_cast<std::size_t>(temp64))); m_content_offset += temp64; m_chunk_offset += temp64; if(m_chunk_offset < m_chunk_size){ m_size_expecting = std::min<boost::uint64_t>(m_chunk_size - m_chunk_offset, 4096); // m_state = state_chunk_data; } else { m_size_expecting = content_length_expecting_endl; m_state = state_chunk_header; } break; case state_chunked_trailer: if(!expected.empty()){ std::string line = expected.dump_string(); AUTO(pos, line.find(':')); POSEIDON_THROW_UNLESS(pos != std::string::npos, Exception, status_bad_request); Rcnts key(line.data(), pos); line.erase(0, pos + 1); std::string value(trim(STD_MOVE(line))); m_chunked_trailer.append(STD_MOVE(key), STD_MOVE(value)); m_size_expecting = content_length_expecting_endl; // m_state = state_chunked_trailer; } else { has_next_request = on_request_end(m_content_offset, STD_MOVE(m_chunked_trailer)); m_size_expecting = content_length_expecting_endl; m_state = state_first_header; } break; } } while(has_next_request); return has_next_request; }
// Lookup a InflateVertData* from a Bvert: static InflateVertData* lookup(CBvert* v) { return v ? (InflateVertData*)v->find_data(key()) : 0; }
// ---------------------------------------------------------------------------- // delete keys/values // ---------------------------------------------------------------------------- bool wxRegKey::DeleteSelf() { { wxLogNull nolog; if ( !Open() ) { // it already doesn't exist - ok! return true; } } // prevent a buggy program from erasing one of the root registry keys or an // immediate subkey (i.e. one which doesn't have '\\' inside) of any other // key except HKCR (HKCR has some "deleteable" subkeys) if ( m_strKey.empty() || ((m_hRootKey != (WXHKEY) aStdKeys[HKCR].hkey) && (m_strKey.Find(REG_SEPARATOR) == wxNOT_FOUND)) ) { wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."), GetFullName(this)); return false; } // we can't delete keys while enumerating because it confuses GetNextKey, so // we first save the key names and then delete them all wxArrayString astrSubkeys; wxString strKey; long lIndex; bool bCont = GetFirstKey(strKey, lIndex); while ( bCont ) { astrSubkeys.Add(strKey); bCont = GetNextKey(strKey, lIndex); } size_t nKeyCount = astrSubkeys.Count(); for ( size_t nKey = 0; nKey < nKeyCount; nKey++ ) { wxRegKey key(*this, astrSubkeys[nKey]); if ( !key.DeleteSelf() ) return false; } // now delete this key itself Close(); // deleting a key which doesn't exist is not considered an error #if wxUSE_DYNLIB_CLASS wxDynamicLibrary dllAdvapi32(wxT("advapi32")); // Minimum supported OS for RegDeleteKeyEx: Vista, XP Pro x64, Win Server 2008, Win Server 2003 SP1 if(dllAdvapi32.HasSymbol(wxT("RegDeleteKeyEx"))) { typedef LONG (WINAPI *RegDeleteKeyEx_t)(HKEY, LPCTSTR, REGSAM, DWORD); wxDYNLIB_FUNCTION(RegDeleteKeyEx_t, RegDeleteKeyEx, dllAdvapi32); m_dwLastError = (*pfnRegDeleteKeyEx)((HKEY) m_hRootKey, m_strKey.t_str(), GetMSWViewFlags(m_viewMode), 0); // This parameter is reserved and must be zero. } else #endif // wxUSE_DYNLIB_CLASS { m_dwLastError = RegDeleteKey((HKEY) m_hRootKey, m_strKey.t_str()); } if ( m_dwLastError != ERROR_SUCCESS && m_dwLastError != ERROR_FILE_NOT_FOUND ) { wxLogSysError(m_dwLastError, _("Can't delete key '%s'"), GetName().c_str()); return false; } return true; }
bool isModifier(unsigned id) const { return id >= key(Shift) && id <= key(Super); }
void menu(int which) { key((char)which, 0, 0); }
//フレーム処理 void RuleMove::update() { key(); }
//------------------------------------------------------------------------------ void ClassDefinition::bindPropertyImpl( const char * name, const ObjectHandle & pBase, PropertyAccessor & o_PropertyAccessor ) const { if (!*name) { // empty name causes noop return; } // find property operator auto propOperator = name; while (true) { if( !*propOperator || *propOperator == INDEX_OPEN || *propOperator == DOT_OPERATOR ) { break; } propOperator += 1; } auto propName = name; auto propLength = propOperator - propName; auto baseProp = findProperty( propName, propLength ); if (baseProp == nullptr) { // error: property `propName` is not found o_PropertyAccessor.setBaseProperty( nullptr ); return; } o_PropertyAccessor.setObject( pBase ); o_PropertyAccessor.setBaseProperty( baseProp ); assert( strncmp( propName, o_PropertyAccessor.getName(), propLength ) == 0 ); if (!*propOperator) { // no operator, so that's it return; } Variant propVal = o_PropertyAccessor.getValue(); if (*propOperator == INDEX_OPEN) { auto wholeIndex = propOperator; // read "multidimensional" indices without recursive bind (optimization) while (true) { Collection collection; if (!propVal.tryCast( collection )) { // error: index operator is applicable to collections only o_PropertyAccessor.setBaseProperty( nullptr ); return; } // determine key type (heterogeneous keys are not supported yet) const auto begin = collection.begin(); const auto end = collection.end(); if (begin == end) { // error: can't index empty collection o_PropertyAccessor.setBaseProperty( nullptr ); return; } // read key Variant key( begin.key().type() ); { propOperator += 1; // skip INDEX_OPEN FixedMemoryStream dataStream( propOperator ); TextStream stream( dataStream ); stream >> key >> match( INDEX_CLOSE ); if (stream.fail()) { // error: either key can't be read, or it isn't followed by INDEX_CLOSE o_PropertyAccessor.setBaseProperty( nullptr ); return; } // skip key and closing bracket propOperator += stream.seek( 0, std::ios_base::cur ); } auto it = collection.find( key ); // If (it == end), still return a valid property accessor to end, // rather than an invalid property accessor. if (!*propOperator || (it == end)) { // name parsing is completed auto baseProp = std::make_shared< CollectionElementHolder >( collection, it, collection.valueType(), wholeIndex ); // o_PropertyAccessor.setObject(); - keep current base o_PropertyAccessor.setBaseProperty( baseProp ); return; } propVal = it.value(); if (*propOperator == INDEX_OPEN) { continue; } // parse next operator break; } }
WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &transaction) { QByteArray transaction_array; /* store serialized transaction */ if(isAnonymizeOnlyUnlocked()) { return AnonymizeOnlyUnlocked; } { LOCK2(cs_main, wallet->cs_wallet); CWalletTx *newTx = transaction.getTransaction(); QList<SendCoinsRecipient> recipients = transaction.getRecipients(); // Store PaymentRequests in wtx.vOrderForm in wallet. foreach(const SendCoinsRecipient &rcp, recipients) { if (rcp.paymentRequest.IsInitialized()) { std::string key("PaymentRequest"); std::string value; rcp.paymentRequest.SerializeToString(&value); newTx->vOrderForm.push_back(make_pair(key, value)); } else if (!rcp.message.isEmpty()) // Message from normal unpay:URI (unpay:XyZ...?message=example) { newTx->vOrderForm.push_back(make_pair("Message", rcp.message.toStdString())); } } CReserveKey *keyChange = transaction.getPossibleKeyChange(); transaction.getRecipients(); if(!wallet->CommitTransaction(*newTx, *keyChange, (recipients[0].useInstantX) ? "txlreq" : "tx")) return TransactionCommitFailed; CTransaction* t = (CTransaction*)newTx; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << *t; transaction_array.append(&(ssTx[0]), ssTx.size()); } // Add addresses / update labels that we've sent to to the address book, // and emit coinsSent signal for each recipient foreach(const SendCoinsRecipient &rcp, transaction.getRecipients()) { // Don't touch the address book when we have a payment request if (!rcp.paymentRequest.IsInitialized()) { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = CBitcoinAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { LOCK(wallet->cs_wallet); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end()) { wallet->SetAddressBook(dest, strLabel, "send"); } else if (mi->second.name != strLabel) { wallet->SetAddressBook(dest, strLabel, ""); // "" means don't change purpose } } } emit coinsSent(wallet, rcp, transaction_array); } return SendCoinsReturn(OK); }
/** * Expected input: * { * alg: "aes", * mode: "cbc", [or "ecb"] * key: key data, * iv: iv data (16 bytes), [if cbc mode] * input: data to encrypt or decrypt * } * * Good output: * { * output: data * } */ Json::Value AES::crypt(const std::string & algorithm, Json::Value & args, bool isEncrypt) { int mode; if (!args.isMember("key")) { throw std::string("key missing"); } if (!args.isMember("input")) { throw std::string("input missing"); } if (!args.isMember("mode")) { throw std::string("mode missing"); } std::string modeString( gsecrypto::util::lowerCaseRemoveDashes(args["mode"].asString())); if ("cbc" == modeString) { mode = SB_AES_CBC; if (!args.isMember("iv")) { throw std::string("iv required for CBC mode"); } } else if("ecb" == modeString) { mode = SB_AES_ECB; } else { throw std::string("Only CBC and ECB currently supported"); } DataTracker input; getData(args["input"], input); DataTracker result(input.dataLen); if (input.dataLen == 0) { Json::Value toReturn; toReturn["output"] = toJson(result); return toReturn; } DataTracker keyBytes; getData(args["key"], keyBytes); switch( keyBytes.dataLen*8 ) { case 128: case 192: case 256: break; default: std::stringstream stream; stream << "Key Size: " << (keyBytes.dataLen*8) << " bits not supported."; throw stream.str(); } if( (input.dataLen % 16) != 0 ) { throw std::string("Input not multiple of 128 bits. Use padding."); } AESParams params(*this, mode, SB_AES_128_BLOCK_BITS, false); AESKey key(params, keyBytes); DataTracker iv(SB_AES_128_BLOCK_BYTES); if( mode == SB_AES_CBC ) { getData(args["iv"], iv); if( iv.dataLen != SB_AES_128_BLOCK_BYTES ) { throw std::string("IV not 128 bits."); } } AESContext context(params, key, mode, iv); context.crypt(input, result, isEncrypt); Json::Value toReturn; toReturn["output"] = toJson(result); return toReturn; }
int main(int argc, char **argv) { int exitStatus(0); bool exit_program = false; std::string prefix(""); std::string homeDir(""); Ember::Application::ConfigMap configMap; #ifndef __WIN32__ if (argc > 1) { (argv)++; argc--; while (argc > 0) { std::string arg = std::string((char *) argv[0]); argv++; argc--; if (arg == "-v" || arg == "--version") { std::cout << "Ember version: " << VERSION << std::endl; exit_program = true; } else if (arg == "-h" || arg == "--help") { std::cout << "-h, --help - display this message" << std::endl; std::cout << "-v, --version - display version info" << std::endl; std::cout << "--home <path> - sets the home directory to something different than the default (~/.ember on *NIX systems, $APPDATA\\Ember on win32 systems)" << std::endl; std::cout << "-p <path>, --prefix <path> - sets the prefix to something else than the one set at compilation (only valid on *NIX systems)" << std::endl; std::cout << "--config <section>:<key> <value> - allows you to override config file settings. See the ember.conf file for examples. (~/.ember/ember.conf on *NIX systems)" << std::endl; exit_program = true; break; } else if (arg == "-p" || arg == "--prefix") { if (!argc) { std::cout << "You didn't supply a prefix."; exit_program = true; } else { prefix = std::string((char *) argv[0]); argv++; argc--; } } else if (arg == "--home") { if (!argc) { std::cout << "You didn't supply a home directory."; exit_program = true; } else { homeDir = std::string((char *) argv[0]); argv++; argc--; } } else if (arg == "--config") { if (argc < 2) { std::cout << "You didn't supply any config arguments."; } else { std::string fullkey(argv[0]); std::string value(argv[1]); Ember::Tokeniser tokeniser(fullkey, ":"); if (tokeniser.remainingTokens() != "") { std::string category(tokeniser.nextToken()); if (tokeniser.remainingTokens() != "") { std::string key(tokeniser.nextToken()); configMap[category][key] = value; } } } } } } #if !defined(__WIN32__) && !defined(__APPLE__) if (exit_program) { return 0; } #endif #ifdef ENABLE_BINRELOC if (prefix == "") { BrInitError error; if (br_init (&error) == 0 && error != BR_INIT_ERROR_DISABLED) { printf ("Warning: BinReloc failed to initialize (error code %d)\n", error); printf ("Will fallback to hardcoded default path.\n"); } char* br_prefixdir = br_find_prefix(PREFIX); const std::string prefixDir(br_prefixdir); free(br_prefixdir); prefix = prefixDir; } #endif // if (prefix == "") { // prefix = PREFIX; // } #else // char tmp[64]; // unsigned int floatSetting = _controlfp( 0, 0 ); //sprintf(tmp, "Original: 0x%.4x\n", floatSetting ); // MessageBox( 0, tmp, "floating point control", MB_OK | MB_ICONERROR | MB_TASKMODAL); //_fpreset(); //_controlfp(_PC_64, _MCW_PC); //_controlfp(_RC_NEAR , _MCW_RC); //floatSetting = _controlfp( 0, 0 ); //sprintf(tmp, "New: 0x%.4x\n", floatSetting ); // MessageBox( 0, tmp, "floating point control", MB_OK | MB_ICONERROR | MB_TASKMODAL); #endif try { //put the application object in its own scope so it gets destroyed before we signal all clear { // Create application object Ember::Application app(prefix, homeDir, configMap); //Ember::OgreView::EmberOgre app; std::cout << "Starting Ember version " << VERSION << std::endl; app.registerComponents(); // Initialize all Ember services needed for this application app.prepareComponents(); app.initializeServices(); app.start(); } } catch (const std::exception& ex) { std::cerr << "Unexpected error, aborting.\n\r\t" << ex.what() << std::endl; exitStatus = 1; } std::cout << "Ember shut down successfully." << std::endl; return exitStatus; }
std::string JsonReaderObjectImpl::get_name() const { auto it = m_json.begin(); return it.key().asString(); }
void RectMulticastStrategy::handleNewMulticastMessage(envelope *env) { ComlibPrintf("[%d] : In handleNewMulticastMessage\n", CkMyPe()); CkUnpackMessage(&env); int sender=env->getSrcPe(); int localElems; envelope *newenv; CkArrayIndex *local_idx_list; sinfo.unpack(env, localElems, local_idx_list, newenv); ComlibMulticastMsg *cbmsg = (ComlibMulticastMsg *)EnvToUsr(env); ComlibSectionHashKey key(cbmsg->_cookie.pe, cbmsg->_cookie.sInfo.cInfo.id); ComlibRectSectionHashObject *old_obj = NULL; old_obj = sec_ht.get(key); if(old_obj != NULL) { delete old_obj; } /* CkArrayIndex *idx_list_array = new CkArrayIndex[idx_list.size()]; for(int count = 0; count < idx_list.size(); count++) idx_list_array[count] = idx_list[count]; */ int cur_sec_id=cbmsg->_cookie.sInfo.cInfo.id; // need everyPe for rectangle not just local_idx_list ComlibMulticastMsg *lll = cbmsg; envelope *ppp = UsrToEnv(cbmsg); CkUnpackMessage(&ppp); int ttt=0; int uuu=0; for (int i=0; i<lll->nPes; ++i) { // ComlibPrintf(" %d (",lll->indicesCount[i].pe); uuu++; for (int j=0; j<lll->indicesCount[i].count; ++j) { // ComlibPrintf(" %d",((int*)&(lll->indices[ttt]))[1]); ttt++; } // ComlibPrintf(" )"); } ComlibPrintf("[%d] cbmsg for intermediate has %d indices %d pes\n",CkMyPe(),ttt, uuu); CkAssert(uuu>0); CkAssert(ttt>0); ComlibRectSectionHashObject *new_obj = createObjectOnIntermediatePe(ttt, cbmsg->indices, cbmsg->nPes, cbmsg->indicesCount, sender, cur_sec_id ); // now revise obj for local use only sinfo.getRemotePelist(localElems, local_idx_list, new_obj->npes, new_obj->pelist); sinfo.getLocalIndices(localElems, local_idx_list, new_obj->indices); sec_ht.put(key) = new_obj; CkPackMessage(&newenv); #ifndef LOCAL_MULTI_OFF localMulticast(newenv, new_obj); //local multicast always copies #endif CmiFree(newenv); //NEED this }
void RectMulticastStrategy::insertMessage(CharmMessageHolder *cmsg){ cmsg->checkme(); // ComlibPrintf("[%d] Comlib Rect Section Multicast: insertMessage \n", if(cmsg->dest_proc == IS_SECTION_MULTICAST && cmsg->sec_id != NULL) { CkSectionID *sid = cmsg->sec_id; int cur_sec_id = sid->getSectionID(); ComlibPrintf("[%d] Comlib Rect Section Multicast: insertMessage section id %d\n", CkMyPe(), cur_sec_id); if(cur_sec_id > 0) { sinfo.processOldSectionMessage(cmsg); // ComlibPrintf("[%d] insertMessage old sectionid %d \n",CkMyPe(),cur_sec_id); ComlibPrintf("[%d] insertMessage old sectionid %d \n",CkMyPe(),cur_sec_id); ComlibSectionHashKey key(CkMyPe(), sid->_cookie.sInfo.cInfo.id); ComlibRectSectionHashObject *obj = sec_ht.get(key); if(obj == NULL) CkAbort("Cannot Find Section\n"); envelope *env = UsrToEnv(cmsg->getCharmMessage()); #ifndef LOCAL_MULTI_OFF localMulticast(env, obj); #endif if(obj->sourceInRectangle) { remoteMulticast(env, obj); } else // forward { forwardMulticast(env, obj); } } else { ComlibPrintf("[%d] insertMessage new section id %d\n", CkMyPe(), cur_sec_id); //New sec id, so send it along with the message void *newmsg = sinfo.getNewMulticastMessage(cmsg, needSorting()); insertSectionID(sid); ComlibSectionHashKey key(CkMyPe(), sid->_cookie.sInfo.cInfo.id); ComlibPrintf("[%d] insertMessage new sectionid %d \n",CkMyPe(),sid->_cookie.sInfo.cInfo.id); ComlibRectSectionHashObject *obj = sec_ht.get(key); if(obj == NULL) CkAbort("Cannot Find Section\n"); /* ComlibPrintf("%u: Src = %d dest:", key.hash(), CkMyPe()); for (int i=0; i<obj->npes; ++i) ComlibPrintf(" %d",obj->pelist[i]); ComlibPrintf(", map:"); ComlibMulticastMsg *lll = (ComlibMulticastMsg*)newmsg; envelope *ppp = UsrToEnv(newmsg); CkUnpackMessage(&ppp); int ttt=0; for (int i=0; i<lll->nPes; ++i) { ComlibPrintf(" %d (",lll->indicesCount[i].pe); for (int j=0; j<lll->indicesCount[i].count; ++j) { ComlibPrintf(" %d",((int*)&(lll->indices[ttt]))[1]); ttt++; } ComlibPrintf(" )"); } CkPackMessage(&ppp); ComlibPrintf("\n"); */ // our object needs indices, npes, pelist sinfo.getRemotePelist(sid->_nElems, sid->_elems, obj->npes, obj->pelist); sinfo.getLocalIndices(sid->_nElems, sid->_elems, obj->indices); char *msg = cmsg->getCharmMessage(); /* ComlibMulticastMsg *lll = (ComlibMulticastMsg*)newmsg; envelope *ppp = UsrToEnv(newmsg); CkUnpackMessage(&ppp); int ttt=0; int uuu=0; for (int i=0; i<lll->nPes; ++i) { // ComlibPrintf(" %d (",lll->indicesCount[i].pe); uuu++; for (int j=0; j<lll->indicesCount[i].count; ++j) { // ComlibPrintf(" %d",((int*)&(lll->indices[ttt]))[1]); ttt++; } // ComlibPrintf(" )"); } ComlibPrintf("[%d] newmsg for sendRectDest has %d indices %d pes\n",CkMyPe(),ttt, uuu); CkAssert(uuu>0); CkAssert(ttt>0); */ envelope *ppp = UsrToEnv(newmsg); CkPackMessage(&ppp); #ifndef LOCAL_MULTI_OFF localMulticast(UsrToEnv(msg), obj); #endif sendRectDest(obj ,CkMyPe(), UsrToEnv(newmsg)); // CkFreeMsg(msg); // need this? } } else CkAbort("Section multicast cannot be used without a section proxy"); delete cmsg; }
int NotePlayHandle::midiKey() const { return key() - m_origBaseNote + instrumentTrack()->baseNote(); }
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; continue; } // transmittance if (token[0] == 'K' && token[1] == 't' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.transmittance[0] = r; material.transmittance[1] = g; material.transmittance[2] = b; continue; } // ior(index of refraction) if (token[0] == 'N' && token[1] == 'i' && isSpace((token[2]))) { token += 2; material.ior = parseFloat(token); continue; } // emission if(token[0] == 'K' && token[1] == 'e' && isSpace(token[2])) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.emission[0] = r; material.emission[1] = g; material.emission[2] = b; continue; } // shininess if(token[0] == 'N' && token[1] == 's' && isSpace(token[2])) { token += 2; material.shininess = parseFloat(token); continue; } // illum model if (0 == strncmp(token, "illum", 5) && isSpace(token[5])) { token += 6; material.illum = parseInt(token); continue; } // dissolve if ((token[0] == 'd' && isSpace(token[1]))) { token += 1; material.dissolve = parseFloat(token); continue; } if (token[0] == 'T' && token[1] == 'r' && isSpace(token[2])) { token += 2; material.dissolve = parseFloat(token); continue; } // ambient texture if ((0 == strncmp(token, "map_Ka", 6)) && isSpace(token[6])) { token += 7; material.ambient_texname = token; continue; } // diffuse texture if ((0 == strncmp(token, "map_Kd", 6)) && isSpace(token[6])) { token += 7; material.diffuse_texname = token; continue; } // specular texture if ((0 == strncmp(token, "map_Ks", 6)) && isSpace(token[6])) { token += 7; material.specular_texname = token; continue; } // normal texture if ((0 == strncmp(token, "map_Ns", 6)) && isSpace(token[6])) { token += 7; material.normal_texname = token; continue; } // unknown parameter const char* _space = strchr(token, ' '); if(!_space) { _space = strchr(token, '\t'); } if(_space) { int len = _space - token; std::string key(token, len); std::string value = _space + 1; material.unknown_parameter.insert(std::pair<std::string, std::string>(key, value)); } } // flush last material. material_map.insert(std::pair<std::string, material_t>(material.name, material)); return err.str(); }
/** * Callback used for search request */ static void search_request_cb(struct evhttp_request *req, void *arg) { std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now(); if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) { // evbuffer_add_printf(evb, "Invalid query request! Needs to be GET\n"); std::cerr << "Invalid query request! Needs to be GET" << std::endl; evhttp_send_error(req, HTTP_BADREQUEST, 0); } else { struct evbuffer *evb = NULL; const char *uri = evhttp_request_get_uri(req); struct evhttp_uri *decoded = NULL; // const char *path = NULL; const char *query = NULL; // struct evkeyvalq *headers; // struct evkeyval *header; printf("Got a GET request for %s\n", uri); // Decode the URI decoded = evhttp_uri_parse(uri); if (!decoded) { printf("It's not a good URI. Sending BADREQUEST\n"); evhttp_send_error(req, HTTP_BADREQUEST, 0); return; } // path = evhttp_uri_get_path(decoded); // std::cout << path << std::endl; query = evhttp_uri_get_query(decoded); // std::cout << query << std::endl; // This holds the content we're sending evb = evbuffer_new(); /* headers = evhttp_request_get_input_headers(req); for (header = headers->tqh_first; header; header = header->next.tqe_next) { printf(" %s: %s\n", header->key, header->value); } */ struct evkeyvalq params; // create storage for your key->value pairs struct evkeyval *param; // iterator int result = evhttp_parse_query_str(query, ¶ms); if (result == 0) { std::string query; unsigned int start = 0; unsigned int offset = 0; for (param = params.tqh_first; param; param = param->next.tqe_next) { std::string key(param->key); std::string value(param->value); // std::cout << key << " " << value << std::endl; if (key.compare(zsearch::server::GET_SEARCH_QUERY_KEY) == 0) { query = value; } if (key.compare(zsearch::server::GET_SEARCH_START_KEY) == 0) { try { start = ZUtil::getUInt(value); } catch (const string& e) { // do nothing } } if (key.compare(zsearch::server::GET_SEARCH_OFFSET_KEY) == 0) { try { offset = ZUtil::getUInt(value); } catch (const string& e) { // do nothing } } } std::cout << "searching for " << query << " with start " << start << " and offset " << offset << std::endl; auto docIdSet = engine->search(query, start, offset); if (docIdSet.size()) { for (auto docId : docIdSet) { evbuffer_add_printf(evb, "%u ", docId); } } evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/html"); evhttp_send_reply(req, 200, "OK", evb); } else { evhttp_send_error(req, HTTP_BADREQUEST, 0); } evhttp_clear_headers(¶ms); if (decoded) { evhttp_uri_free(decoded); } if (evb) { evbuffer_free(evb); } } std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); std::chrono::nanoseconds timeTaken = std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0); std::cout << ZUtil::printTimeTaken(timeTaken) << std::endl; }
bool migrate_manager::migrate_data_file(int db_id, vector<uint64_t> dest_servers) { bool flag = true; bool tag = false; md_info info; info.is_migrate = true; info.db_id = db_id; storage_mgr->begin_scan(info); vector<item_data_info*> items; bool have_item = storage_mgr->get_next_items(info, items); request_mupdate *packet = new request_mupdate(); packet->server_flag = TAIR_SERVERFLAG_MIGRATE; uint64_t total_count = 0; while(true) { if (!items.empty()) { total_count += items.size(); tag = true; for(vector<item_data_info *>::iterator itor = items.begin(); itor != items.end(); itor++) { item_data_info *item = *itor; data_entry key(item->m_data, item->header.keysize, false); key.data_meta = item->header; // skip embedded cache when migrating key.data_meta.flag = TAIR_CLIENT_PUT_SKIP_CACHE_FLAG; key.server_flag = TAIR_SERVERFLAG_MIGRATE; key.has_merged = true; if (item->header.magic == MAGIC_ITEM_META_LDB_PREFIX) key.set_prefix_size(item->header.prefixsize); data_entry value(item->m_data + item->header.keysize, item->header.valsize, false); value.data_meta = item->header; bool is_succuss = packet->add_put_key_data(key, value); log_debug("thiskey is %d", key.has_merged); if (!is_succuss) { flag = send_packet(dest_servers, packet, db_id); delete packet; packet = new request_mupdate(); packet->server_flag = TAIR_SERVERFLAG_MIGRATE; is_succuss = packet->add_put_key_data(key, value); assert(is_succuss); } } for(vector<item_data_info *>::iterator it = items.begin(); it < items.end(); it++) { free(*it); } items.clear(); } if(flag == false){ log_error("send migrate packet fail. bucket: %d", db_id); break; } if (have_item) { have_item = storage_mgr->get_next_items(info, items); } else { break; } } if (flag && tag) { flag = send_packet(dest_servers, packet, db_id); } delete packet; packet = NULL; storage_mgr->end_scan(info); log_warn("migrate bucket db data end. total count: %"PRI64_PREFIX"d, all_done: %d, send suc: %d", total_count, !have_item, flag); return flag; }
/** * Call back used for a POST request */ static void post_request_cb(struct evhttp_request *req, void *arg) { std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now(); /* bool isPostRequest = false; const char *cmdtype = NULL; switch (evhttp_request_get_command(req)) { case EVHTTP_REQ_GET: cmdtype = "GET"; break; case EVHTTP_REQ_POST: cmdtype = "POST"; isPostRequest = true; break; case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break; case EVHTTP_REQ_PUT: cmdtype = "PUT"; break; case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break; case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break; case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break; case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break; case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break; default: cmdtype = "unknown"; break; } if (!isPostRequest) { evhttp_send_error(req, HTTP_BADREQUEST, 0); } */ if (evhttp_request_get_command(req) != EVHTTP_REQ_POST) { std::cerr << "Invalid request! Needs to be POST" << std::endl; evhttp_send_error(req, HTTP_BADREQUEST, 0); } else { struct evbuffer *evb = NULL; struct evkeyvalq *headers; struct evkeyval *header; struct evbuffer *buf; printf("Received a POST request for %s\nHeaders:\n", evhttp_request_get_uri(req)); headers = evhttp_request_get_input_headers(req); for (header = headers->tqh_first; header; header = header->next.tqe_next) { printf(" %s: %s\n", header->key, header->value); } buf = evhttp_request_get_input_buffer(req); std::string postData; while (evbuffer_get_length(buf)) { int n; char cbuf[128]; n = evbuffer_remove(buf, cbuf, sizeof(buf)-1); if (n > 0) { // (void) fwrite(cbuf, 1, n, stdout); postData.append(cbuf, n); } } // std::cout << "Post data: " << std::endl << postData << std::endl; // do not remove this struct evkeyvalq params; // create storage for your key->value pairs struct evkeyval *param; // iterator // working code to return the parameters as plain text ... /* std::string postDataDecoded; if (result == 0) { for (param = params.tqh_first; param; param = param->next.tqe_next) { printf("%s %s\n", param->key, param->value); postDataDecoded.append(param->key); postDataDecoded.append(" "); postDataDecoded.append(param->value); postDataDecoded.append("\n"); } evb = evbuffer_new(); evbuffer_add_printf(evb, postDataDecoded.c_str()); evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/html"); evhttp_send_reply(req, 200, "OK", evb); } else { evhttp_send_error(req, HTTP_BADREQUEST, 0); } */ // working code to decode and index data int result = evhttp_parse_query_str(postData.c_str(), ¶ms); // if we were able to parse post data ok if (result == 0) { param = params.tqh_first; std::string key(param->key); std::string value(param->value); // std::cout << value << std::endl; evb = evbuffer_new(); // check that the first key is data if (key.compare(zsearch::server::POST_DATA_KEY) == 0) { try { std::shared_ptr<IDocument> document = std::make_shared<DocumentImpl>(value); unsigned int docId = engine->addDocument(document); std::cout << "Added document: " << docId << std::endl; evbuffer_add_printf(evb, "%d", docId); } catch (const std::string& e) { evbuffer_add_printf(evb, "Error parsing document. See documentation for more details\n"); evbuffer_add_printf(evb, "%s", e.c_str()); } catch (const std::exception& e) { evbuffer_add_printf(evb, "Error parsing document. See documentation for more details\n"); evbuffer_add_printf(evb, "%s", e.what()); } } else { evbuffer_add_printf(evb, "Invalid post data, first key must be in the form of data -> {xml}. See documentation for more details\n"); } evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/html"); evhttp_send_reply(req, 200, "OK", evb); } else { evhttp_send_error(req, HTTP_BADREQUEST, 0); } evhttp_clear_headers(¶ms); if (evb) { evbuffer_free(evb); } } std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); std::chrono::nanoseconds timeTaken = std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0); std::cout << ZUtil::printTimeTaken(timeTaken) << std::endl; }
Load::Load(QObject *parent) : QObject(parent), d_ptr(new LoadPrivate(this)) { Q_D(Load); ins = this; setObjectName("Load"); auto avProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); int sharp = task.code.indexOf(QRegularExpression("[#_]")); switch (task.state){ case None: { QString i = task.code.mid(2, sharp - 2); QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1); QString url("http://www.%1/video/av%2/"); url = url.arg(Utils::customUrl(Utils::Bilibili)).arg(i); if (!p.isEmpty()){ url += QString("index_%1.html").arg(p); } forward(QNetworkRequest(url), Page); break; } case Page: { d->model->clear(); QString api, id, video(reply->readAll()); int part = video.indexOf("<select"); if (part != -1 && sharp == -1){ QRegularExpression r("(?<=>).*?(?=</option>)"); QStringRef list(&video, part, video.indexOf("</select>", part) - part); QRegularExpressionMatchIterator i = r.globalMatch(list); api = "http://www.%1/video/%2/index_%3.html"; api = api.arg(Utils::customUrl(Utils::Bilibili)); while (i.hasNext()){ int index = d->model->rowCount() + 1; QStandardItem *item = new QStandardItem; item->setData(QUrl(api.arg(task.code).arg(index)), UrlRole); item->setData((task.code + "#%1").arg(index), StrRole); item->setData(Page, NxtRole); item->setData(Utils::decodeXml(i.next().captured()), Qt::EditRole); d->model->appendRow(item); } } if (d->model->rowCount() > 0){ emit stateChanged(task.state = Part); } else{ QRegularExpression r = QRegularExpression("cid[=\":]*\\d+", QRegularExpression::CaseInsensitiveOption); QRegularExpressionMatchIterator i = r.globalMatch(video); while (i.hasNext()){ QString m = i.next().captured(); m = QRegularExpression("\\d+").match(m).captured(); if (id.isEmpty()){ id = m; } else if (id != m){ id.clear(); break; } } if (!id.isEmpty()){ api = "http://comment.%1/%2.xml"; api = api.arg(Utils::customUrl(Utils::Bilibili)); forward(QNetworkRequest(api.arg(id)), File); } else{ emit stateChanged(203); qDebug() << "Fail to load danmaku, try biliApi"; dequeue(); } } break; } case File: { dumpDanmaku(reply->readAll(), Utils::Bilibili, false); emit stateChanged(task.state = None); dequeue(); break; } } }; auto avRegular = [](QString &code){ code.remove(QRegularExpression("/index(?=_\\d+\\.html)")); QRegularExpression r("a(v(\\d+([#_])?(\\d+)?)?)?"); r.setPatternOptions(QRegularExpression::CaseInsensitiveOption); return getRegular(r)(code); }; d->pool.append({ avRegular, 0, avProcess }); auto bbProcess = [this, avProcess](QNetworkReply *reply) { Q_D(Load); Task &task = d->queue.head(); switch (task.state) { case None: { QString i = task.code.mid(2); QString u = "http://www.%1/bangumi/i/%2/"; u = u.arg(Utils::customUrl(Utils::Bilibili)).arg(i); forward(QNetworkRequest(u), Page); break; } case Page: { d->model->clear(); QString page(reply->readAll()); QStringList list = page.split("<li data-index"); if (list.size() < 2) { emit stateChanged(task.state = None); dequeue(); break; } list.removeFirst(); QListIterator<QString> iter(list); iter.toBack(); while (iter.hasPrevious()) { QRegularExpression r; const QString &i = iter.previous(); r.setPattern("(?<=href=\")[^\"]+"); QString c = r.match(i).captured(); fixCode(c); r.setPattern("(?<=<span>).+(?=</span>)"); QString t = Utils::decodeXml(r.match(i).captured()); QStandardItem *item = new QStandardItem; item->setData(c, StrRole); item->setData(None, NxtRole); item->setData(t, Qt::EditRole); d->model->appendRow(item); } emit stateChanged(task.state = Part); } } }; auto bbRegular = [](QString &code) { code.replace(QRegularExpression("bangumi/i/(?=\\d+)"), "bb"); QRegularExpression r("b(b(\\d+)?)?"); r.setPatternOptions(QRegularExpression::CaseInsensitiveOption); return getRegular(r)(code); }; d->pool.append({ bbRegular, 0, bbProcess }); auto acProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); int sharp = task.code.indexOf(QRegularExpression("[#_]")); switch (task.state){ case None: { QString i = task.code.mid(2, sharp - 2); QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1); QString url("http://www.%1/v/ac%2"); url = url.arg(Utils::customUrl(Utils::AcFun)).arg(i); if (!p.isEmpty()){ url += QString("_%1").arg(p); } forward(QNetworkRequest(url), Page); break;; } case Page: { d->model->clear(); QRegularExpressionMatchIterator match = QRegularExpression("data-vid.*?</a>").globalMatch(reply->readAll()); while (match.hasNext()){ QStandardItem *item = new QStandardItem; QString part = match.next().captured(); QRegularExpression r; r.setPattern("(?<=>)[^>]+?(?=</a>)"); item->setData(Utils::decodeXml(r.match(part).captured()), Qt::EditRole); r.setPattern("(?<=data-vid=\").+?(?=\")"); QString next("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1"); next = next.arg(Utils::customUrl(Utils::AcFun)).arg(r.match(part).captured()); item->setData(next, UrlRole); item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole); item->setData(File, NxtRole); d->model->appendRow(item); } if (sharp == -1 && d->model->rowCount() >= 2){ emit stateChanged(task.state = Part); } else{ int i = sharp == -1 ? 0 : task.code.mid(sharp + 1).toInt() - 1; if (i >= 0 && i < d->model->rowCount()){ forward(QNetworkRequest(d->model->item(i)->data(UrlRole).toUrl()), File); } else{ emit stateChanged(203); dequeue(); } } break; } case File: { QByteArray data = reply->readAll(); if (data != "[[],[],[]]"){ QNetworkRequest &request = task.request; QUrl url = request.url(); int page = QUrlQuery(url).queryItemValue("pageNo").toInt(); url.setQuery(QString()); request.setUrl(url); dumpDanmaku(data, Utils::AcFun, false); QUrlQuery query; query.addQueryItem("pageSize", "1000"); query.addQueryItem("pageNo", QString::number(page + 1)); url.setQuery(query); request.setUrl(url); forward(request, File); } else{ emit stateChanged(task.state = None); dequeue(); } break; } } }; auto acRegular = getRegular(QRegularExpression("a(c(\\d+([#_])?(\\d+)?)?)?", QRegularExpression::CaseInsensitiveOption)); d->pool.append({ acRegular, 0, acProcess }); auto abProcess = [this, acProcess](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); int sharp = task.code.indexOf(QRegularExpression("[#_]")); switch (task.state){ case None: { QString url("http://www.%1/bangumi/video/page?bangumiId=%2&pageSize=30&pageNo=%3&order=2"); url = url.arg(Utils::customUrl(Utils::AcFun)).arg(task.code.mid(2, sharp - 2)); url = url.arg(sharp == -1 ? 1 : (task.code.mid(sharp + 1).toInt() - 1) / 30 + 1); forward(QNetworkRequest(url), Page); break; } case Page: { if (sharp != -1){ QJsonObject data = QJsonDocument::fromJson(reply->readAll()).object()["data"].toObject(); int i = task.code.mid(sharp + 1).toInt(); if (i > 0){ i = (i - 1) % 30; } else{ i = data["totalCount"].toInt(); if (i > 30){ task.code = task.code.left(sharp) + QString("#%1").arg(i); task.state = None; task.processer->process(nullptr); break; } } QJsonArray list = data["list"].toArray(); if (i < 0 || i >= list.size()){ emit stateChanged(203); dequeue(); break; } QString head("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1"); head = head.arg(Utils::customUrl(Utils::AcFun)); head = head.arg(list[i].toObject()["danmakuId"].toString()); forward(QNetworkRequest(head), File); break; } else{ d->model->clear(); } } case Part: { QJsonObject info = QJsonDocument::fromJson(reply->readAll()).object(); if (!info["success"].toBool() && d->model->rowCount() == 0){ emit stateChanged(info["status"].toInt()); dequeue(); } QJsonObject data = info["data"].toObject(); for (const QJsonValue &value : data["list"].toArray()){ QStandardItem *item = new QStandardItem; QJsonObject data = value.toObject(); item->setData(data["title"].toString(), Qt::EditRole); QString head("http://static.comment.%1/V2/%2?pageSize=1000&pageNo=1"); head = head.arg(Utils::customUrl(Utils::AcFun)).arg(data["danmakuId"].toString()); item->setData(head, UrlRole); item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole); item->setData(File, NxtRole); d->model->appendRow(item); } if (task.state != Part){ emit stateChanged(task.state = Part); } if (data["pageNo"].toInt() < data["totalPage"].toInt()){ QUrl url = reply->request().url(); auto arg = QUrlQuery(url).queryItems(); for (auto &p : arg){ if (p.first == "pageNo"){ p.second = QString::number(p.second.toInt() + 1); break; } } QUrlQuery query; query.setQueryItems(arg); url.setQuery(query); d->remain.insert(d->manager.get(QNetworkRequest(url))); } break; } case File: { acProcess(reply); break; } } }; auto abRegular = getRegular(QRegularExpression("a(b(\\d+([#_])?(\\d+)?)?)?", QRegularExpression::CaseInsensitiveOption)); d->pool.append({ abRegular, 0, abProcess }); auto ccProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); int sharp = task.code.indexOf(QRegularExpression("[#_]")); switch (task.state){ case None: { QString i = task.code.mid(2, sharp - 2); QString p = sharp == -1 ? QString() : task.code.mid(sharp + 1); QString url("http://www.%1/play/h%2/"); url = url.arg(Utils::customUrl(Utils::TuCao)).arg(i); if (!p.isEmpty()){ url += QString("#%1").arg(p); } forward(QNetworkRequest(url), Page); break; } case Page: { QString page = reply->readAll(); d->model->clear(); QRegularExpressionMatch m; QRegularExpression r("(?<=<li>)[^<]*(?=</li>)"); m = r.match(page, page.indexOf("<ul id=\"player_code\"")); QStringList list = m.captured().split("**"); m = r.match(page, m.capturedEnd()); QString code = m.captured(); for (const QString &iter : list){ QStandardItem *item = new QStandardItem; item->setData(iter.mid(iter.indexOf('|') + 1), Qt::EditRole); QString api("http://www.%1/index.php?m=mukio&c=index&a=init&playerID=%2"); api = api.arg(Utils::customUrl(Utils::TuCao)).arg((code + "-%1").arg(d->model->rowCount())); item->setData(api, UrlRole); item->setData((task.code + "#%1").arg(d->model->rowCount() + 1), StrRole); item->setData(File, NxtRole); d->model->appendRow(item); } if (sharp == -1 && d->model->rowCount() >= 2){ emit stateChanged(task.state = Part); } else{ int i = sharp == -1 ? 0 : task.code.mid(sharp + 1).toInt() - 1; if (i >= 0 && i < d->model->rowCount()){ forward(QNetworkRequest(d->model->item(i)->data(UrlRole).toUrl()), File); } else{ emit stateChanged(203); dequeue(); } } break; } case File: { dumpDanmaku(reply->readAll(), Utils::TuCao, false); emit stateChanged(task.state = None); dequeue(); break; } } }; auto ccRegular = [](QString &code){ code.replace(QRegularExpression("[Hh](?=\\d)"), "cc"); QRegularExpression r("c(c(\\d+([#_])?(\\d+)?)?)?"); r.setPatternOptions(QRegularExpression::CaseInsensitiveOption); return getRegular(r)(code); }; d->pool.append({ ccRegular, 0, ccProcess }); d->pool.append(Proc()); Proc *directProc = &d->pool.last(); directProc->process = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); switch (task.state){ case None: { QUrl url = QUrl::fromUserInput(task.code); task.request.setUrl(url); task.state = File; forward(); break; } case File: { Record load; QUrl url = reply->url(); QByteArray data(reply->readAll()); load.source = url.url(); load.access = url.isLocalFile() ? url.toLocalFile() : load.source; load.string = QFileInfo(task.code).fileName(); load.delay = task.delay; QString head = Utils::decodeTxt(data.left(512)); if (head.startsWith("[Script Info]")){ load.danmaku = Parse::parseComment(data, Utils::ASS); } else if (!head.startsWith("<?xml")){ load.danmaku = Parse::parseComment(data, Utils::AcFun); } else if (head.indexOf("<packet>") != -1){ load.danmaku = Parse::parseComment(data, Utils::Niconico); } else if (head.indexOf("<i>") != -1){ load.danmaku = Parse::parseComment(data, Utils::Bilibili); QString i = QRegularExpression("(?<=<chatid>)\\d+(?=</chatid>)").match(head).captured(); if (!i.isEmpty()){ load.source = "http://comment.%1/%2.xml"; load.source = load.source.arg(Utils::customUrl(Utils::Bilibili)).arg(i); } } else if (head.indexOf("<c>") != -1){ load.danmaku = Parse::parseComment(data, Utils::AcfunLocalizer); } if (load.delay != 0){ for (Comment &c : load.danmaku){ c.time += load.delay; } } Danmaku::instance()->appendToPool(&load); emit stateChanged(task.state = None); dequeue(); break; } } }; directProc->priority = -100; directProc->regular = [this, directProc](QString &code){ if (code.startsWith("full?") || code.startsWith("hist?")){ code.clear(); return false; } QUrl u = QUrl::fromUserInput(code); if (!u.host().isEmpty() && !u.path().isEmpty()){ return true; } if (QFileInfo(code).exists()){ return true; } code.clear(); return false; }; auto fullBiProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); switch (task.state) { case None: { emit progressChanged(0); QString api("http://comment.%1/rolldate,%2"); api = api.arg(Utils::customUrl(Utils::Bilibili)); task.code = QUrlQuery(task.code.mid(5)).queryItemValue("source"); forward(QNetworkRequest(api.arg(QFileInfo(task.code).baseName())), Page); break; } case Page: { QByteArray data = reply->readAll(); QJsonArray date = QJsonDocument::fromJson(data).array(); if (date.isEmpty()) { emit stateChanged(203); dequeue(); break; } QJsonObject head = date.first().toObject(); QString url("http://comment.%1/dmroll,%2,%3"); url = url.arg(Utils::customUrl(Utils::Bilibili)); url = url.arg(head["timestamp"].toVariant().toInt()); url = url.arg(QFileInfo(task.code).baseName()); QNetworkRequest request(url); request.setAttribute(QNetworkRequest::User, data); forward(request, Code); break; } case Code: { QByteArray data = task.request.attribute(QNetworkRequest::User).toByteArray(); QJsonArray date = QJsonDocument::fromJson(data).array(); QMap<int, int> count; for (auto iter : date) { QJsonObject item = iter.toObject(); count[item["timestamp"].toVariant().toInt()] += item["new"].toVariant().toInt(); } data = reply->readAll(); if (count.size() >= 2) { int max = QRegularExpression("(?<=\\<max_count\\>).+(?=\\</max_count\\>)").match(data).captured().toInt(); int now = 0; auto getHistory = [d, &count, &task](int date) { QString url("http://comment.%1/dmroll,%2,%3"); url = url.arg(Utils::customUrl(Utils::Bilibili)); url = url.arg(date); url = url.arg(QFileInfo(task.code).baseName()); return d->manager.get(QNetworkRequest(url)); }; for (auto iter = count.begin() + 1;; ++iter) { now += iter.value(); if (iter + 1 == count.end()) { d->remain += getHistory(iter.key()); break; } else if (now + (iter + 1).value() > max) { d->remain += getHistory(iter.key()); now = 0; } } auto pool = QSharedPointer<QVector<Parse::ResultDelegate>>::create(); pool->append(Parse::parseComment(data, Utils::Bilibili)); double total = d->remain.size() + 2; for (QNetworkReply *iter : d->remain) { connect(iter, &QNetworkReply::finished, [=, &task]() { QByteArray data = iter->readAll(); pool->append(Parse::parseComment(data, Utils::Bilibili)); switch (iter->error()) { case QNetworkReply::NoError: emit progressChanged((total - d->remain.size()) / total); case QNetworkReply::OperationCanceledError: if (d->remain.isEmpty() && !pool->empty()) { Record load; load.full = true; for (auto &iter : *pool) { load.danmaku.append(iter); } load.source = task.code; Danmaku::instance()->appendToPool(&load); emit stateChanged(task.state = None); dequeue(); } default: break; } }); } emit progressChanged(2 / total); emit stateChanged(task.state = File); break; } else { emit progressChanged(1); dumpDanmaku(data, Utils::Bilibili, true); emit stateChanged(task.state = None); dequeue(); break; } } } }; auto fullBiRegular = QRegularExpression("^full\\?source=http://comment\\.bilibili\\.com/\\d+\\.xml$"); fullBiRegular.setPatternOptions(QRegularExpression::CaseInsensitiveOption); d->pool.append({ getRegular(fullBiRegular), 100, fullBiProcess }); auto histBiProcess = [this](QNetworkReply *reply){ Q_D(Load); Task &task = d->queue.head(); switch (task.state){ case None: { QUrlQuery query(task.code.mid(5)); task.code = query.queryItemValue("source"); QString cid = QFileInfo(task.code).baseName(); QString dat = query.queryItemValue("date"); QString url; QNetworkRequest request; if (dat != "0" && dat.toUInt() != QDateTime(QDate::currentDate()).toTime_t()){ url = QString("http://comment.%1/dmroll,%2,%3"); url = url.arg(Utils::customUrl(Utils::Bilibili)); url = url.arg(dat).arg(cid); int limit = QDateTime(QDateTime::fromTime_t(dat.toInt()).date().addDays(1)).toTime_t(); request.setAttribute(QNetworkRequest::User, limit); } else{ url = QString("http://comment.%1/%2.xml").arg(Utils::customUrl(Utils::Bilibili)); url = url.arg(cid); } request.setUrl(url); forward(request, File); break; } case File: { Record load; load.danmaku = Parse::parseComment(reply->readAll(), Utils::Bilibili); load.source = task.code; for (Record &iter : Danmaku::instance()->getPool()){ if (iter.source == load.source){ iter.full = false; iter.danmaku.clear(); iter.limit = 1; break; } } load.limit = task.request.attribute(QNetworkRequest::User).toInt(); Danmaku::instance()->appendToPool(&load); emit stateChanged(task.state = None); dequeue(); break; } } }; auto histBiRegular = QRegularExpression("^hist\\?source=http://comment\\.bilibili\\.com/\\d+\\.xml&date=\\d+$"); histBiRegular.setPatternOptions(QRegularExpression::CaseInsensitiveOption); d->pool.append({ getRegular(histBiRegular), 100, histBiProcess }); connect(this, &Load::stateChanged, [this](int code){ switch (code){ case None: case Page: case Part: case Code: case File: break; default: { Q_D(Load); if (!d->tryNext()){ emit errorOccured(code); } break; } } }); }
/** * Callback used for doc request */ static void doc_request_cb(struct evhttp_request *req, void *arg) { std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now(); if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) { std::cerr << "Invalid query request! Needs to be GET" << std::endl; evhttp_send_error(req, HTTP_BADREQUEST, 0); } else { struct evbuffer *evb = NULL; const char *uri = evhttp_request_get_uri(req); struct evhttp_uri *decoded = NULL; // const char *path = NULL; const char *query = NULL; printf("Got a GET request for %s\n", uri); // Decode the URI decoded = evhttp_uri_parse(uri); if (!decoded) { printf("It's not a good URI. Sending BADREQUEST\n"); evhttp_send_error(req, HTTP_BADREQUEST, 0); return; } // path = evhttp_uri_get_path(decoded); // std::cout << path << std::endl; query = evhttp_uri_get_query(decoded); // std::cout << query << std::endl; // This holds the content we're sending evb = evbuffer_new(); struct evkeyvalq params; // create storage for your key->value pairs struct evkeyval *param; // iterator int result = evhttp_parse_query_str(query, ¶ms); if (result == 0) { bool found = false; for (param = params.tqh_first; param; param = param->next.tqe_next) { std::string key(param->key); std::string value(param->value); // printf("%s %s\n", key.c_str(), value.c_str()); if (key.compare(zsearch::server::DOC_ID_KEY) == 0) { unsigned int docId = 0; try { docId = ZUtil::getUInt(value); std::cout << "retrieving document " << value << std::endl; std::shared_ptr<IDocument> document = make_shared<DocumentImpl>(); if (engine->getDoc(docId, document)) { std::stringstream ss; document->write(ss); const std::string docStr = ss.str(); // cout << docStr << endl; evbuffer_add(evb, docStr.data(), docStr.size()); found = true; } } // TODO: consider splitting out the errors so we know if the problem is getting the docId or in the engine catch (const std::string& e) { // no need to do anything here // evbuffer_add_printf(evb, "Invalid docId\n"); // evbuffer_add_printf(evb, e.c_str()); } break; // break out of looping through parameters } } if (found) { evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/xml"); evhttp_send_reply(req, 200, "OK", evb); } else { /* evbuffer_add_printf(evb, "Document not found or invalid docId"); evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/html"); */ evhttp_send_error(req, 404, "Document not found."); } } else { evhttp_send_error(req, HTTP_BADREQUEST, 0); } evhttp_clear_headers(¶ms); if (decoded) { evhttp_uri_free(decoded); } if (evb) { evbuffer_free(evb); } } std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); std::chrono::nanoseconds timeTaken = std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0); std::cout << ZUtil::printTimeTaken(timeTaken) << std::endl; }
bool isKey(unsigned id) const { return id >= key(Escape) && id <= key(Menu); }
std::shared_ptr<node::Node> VolumeLoader::create_volume_from_file(std::string const& node_name, std::string const& file_name, unsigned flags) { std::shared_ptr<node::Node> cached_node; std::string key(file_name + "_" + string_utils::to_string(flags)); auto searched(loaded_files_.find(key)); if (searched != loaded_files_.end()) { cached_node = searched->second; } else { std::ifstream f(file_name.c_str()); if (!f.good()) { f.close(); Logger::LOG_WARNING << "Unable to load " << file_name << ": File does not exist!" << std::endl; return std::make_shared<node::TransformNode>(node_name); } f.close(); if (is_supported(file_name)) { cached_node = load(file_name, flags); cached_node->update_cache(); loaded_files_.insert(std::make_pair(key, cached_node)); // normalize volume position and rotation if (flags & VolumeLoader::NORMALIZE_POSITION || flags & VolumeLoader::NORMALIZE_SCALE) { auto bbox = cached_node->get_bounding_box(); if (flags & VolumeLoader::NORMALIZE_POSITION) { auto center((bbox.min + bbox.max)*0.5); cached_node->translate(-center); } if (flags & VolumeLoader::NORMALIZE_SCALE) { auto size(bbox.max - bbox.min); auto max_size(std::max(std::max(size.x, size.y), size.z)); cached_node->scale(1.f / max_size); } } } if (!cached_node) { Logger::LOG_WARNING << "Unable to load " << file_name << ": Volume Type is not supported!" << std::endl; } } if (cached_node) { auto copy(cached_node->deep_copy()); copy->set_name(node_name); return copy; } return std::make_shared<node::TransformNode>(node_name); }
// Get state nodes from a ledger // Inputs: // limit: integer, maximum number of entries // marker: opaque, resume point // binary: boolean, format // Outputs: // ledger_hash: chosen ledger's hash // ledger_index: chosen ledger's index // state: array of state nodes // marker: resume point, if any Json::Value doLedgerData (RPC::Context& context) { std::shared_ptr<ReadView const> lpLedger; auto const& params = context.params; auto jvResult = RPC::lookupLedger(lpLedger, context); if (!lpLedger) return jvResult; boost::optional<ReadView::key_type> key = ReadView::key_type(); if (params.isMember (jss::marker)) { Json::Value const& jMarker = params[jss::marker]; if (! (jMarker.isString () && key->SetHex (jMarker.asString ()))) return RPC::expected_field_error (jss::marker, "valid"); } bool isBinary = params[jss::binary].asBool(); int limit = -1; if (params.isMember (jss::limit)) { Json::Value const& jLimit = params[jss::limit]; if (!jLimit.isIntegral ()) return RPC::expected_field_error (jss::limit, "integer"); limit = jLimit.asInt (); } auto maxLimit = RPC::Tuning::pageLength(isBinary); if ((limit < 0) || ((limit > maxLimit) && (! isUnlimited (context.role)))) limit = maxLimit; jvResult[jss::ledger_hash] = to_string (lpLedger->info().hash); jvResult[jss::ledger_index] = lpLedger->info().seq; Json::Value& nodes = jvResult[jss::state]; auto e = lpLedger->sles.end(); for (auto i = lpLedger->sles.upper_bound(*key); i != e; ++i) { auto sle = lpLedger->read(keylet::unchecked((*i)->key())); if (limit-- <= 0) { // Stop processing before the current key. auto k = sle->key(); jvResult[jss::marker] = to_string(--k); break; } if (isBinary) { Json::Value& entry = nodes.append (Json::objectValue); entry[jss::data] = serializeHex(*sle); entry[jss::index] = to_string(sle->key()); } else { Json::Value& entry = nodes.append (sle->getJson (0)); entry[jss::index] = to_string(sle->key()); } } return jvResult; }
bool CVolumeDescriptionEnumeratorThread::GetDrives() { long drivesToHide = 0; // Adhere to the NODRIVES group policy wxRegKey key(_T("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer")); if (key.Exists()) { if (!key.HasValue(_T("NoDrives")) || !key.QueryValue(_T("NoDrives"), &drivesToHide)) drivesToHide = 0; } int len = GetLogicalDriveStrings(0, 0); if (!len) return false; wxChar* drives = new wxChar[len + 1]; if (!GetLogicalDriveStrings(len, drives)) { delete [] drives; return false; } const wxChar* drive_a = 0; const wxChar* pDrive = drives; while (*pDrive) { if (m_stop) { delete [] drives; return false; } // Check if drive should be hidden by default if (pDrive[0] != 0 && pDrive[1] == ':') { int bit = 0; char letter = pDrive[0]; if (letter >= 'A' && letter <= 'Z') bit = 1 << (letter - 'A'); if (letter >= 'a' && letter <= 'z') bit = 1 << (letter - 'a'); if (drivesToHide & bit) { pDrive += wxStrlen(pDrive) + 1; continue; } } const int len = wxStrlen(pDrive); if ((pDrive[0] == 'a' || pDrive[0] == 'A') && !drive_a) { // Defer processing of A:, most commonly the slowest of all drives. drive_a = pDrive; pDrive += len + 1; continue; } if (GetDrive(pDrive, len)) { wxCommandEvent evt(fzEVT_VOLUMEENUMERATED); m_pEvtHandler->AddPendingEvent(evt); } pDrive += len + 1; } if (drive_a) { const int len = wxStrlen(drive_a); if (GetDrive(drive_a, len)) { wxCommandEvent evt(fzEVT_VOLUMEENUMERATED); m_pEvtHandler->AddPendingEvent(evt); } } delete [] drives; return true; }
void ExtraCompiler::forEachTarget(std::function<void (const Utils::FileName &)> func) { for (auto it = d->contents.constBegin(), end = d->contents.constEnd(); it != end; ++it) func(it.key()); }
void ConfigManager::Set(const wxString& name) { wxString key(name); TiXmlElement* e = AssertPath(key); GetUniqElement(e, key); }
void State::applyUniformsMappings() { if (m_materials.isEmpty()) return; Material& mat = *m_materials.back(); /// @todo should maybe work without shaders if (!mat.prog()) return; GLProgram& prog = *mat.prog(); CameraPtr c = camera(); for (auto it = mat.uniformMap().begin(); it != mat.uniformMap().end(); ++it) { const MappableValue& map = *it; bool ok = true; if (map.src() == "model") { if (map.var() == "transform") setUniform(prog, it.key(), model()); else if (map.var() == "modelview" && c) { glm::mat4 m = (c->view() * model()); prog.setUniform(this, it.key(), m); } else ok = false; } else if (map.src() == "material") { if (map.var() == "diffuse") setUniformSel(this, prog, it.key(), mat.colors.diffuse, map.select()); else if (map.var() == "ambient") setUniformSel(this, prog, it.key(), mat.colors.ambient, map.select()); else if (map.var() == "specular") setUniformSel(this, prog, it.key(), mat.colors.specular, map.select()); else if (map.var() == "transparent") setUniformSel(this, prog, it.key(), mat.colors.transparent, map.select()); else if (map.var() == "emissive") setUniformSel(this, prog, it.key(), mat.colors.emissive, map.select()); else if (map.var() == "wireframe") prog.setUniform(this, it.key(), mat.style.wireframe); else if (map.var() == "twosided") prog.setUniform(this, it.key(), mat.style.twosided); else if (map.var() == "opacity") prog.setUniform(this, it.key(), mat.style.opacity); else if (map.var() == "shininess") prog.setUniform(this, it.key(), mat.style.shininess); else if (map.var() == "shininess_strength") prog.setUniform(this, it.key(), mat.style.shininess_strength); else if (map.var() == "refracti") prog.setUniform(this, it.key(), mat.style.refracti); else ok = false; } else if (map.src() == "scene") { if (map.var() == "size") setUniformSel(this, prog, it.key(), glm::vec2(m_scene.width(), m_scene.height()), map.select()); else if (map.var() == "time") prog.setUniform(this, it.key(), m_time); else if (map.var() == "dt") prog.setUniform(this, it.key(), m_dt); else ok = false; } else if (map.src() == "camera" && c) { if (map.var() == "target") setUniformSel(this, prog, it.key(), c->target(), map.select()); else if (map.var() == "up") setUniformSel(this, prog, it.key(), c->up(), map.select()); else if (map.var() == "right") setUniformSel(this, prog, it.key(), c->right(), map.select()); else if (map.var() == "front") setUniformSel(this, prog, it.key(), c->front(), map.select()); else if (map.var() == "view") setUniform(prog, it.key(), c->view()); else if (map.var() == "projection") prog.setUniform(this, it.key(), c->projection()); else if (map.var() == "dist") prog.setUniform(this, it.key(), c->dist()); else if (map.var() == "fov") prog.setUniform(this, it.key(), c->fov()); else if (map.var() == "near") prog.setUniform(this, it.key(), c->near()); else if (map.var() == "far") prog.setUniform(this, it.key(), c->far()); else if (map.var() == "size") setUniformSel(this, prog, it.key(), glm::vec2(c->width(), c->height()), map.select()); else ok = false; } else if (map.src() == "lights" || map.src() == "light") { if (map.var() == "ambient") assignVector(this, prog, it.key(), map, m_data.back().m_lights, &Light::ambient); else if (map.var() == "diffuse") assignVector(this, prog, it.key(), map, m_data.back().m_lights, &Light::diffuse); else if (map.var() == "specular") assignVector(this, prog, it.key(), map, m_data.back().m_lights, &Light::specular); else if (map.var() == "direction") assignVector(this, prog, it.key(), map, m_data.back().m_lights, &Light::direction); else if (map.var() == "location") assignVector(this, prog, it.key(), map, m_data.back().m_lights, &Light::location); else if (map.var() == "target") assignVector(this, prog, it.key(), map, m_data.back().m_lights, &Light::target); else if (map.var() == "spot_cutoff") assignVector(this, prog, it.key(), map, m_data.back().m_lights, &Light::spotCutoff); else ok = false; } else if (map.src() == "gui") { if (map.var() == "mouse") setUniformSel(this, prog, it.key(), m_scene.lastRenderOpts().hover, map.select()); else if (map.var() == "mousedown") setUniformSel(this, prog, it.key(), m_scene.lastRenderOpts().mousedown, map.select()); else ok = false; } else ok = false; } }
bool CGUIWindowFullScreen::OnAction(const CAction &action) { if (g_application.m_pPlayer != NULL && g_application.m_pPlayer->OnAction(action)) return true; if (m_timeCodePosition > 0 && action.GetButtonCode()) { // check whether we have a mapping in our virtual videotimeseek "window" and have a select action CKey key(action.GetButtonCode()); CAction timeSeek = CButtonTranslator::GetInstance().GetAction(WINDOW_VIDEO_TIME_SEEK, key, false); if (timeSeek.GetID() == ACTION_SELECT_ITEM) { SeekToTimeCodeStamp(SEEK_ABSOLUTE); return true; } } const unsigned int MsgTime = 300; const unsigned int DisplTime = 2000; switch (action.GetID()) { case ACTION_SHOW_OSD: ToggleOSD(); return true; case ACTION_SHOW_GUI: { // switch back to the menu OutputDebugString("Switching to GUI\n"); g_windowManager.PreviousWindow(); OutputDebugString("Now in GUI\n"); return true; } break; case ACTION_PLAYER_PLAY: case ACTION_PAUSE: if (m_timeCodePosition > 0) { SeekToTimeCodeStamp(SEEK_ABSOLUTE); return true; } break; case ACTION_STEP_BACK: if (m_timeCodePosition > 0) SeekToTimeCodeStamp(SEEK_RELATIVE, SEEK_BACKWARD); else g_application.m_pPlayer->Seek(false, false); return true; break; case ACTION_STEP_FORWARD: if (m_timeCodePosition > 0) SeekToTimeCodeStamp(SEEK_RELATIVE, SEEK_FORWARD); else g_application.m_pPlayer->Seek(true, false); return true; break; case ACTION_BIG_STEP_BACK: if (m_timeCodePosition > 0) SeekToTimeCodeStamp(SEEK_RELATIVE, SEEK_BACKWARD); else g_application.m_pPlayer->Seek(false, true); return true; break; case ACTION_BIG_STEP_FORWARD: if (m_timeCodePosition > 0) SeekToTimeCodeStamp(SEEK_RELATIVE, SEEK_FORWARD); else g_application.m_pPlayer->Seek(true, true); return true; break; case ACTION_NEXT_SCENE: if (g_application.m_pPlayer->SeekScene(true)) g_infoManager.SetDisplayAfterSeek(); return true; break; case ACTION_PREV_SCENE: if (g_application.m_pPlayer->SeekScene(false)) g_infoManager.SetDisplayAfterSeek(); return true; break; case ACTION_SHOW_OSD_TIME: m_bShowCurrentTime = !m_bShowCurrentTime; if(!m_bShowCurrentTime) g_infoManager.SetDisplayAfterSeek(0); //Force display off g_infoManager.SetShowTime(m_bShowCurrentTime); return true; break; case ACTION_SHOW_SUBTITLES: { if (g_application.m_pPlayer->GetSubtitleCount() == 0) return true; g_settings.m_currentVideoSettings.m_SubtitleOn = !g_settings.m_currentVideoSettings.m_SubtitleOn; g_application.m_pPlayer->SetSubtitleVisible(g_settings.m_currentVideoSettings.m_SubtitleOn); CStdString sub, lang; if (g_settings.m_currentVideoSettings.m_SubtitleOn) { g_application.m_pPlayer->GetSubtitleName(g_application.m_pPlayer->GetSubtitle(),sub); g_application.m_pPlayer->GetSubtitleLanguage(g_application.m_pPlayer->GetSubtitle(),lang); if (sub != lang) sub.Format("%s [%s]", sub.c_str(), lang.c_str()); } else sub = g_localizeStrings.Get(1223); CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Info, g_localizeStrings.Get(287), sub, DisplTime, false, MsgTime); } return true; break; case ACTION_SHOW_INFO: { CGUIDialogFullScreenInfo* pDialog = (CGUIDialogFullScreenInfo*)g_windowManager.GetWindow(WINDOW_DIALOG_FULLSCREEN_INFO); if (pDialog) { pDialog->DoModal(); return true; } break; } case ACTION_NEXT_SUBTITLE: { if (g_application.m_pPlayer->GetSubtitleCount() == 0) return true; if(g_settings.m_currentVideoSettings.m_SubtitleStream < 0) g_settings.m_currentVideoSettings.m_SubtitleStream = g_application.m_pPlayer->GetSubtitle(); if (g_settings.m_currentVideoSettings.m_SubtitleOn) { g_settings.m_currentVideoSettings.m_SubtitleStream++; if (g_settings.m_currentVideoSettings.m_SubtitleStream >= g_application.m_pPlayer->GetSubtitleCount()) { g_settings.m_currentVideoSettings.m_SubtitleStream = 0; g_settings.m_currentVideoSettings.m_SubtitleOn = false; g_application.m_pPlayer->SetSubtitleVisible(false); } g_application.m_pPlayer->SetSubtitle(g_settings.m_currentVideoSettings.m_SubtitleStream); } else { g_settings.m_currentVideoSettings.m_SubtitleOn = true; g_application.m_pPlayer->SetSubtitleVisible(true); } CStdString sub, lang; if (g_settings.m_currentVideoSettings.m_SubtitleOn) { g_application.m_pPlayer->GetSubtitleName(g_settings.m_currentVideoSettings.m_SubtitleStream,sub); g_application.m_pPlayer->GetSubtitleLanguage(g_settings.m_currentVideoSettings.m_SubtitleStream,lang); if (sub != lang) sub.Format("%s [%s]", sub.c_str(), lang.c_str()); } else sub = g_localizeStrings.Get(1223); CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Info, g_localizeStrings.Get(287), sub, DisplTime, false, MsgTime); } return true; break; case ACTION_SUBTITLE_DELAY_MIN: g_settings.m_currentVideoSettings.m_SubtitleDelay -= 0.1f; if (g_settings.m_currentVideoSettings.m_SubtitleDelay < -g_advancedSettings.m_videoSubsDelayRange) g_settings.m_currentVideoSettings.m_SubtitleDelay = -g_advancedSettings.m_videoSubsDelayRange; if (g_application.m_pPlayer) g_application.m_pPlayer->SetSubTitleDelay(g_settings.m_currentVideoSettings.m_SubtitleDelay); ShowSlider(action.GetID(), 22006, g_settings.m_currentVideoSettings.m_SubtitleDelay, -g_advancedSettings.m_videoSubsDelayRange, 0.1f, g_advancedSettings.m_videoSubsDelayRange); return true; break; case ACTION_SUBTITLE_DELAY_PLUS: g_settings.m_currentVideoSettings.m_SubtitleDelay += 0.1f; if (g_settings.m_currentVideoSettings.m_SubtitleDelay > g_advancedSettings.m_videoSubsDelayRange) g_settings.m_currentVideoSettings.m_SubtitleDelay = g_advancedSettings.m_videoSubsDelayRange; if (g_application.m_pPlayer) g_application.m_pPlayer->SetSubTitleDelay(g_settings.m_currentVideoSettings.m_SubtitleDelay); ShowSlider(action.GetID(), 22006, g_settings.m_currentVideoSettings.m_SubtitleDelay, -g_advancedSettings.m_videoSubsDelayRange, 0.1f, g_advancedSettings.m_videoSubsDelayRange); return true; break; case ACTION_SUBTITLE_DELAY: ShowSlider(action.GetID(), 22006, g_settings.m_currentVideoSettings.m_SubtitleDelay, -g_advancedSettings.m_videoSubsDelayRange, 0.1f, g_advancedSettings.m_videoSubsDelayRange, true); return true; break; case ACTION_AUDIO_DELAY: ShowSlider(action.GetID(), 297, g_settings.m_currentVideoSettings.m_AudioDelay, -g_advancedSettings.m_videoAudioDelayRange, 0.025f, g_advancedSettings.m_videoAudioDelayRange, true); return true; break; case ACTION_AUDIO_DELAY_MIN: g_settings.m_currentVideoSettings.m_AudioDelay -= 0.025f; if (g_settings.m_currentVideoSettings.m_AudioDelay < -g_advancedSettings.m_videoAudioDelayRange) g_settings.m_currentVideoSettings.m_AudioDelay = -g_advancedSettings.m_videoAudioDelayRange; if (g_application.m_pPlayer) g_application.m_pPlayer->SetAVDelay(g_settings.m_currentVideoSettings.m_AudioDelay); ShowSlider(action.GetID(), 297, g_settings.m_currentVideoSettings.m_AudioDelay, -g_advancedSettings.m_videoAudioDelayRange, 0.025f, g_advancedSettings.m_videoAudioDelayRange); return true; break; case ACTION_AUDIO_DELAY_PLUS: g_settings.m_currentVideoSettings.m_AudioDelay += 0.025f; if (g_settings.m_currentVideoSettings.m_AudioDelay > g_advancedSettings.m_videoAudioDelayRange) g_settings.m_currentVideoSettings.m_AudioDelay = g_advancedSettings.m_videoAudioDelayRange; if (g_application.m_pPlayer) g_application.m_pPlayer->SetAVDelay(g_settings.m_currentVideoSettings.m_AudioDelay); ShowSlider(action.GetID(), 297, g_settings.m_currentVideoSettings.m_AudioDelay, -g_advancedSettings.m_videoAudioDelayRange, 0.025f, g_advancedSettings.m_videoAudioDelayRange); return true; break; case ACTION_AUDIO_NEXT_LANGUAGE: { if (g_application.m_pPlayer->GetAudioStreamCount() == 1) return true; if(g_settings.m_currentVideoSettings.m_AudioStream < 0) g_settings.m_currentVideoSettings.m_AudioStream = g_application.m_pPlayer->GetAudioStream(); g_settings.m_currentVideoSettings.m_AudioStream++; if (g_settings.m_currentVideoSettings.m_AudioStream >= g_application.m_pPlayer->GetAudioStreamCount()) g_settings.m_currentVideoSettings.m_AudioStream = 0; g_application.m_pPlayer->SetAudioStream(g_settings.m_currentVideoSettings.m_AudioStream); // Set the audio stream to the one selected CStdString aud; g_application.m_pPlayer->GetAudioStreamName(g_settings.m_currentVideoSettings.m_AudioStream,aud); CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Info, g_localizeStrings.Get(460), aud, DisplTime, false, MsgTime); return true; } break; case REMOTE_0: case REMOTE_1: case REMOTE_2: case REMOTE_3: case REMOTE_4: case REMOTE_5: case REMOTE_6: case REMOTE_7: case REMOTE_8: case REMOTE_9: { if (g_application.CurrentFileItem().IsLiveTV()) { int channelNr = -1; CStdString strChannel; strChannel.Format("%i", action.GetID() - REMOTE_0); if (CGUIDialogNumeric::ShowAndGetNumber(strChannel, g_localizeStrings.Get(19000))) channelNr = atoi(strChannel.c_str()); if (channelNr > 0) OnAction(CAction(ACTION_CHANNEL_SWITCH, (float)channelNr)); } else { ChangetheTimeCode(action.GetID()); } return true; } break; case ACTION_ASPECT_RATIO: { // toggle the aspect ratio mode (only if the info is onscreen) if (m_bShowViewModeInfo) { #ifdef HAS_VIDEO_PLAYBACK g_renderManager.SetViewMode(++g_settings.m_currentVideoSettings.m_ViewMode); #endif } m_bShowViewModeInfo = true; m_dwShowViewModeTimeout = XbmcThreads::SystemClockMillis(); } return true; break; case ACTION_SMALL_STEP_BACK: if (m_timeCodePosition > 0) SeekToTimeCodeStamp(SEEK_RELATIVE, SEEK_BACKWARD); else { int orgpos = (int)g_application.GetTime(); int jumpsize = g_advancedSettings.m_videoSmallStepBackSeconds; // secs int setpos = (orgpos > jumpsize) ? orgpos - jumpsize : 0; g_application.SeekTime((double)setpos); } return true; break; case ACTION_ZOOM_IN: { g_settings.m_currentVideoSettings.m_CustomZoomAmount += 0.01f; if (g_settings.m_currentVideoSettings.m_CustomZoomAmount > 2.f) g_settings.m_currentVideoSettings.m_CustomZoomAmount = 2.f; g_settings.m_currentVideoSettings.m_ViewMode = VIEW_MODE_CUSTOM; g_renderManager.SetViewMode(VIEW_MODE_CUSTOM); ShowSlider(action.GetID(), 216, g_settings.m_currentVideoSettings.m_CustomZoomAmount, 0.5f, 0.1f, 2.0f); } return true; break; case ACTION_ZOOM_OUT: { g_settings.m_currentVideoSettings.m_CustomZoomAmount -= 0.01f; if (g_settings.m_currentVideoSettings.m_CustomZoomAmount < 0.5f) g_settings.m_currentVideoSettings.m_CustomZoomAmount = 0.5f; g_settings.m_currentVideoSettings.m_ViewMode = VIEW_MODE_CUSTOM; g_renderManager.SetViewMode(VIEW_MODE_CUSTOM); ShowSlider(action.GetID(), 216, g_settings.m_currentVideoSettings.m_CustomZoomAmount, 0.5f, 0.1f, 2.0f); } return true; break; case ACTION_INCREASE_PAR: { g_settings.m_currentVideoSettings.m_CustomPixelRatio += 0.01f; if (g_settings.m_currentVideoSettings.m_CustomPixelRatio > 2.f) g_settings.m_currentVideoSettings.m_CustomZoomAmount = 2.f; g_settings.m_currentVideoSettings.m_ViewMode = VIEW_MODE_CUSTOM; g_renderManager.SetViewMode(VIEW_MODE_CUSTOM); ShowSlider(action.GetID(), 217, g_settings.m_currentVideoSettings.m_CustomPixelRatio, 0.5f, 0.1f, 2.0f); } return true; break; case ACTION_DECREASE_PAR: { g_settings.m_currentVideoSettings.m_CustomPixelRatio -= 0.01f; if (g_settings.m_currentVideoSettings.m_CustomZoomAmount < 0.5f) g_settings.m_currentVideoSettings.m_CustomPixelRatio = 0.5f; g_settings.m_currentVideoSettings.m_ViewMode = VIEW_MODE_CUSTOM; g_renderManager.SetViewMode(VIEW_MODE_CUSTOM); ShowSlider(action.GetID(), 217, g_settings.m_currentVideoSettings.m_CustomPixelRatio, 0.5f, 0.1f, 2.0f); } return true; break; case ACTION_VSHIFT_UP: { g_settings.m_currentVideoSettings.m_CustomVerticalShift -= 0.01f; if (g_settings.m_currentVideoSettings.m_CustomVerticalShift < -2.0f) g_settings.m_currentVideoSettings.m_CustomVerticalShift = -2.0f; g_settings.m_currentVideoSettings.m_ViewMode = VIEW_MODE_CUSTOM; g_renderManager.SetViewMode(VIEW_MODE_CUSTOM); ShowSlider(action.GetID(), 225, g_settings.m_currentVideoSettings.m_CustomVerticalShift, -2.0f, 0.1f, 2.0f); } return true; break; case ACTION_VSHIFT_DOWN: { g_settings.m_currentVideoSettings.m_CustomVerticalShift += 0.01f; if (g_settings.m_currentVideoSettings.m_CustomVerticalShift > 2.0f) g_settings.m_currentVideoSettings.m_CustomVerticalShift = 2.0f; g_settings.m_currentVideoSettings.m_ViewMode = VIEW_MODE_CUSTOM; g_renderManager.SetViewMode(VIEW_MODE_CUSTOM); ShowSlider(action.GetID(), 225, g_settings.m_currentVideoSettings.m_CustomVerticalShift, -2.0f, 0.1f, 2.0f); } return true; break; case ACTION_SUBTITLE_VSHIFT_UP: { RESOLUTION_INFO& res_info = g_settings.m_ResInfo[g_graphicsContext.GetVideoResolution()]; int subalign = g_guiSettings.GetInt("subtitles.align"); if ((subalign == SUBTITLE_ALIGN_BOTTOM_OUTSIDE) || (subalign == SUBTITLE_ALIGN_TOP_INSIDE)) { res_info.iSubtitles ++; if (res_info.iSubtitles >= res_info.iHeight) res_info.iSubtitles = res_info.iHeight - 1; ShowSlider(action.GetID(), 274, (float) res_info.iHeight - res_info.iSubtitles, 0.0f, 1.0f, (float) res_info.iHeight); } else { res_info.iSubtitles --; if (res_info.iSubtitles < 0) res_info.iSubtitles = 0; if (subalign == SUBTITLE_ALIGN_MANUAL) ShowSlider(action.GetID(), 274, (float) res_info.iSubtitles, 0.0f, 1.0f, (float) res_info.iHeight); else ShowSlider(action.GetID(), 274, (float) res_info.iSubtitles - res_info.iHeight, (float) -res_info.iHeight, -1.0f, 0.0f); } break; } case ACTION_SUBTITLE_VSHIFT_DOWN: { RESOLUTION_INFO& res_info = g_settings.m_ResInfo[g_graphicsContext.GetVideoResolution()]; int subalign = g_guiSettings.GetInt("subtitles.align"); if ((subalign == SUBTITLE_ALIGN_BOTTOM_OUTSIDE) || (subalign == SUBTITLE_ALIGN_TOP_INSIDE)) { res_info.iSubtitles--; if (res_info.iSubtitles < 0) res_info.iSubtitles = 0; ShowSlider(action.GetID(), 274, (float) res_info.iHeight - res_info.iSubtitles, 0.0f, 1.0f, (float) res_info.iHeight); } else { res_info.iSubtitles++; if (res_info.iSubtitles >= res_info.iHeight) res_info.iSubtitles = res_info.iHeight - 1; if (subalign == SUBTITLE_ALIGN_MANUAL) ShowSlider(action.GetID(), 274, (float) res_info.iSubtitles, 0.0f, 1.0f, (float) res_info.iHeight); else ShowSlider(action.GetID(), 274, (float) res_info.iSubtitles - res_info.iHeight, (float) -res_info.iHeight, -1.0f, 0.0f); } break; } case ACTION_SUBTITLE_ALIGN: { RESOLUTION_INFO& res_info = g_settings.m_ResInfo[g_graphicsContext.GetVideoResolution()]; int subalign = g_guiSettings.GetInt("subtitles.align"); subalign++; if (subalign > SUBTITLE_ALIGN_TOP_OUTSIDE) subalign = SUBTITLE_ALIGN_MANUAL; res_info.iSubtitles = res_info.iHeight - 1; g_guiSettings.SetInt("subtitles.align", subalign); CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Info, g_localizeStrings.Get(21460), g_localizeStrings.Get(21461 + subalign), TOAST_DISPLAY_TIME, false); break; } default: break; } return CGUIWindow::OnAction(action); }
Json::Value doAccountObjects (RPC::Context& context) { auto const& params = context.params; if (! params.isMember (jss::account)) return RPC::missing_field_error (jss::account); std::shared_ptr<ReadView const> ledger; auto result = RPC::lookupLedger (ledger, context); if (ledger == nullptr) return result; AccountID accountID; { auto const strIdent = params[jss::account].asString (); if (auto jv = RPC::accountFromString (accountID, strIdent)) { for (auto it = jv.begin (); it != jv.end (); ++it) result[it.memberName ()] = it.key (); return result; } } if (! ledger->exists(keylet::account (accountID))) return rpcError (rpcACT_NOT_FOUND); auto type = ltINVALID; if (params.isMember (jss::type)) { using filter_types = std::vector <std::pair <std::string, LedgerEntryType>>; static beast::static_initializer <filter_types> const types ([]() -> filter_types { return { { "account", ltACCOUNT_ROOT }, { "amendments", ltAMENDMENTS }, { "directory", ltDIR_NODE }, { "fee", ltFEE_SETTINGS }, { "hashes", ltLEDGER_HASHES }, { "offer", ltOFFER }, { "state", ltRIPPLE_STATE }, { "ticket", ltTICKET } }; }()); auto const& p = params[jss::type]; if (! p.isString ()) return RPC::expected_field_error (jss::type, "string"); auto const filter = p.asString (); auto iter = std::find_if (types->begin (), types->end (), [&filter](decltype (types->front ())& t) { return t.first == filter; }); if (iter == types->end ()) return RPC::invalid_field_error (jss::type); type = iter->second; } auto limit = RPC::Tuning::defaultObjectsPerRequest; if (params.isMember (jss::limit)) { auto const& jvLimit = params[jss::limit]; if (! jvLimit.isIntegral ()) return RPC::expected_field_error (jss::limit, "unsigned integer"); limit = jvLimit.isUInt () ? jvLimit.asUInt () : std::max (0, jvLimit.asInt ()); if (context.role != Role::ADMIN) { limit = std::max (RPC::Tuning::minObjectsPerRequest, std::min (limit, RPC::Tuning::maxObjectsPerRequest)); } } uint256 dirIndex; uint256 entryIndex; if (params.isMember (jss::marker)) { auto const& marker = params[jss::marker]; if (! marker.isString ()) return RPC::expected_field_error (jss::marker, "string"); std::stringstream ss (marker.asString ()); std::string s; if (!std::getline(ss, s, ',')) return RPC::invalid_field_error (jss::marker); if (! dirIndex.SetHex (s)) return RPC::invalid_field_error (jss::marker); if (! std::getline (ss, s, ',')) return RPC::invalid_field_error (jss::marker); if (! entryIndex.SetHex (s)) return RPC::invalid_field_error (jss::marker); } if (! RPC::getAccountObjects (*ledger, accountID, type, dirIndex, entryIndex, limit, result)) { return RPC::invalid_field_error (jss::marker); } result[jss::account] = getApp().accountIDCache().toBase58 (accountID); context.loadType = Resource::feeMediumBurdenRPC; return result; }
void WiredTigerSizeStorer::storeInto( WiredTigerSession* session, const std::string& uri ) { Map myMap; { boost::mutex::scoped_lock lk( _entriesMutex ); for ( Map::iterator it = _entries.begin(); it != _entries.end(); ++it ) { std::string uriKey = it->first; Entry& entry = it->second; if ( entry.rs ) { if ( entry.dataSize != entry.rs->dataSize( NULL ) ) { entry.dataSize = entry.rs->dataSize( NULL ); entry.dirty = true; } if ( entry.numRecords != entry.rs->numRecords( NULL ) ) { entry.numRecords = entry.rs->numRecords( NULL ); entry.dirty = true; } } if ( !entry.dirty ) continue; myMap[uriKey] = entry; } } WT_SESSION* s = session->getSession(); WT_CURSOR* c = NULL; int ret = s->open_cursor( s, uri.c_str(), NULL, NULL, &c ); if ( ret == ENOENT ) { invariantWTOK( s->create( s, uri.c_str(), "" ) ); ret = s->open_cursor( s, uri.c_str(), NULL, NULL, &c ); } invariantWTOK( ret ); for ( Map::iterator it = myMap.begin(); it != myMap.end(); ++it ) { string uriKey = it->first; Entry& entry = it->second; BSONObj data; { BSONObjBuilder b; b.append( "numRecords", entry.numRecords ); b.append( "dataSize", entry.dataSize ); data = b.obj(); } LOG(2) << "WiredTigerSizeStorer::storeInto " << uriKey << " -> " << data; WiredTigerItem key( uriKey.c_str(), uriKey.size() ); WiredTigerItem value( data.objdata(), data.objsize() ); c->set_key( c, key.Get() ); c->set_value( c, value.Get() ); invariantWTOK( c->insert(c) ); entry.dirty = false; c->reset(c); } invariantWTOK( c->close(c) ); }