int main(int argc, char *argv[]) { Conf conf; for (int i = 1; i < argc; i++) { string arg = argv[i]; if (arg == "-h") { if (i + 1 >= argc || argv[i+1][0] == '-') { fprintf(stderr, " Usage: -h host\n"); return EXIT_FAILURE; } conf.host = argv[++i]; } else if (arg == "-u") { if (i + 1 >= argc || argv[i+1][0] == '-') { fprintf(stderr, " Usage: -u user\n"); return EXIT_FAILURE; } conf.username = argv[++i]; } else if (arg == "-p") { if (i + 1 >= argc || argv[i+1][0] == '-') { fprintf(stderr, " Usage: -p password\n"); return EXIT_FAILURE; } conf.password = argv[++i]; } else if (arg == "-s") { if (i + 1 >= argc || argv[i+1][0] == '-') { fprintf(stderr, " Usage: -s schema\n"); return EXIT_FAILURE; } conf.schema = argv[++i]; } else if (arg == "-d") { if (i + 1 >= argc || argv[i+1][0] == '-') { fprintf(stderr, " Usage: -d delay\n"); return EXIT_FAILURE; } conf.no_rows_sleep = boost::posix_time::time_duration(0, 0, atol(argv[++i])); } else if (arg == "-i") { if (i + 1 >= argc || argv[i+1][0] == '-') { fprintf(stderr, " Usage: -i interval\n"); return EXIT_FAILURE; } conf.scan_interval = atoi(argv[++i]); } else if (arg == "-g") { conf.display_grid = true; } } try { printf("Connecting to database...\n"); driver = get_driver_instance(); con.reset(driver->connect(conf.host, conf.username, conf.password)); if ( ! con || con->isClosed()) { printf("Failed.\n"); return EXIT_FAILURE; } con->setSchema(conf.schema); printf("Connected.\n"); for (EVER) { unique_ptr<PreparedStatement> query(con->prepareStatement("SELECT id FROM parking WHERE last_scan <= ? ORDER BY last_scan ASC LIMIT 1")); query->setUInt(1, (unsigned int) time(nullptr) - conf.scan_interval); unique_ptr<ResultSet> res(query->executeQuery()); if ( ! res->first()) { printf("No data, skipping.\n"); boost::this_thread::sleep(conf.no_rows_sleep); continue; } unsigned int parking_id = res->getUInt("id"); printf("Scanning parking (id %u)\n", parking_id); // insert basic parking stats unsigned int free_spots = 0; query.reset(con->prepareStatement("INSERT INTO stats_parking (parking_id) VALUES(?)")); query->setUInt(1, parking_id); query->executeUpdate(); unsigned int stats_parking_id = get_last_insert_id("stats_parking"); Crawler crawler(parking_id); while (crawler.hasNext()) { unsigned int camera_id = crawler.camera_results->getUInt("id"); string type = crawler.camera_results->getString("type"); string address = crawler.camera_results->getString("address"); double threshold_high = crawler.camera_results->getDouble("threshold_high"); double threshold_low = crawler.camera_results->getDouble("threshold_low"); double threshold_scan = crawler.camera_results->getDouble("threshold_scan"); double scale = crawler.camera_results->getDouble("scale"); unique_ptr<CameraDriver> camera(CameraDriver::factory(type, address)); if ( ! camera->isValid()) { printf(" Warning: Failed to retrive image from camera (id %u); skipping\n", camera_id); continue; } Detector detector; clock_t start, end; start = clock(); if ( ! detector.loadImage(camera->getImagePath(), threshold_low, threshold_high, scale)) { printf(" Warning: Failed to load image from camera (id %u) into detector; skipping\n", camera_id); continue; } unique_ptr<vector<Spot *>> spots(crawler.loadSpots()); detector.findFreeSpots(*spots, threshold_scan); end = clock(); #ifdef _DEBUG printf(" Info: scanned %u spots in %u microseconds\n", spots->size(), (end - start) * 1000 / CLOCKS_PER_SEC); #endif unsigned int to_update = 0; unsigned int camera_free_spots = 0; vector<int> update_to_free_ids, update_to_occupied_ids; stringstream insert_spot_stats; // insert camera and spots stats query.reset(con->prepareStatement("INSERT INTO stats_camera (camera_id, stats_parking_id) VALUES(?, ?)")); query->setUInt(1, camera_id); query->setUInt(2, stats_parking_id); query->executeUpdate(); unsigned int stats_camera_id = get_last_insert_id("stats_camera"); insert_spot_stats << "INSERT INTO stats_spot (spot_id, stats_camera_id, status) VALUES "; for (size_t i = 0, l = spots->size(); i < l; i++) { Spot &spot = *(*spots)[i]; if (spot.status != spot.original_status) { to_update++; switch (spot.status) { case Free: update_to_free_ids.push_back(spot.id); break; case Occupied: update_to_occupied_ids.push_back(spot.id); break; } } insert_spot_stats << "(" << spot.id << "," << stats_camera_id << ","; switch (spot.status) { case Free: free_spots++; camera_free_spots++; insert_spot_stats << "'free'),"; break; case Occupied: insert_spot_stats << "'occupied'),"; break; case Blocked: insert_spot_stats << "'blocked'),"; break; } } // insert spots stats if (spots->size() > 0) { string insert_query = insert_spot_stats.str(); query.reset(con->prepareStatement(insert_query.substr(0, insert_query.length() - 1))); query->executeUpdate(); } // update camera stats query.reset(con->prepareStatement("UPDATE stats_camera SET free_spots = ? WHERE id = ?")); query->setUInt(1, camera_free_spots); query->setUInt(2, stats_camera_id); query->executeUpdate(); #ifdef _DEBUG printf(" Info: updating %i spots\n", to_update); #endif if (conf.display_grid) { detector.displayGrid(*spots); boost::this_thread::sleep(conf.no_rows_sleep); } size_t lf = update_to_free_ids.size(); size_t lo = update_to_occupied_ids.size(); if (lf > 0) { stringstream update_to_free; update_to_free << "UPDATE spot SET status = 1 WHERE id IN ("; lf -= 1; for (size_t i = 0; i < lf; i++) { update_to_free << update_to_free_ids[i] << ","; } update_to_free << update_to_free_ids[lf] << ")"; query.reset(con->prepareStatement(update_to_free.str())); query->executeUpdate(); } if (lo > 0) { stringstream update_to_occupied; update_to_occupied << "UPDATE spot SET status = 2 WHERE id IN ("; lo -= 1; for (size_t i = 0; i < lo; i++) { update_to_occupied << update_to_occupied_ids[i] << ","; } update_to_occupied << update_to_occupied_ids[lo] << ")"; query.reset(con->prepareStatement(update_to_occupied.str())); query->executeUpdate(); } for (size_t i = 0, l = spots->size(); i < l; i++) { delete spots->at(i); } } query.reset(con->prepareStatement("UPDATE parking SET last_scan = ? WHERE id = ?")); query->setUInt(1, (unsigned int) time(nullptr)); query->setUInt(2, parking_id); query->executeUpdate(); // update parkign stats query.reset(con->prepareStatement("UPDATE stats_parking SET free_spots = ? WHERE id = ?")); query->setUInt(1, free_spots); query->setUInt(2, stats_parking_id); query->executeUpdate(); } } catch (SQLException &e) { printf("Error: SQLException in %s\n%s\n(MySQL error code: %i, SQLState: %s)\n", __FILE_SHORT__, e.what(), e.getErrorCode(), e.getSQLState().c_str()); } catch (exception &e) { printf("Error: Exception in %s\n%s\n", __FILE_SHORT__, e.what()); } catch (...) { printf("Error: Unknown exception in %s\n", __FILE_SHORT__); } system("pause"); return EXIT_SUCCESS; }
sequence_in_t C_method(const unique_ptr<DFSM>& fsm, int extraStates) { RETURN_IF_UNREDUCED(fsm, "FSMtesting::C_method", sequence_in_t()); auto E = getAdaptiveDistinguishingSet(fsm); if (E.empty()) { return sequence_in_t(); } auto N = fsm->getNumberOfStates(); auto P = fsm->getNumberOfInputs(); /* // Example from simao2009checking E.clear(); E[0].push_back(0); E[0].push_back(1); E[0].push_back(0); E[1].push_back(0); E[1].push_back(1); E[1].push_back(0); E[2].push_back(0); E[2].push_back(1); E[3].push_back(0); E[3].push_back(1); E[4].push_back(0); E[4].push_back(1); //*/ vector<vector<bool>> verifiedTransition(N); vector<input_t> verifiedState(N, P); vector<shared_ptr<ver_seq_t>> verSeq(N); for (state_t i = 0; i < N; i++) { verifiedTransition[i].resize(P, false); verSeq[i] = make_shared<ver_seq_t>(); } if (fsm->isOutputState()) { for (state_t i = 0; i < N; i++) { sequence_in_t seq; for (const auto& input : E[i]) { if (input == STOUT_INPUT) continue; seq.push_back(input); } E[i].swap(seq); } } output_t outputState = (fsm->isOutputState()) ? fsm->getOutput(0, STOUT_INPUT) : DEFAULT_OUTPUT; output_t outputTransition; vector<unique_ptr<TestNodeC>> cs; cs.emplace_back(make_unique<TestNodeC>(STOUT_INPUT, DEFAULT_OUTPUT, 0, outputState)); state_t currState = 0; for (const auto& input : E[0]) { auto nextState = fsm->getNextState(currState, input); outputState = (fsm->isOutputState()) ? fsm->getOutput(nextState, STOUT_INPUT) : DEFAULT_OUTPUT; outputTransition = (fsm->isOutputTransition()) ? fsm->getOutput(currState, input) : DEFAULT_OUTPUT; cs.emplace_back(make_unique<TestNodeC>(input, outputTransition, nextState, outputState)); currState = nextState; } vector<vector<seq_len_t>> confirmedNodes(N); confirmedNodes[0].push_back(0); queue<seq_len_t> newlyConfirmed; seq_len_t counter = N * fsm->getNumberOfInputs(); seq_len_t currIdx = 1; seq_len_t lastConfIdx = 0; currState = 0; while (counter > 0) { //getCS(CS, fsm->isOutputState()); //printf("%u/%u %u %s\n", currIdx, cs.size(), lastConfIdx, FSMmodel::getInSequenceAsString(CS).c_str()); if (cs.back()->confirmed) { currIdx = seq_len_t(cs.size()); lastConfIdx = currIdx - 1; } if (currIdx < cs.size()) { if (!cs[currIdx]->confirmed) { auto nextState = cs[currIdx]->state; auto nextInput = E[nextState].begin(); if (equalSeqPart(currIdx + 1, nextInput, E[nextState].end(), cs)) { currState = cs.back()->state; for (; nextInput != E[cs[currIdx]->state].end(); nextInput++) { nextState = fsm->getNextState(currState, *nextInput); outputState = (fsm->isOutputState()) ? fsm->getOutput(nextState, STOUT_INPUT) : DEFAULT_OUTPUT; outputTransition = (fsm->isOutputTransition()) ? fsm->getOutput(currState, *nextInput) : DEFAULT_OUTPUT; cs.emplace_back(make_unique<TestNodeC>(*nextInput, outputTransition, nextState, outputState)); currState = nextState; } cs[currIdx]->confirmed = true; newlyConfirmed.emplace(currIdx); update(lastConfIdx, cs, newlyConfirmed, verifiedTransition, verifiedState, verSeq, confirmedNodes, counter); processNewlyConfirmed(cs, newlyConfirmed, verifiedTransition, verifiedState, verSeq, confirmedNodes, counter, currIdx, lastConfIdx); } } else { lastConfIdx = currIdx; } currIdx++; } else if (verifiedState[cs.back()->state] > 0) { currState = cs.back()->state; for (input_t input = 0; input < P; input++) { if (!verifiedTransition[currState][input]) { auto nextState = fsm->getNextState(currState, input); outputState = (fsm->isOutputState()) ? fsm->getOutput(nextState, STOUT_INPUT) : DEFAULT_OUTPUT; outputTransition = (fsm->isOutputTransition()) ? fsm->getOutput(currState, input) : DEFAULT_OUTPUT; cs.emplace_back(make_unique<TestNodeC>(input, outputTransition, nextState, outputState)); cs.back()->confirmed = true; newlyConfirmed.emplace(currIdx); //cs.size()-1 sequence_in_t seqE(E[nextState]); // output-confirmed if (!E[currState].empty() && input == E[currState].front()) { sequence_in_t suf(E[currState]); suf.pop_front(); auto outSuf = fsm->getOutputAlongPath(nextState, suf); auto outE = fsm->getOutputAlongPath(nextState, E[nextState]); //printf("(%d,%d,%d) %s/%s %s\n", currState, input, nextState, // FSMmodel::getInSequenceAsString(suf).c_str(), // FSMmodel::getOutSequenceAsString(outSuf).c_str(), // FSMmodel::getOutSequenceAsString(outE).c_str()); seq_len_t lenE = 0; //outE.size(); for (state_t i = 0; i < N; i++) { if (i != nextState) { auto outSufI = fsm->getOutputAlongPath(i, suf); auto osl = equalLength(outSuf.begin(), outSufI.begin(), seq_len_t(outSuf.size())); if (osl != outSuf.size()) { bool outConfirmed = false; auto sufIt = suf.begin(); osl++; while (osl-- > 0) sufIt++; for (auto& cnIdx : confirmedNodes[i]) { auto sufBeginIt = suf.begin(); if (equalSeqPart(cnIdx + 1, sufBeginIt, sufIt, cs)) { outConfirmed = true; break; } } if (outConfirmed) { continue; /* outConfirmed = false; for (auto cnIdx : confirmedNodes[nextState]) { auto sufBeginIt = suf.begin(); if (equalSeqPart(cnIdx, sufBeginIt, sufIt)) { outConfirmed = true; break; } } if (outConfirmed) { continue; } */ } } auto outI = fsm->getOutputAlongPath(i, E[nextState]); auto oel = 1 + equalLength(outE.begin(), outI.begin(), seq_len_t(outI.size())); //printf("%s/%s x %s %d %d-%d\n", // FSMmodel::getInSequenceAsString(E[nextState]).c_str(), // FSMmodel::getOutSequenceAsString(outE).c_str(), // FSMmodel::getOutSequenceAsString(outI).c_str(), //oel, lenE, outE.size()); if (oel > lenE) { lenE = oel; if (lenE == outE.size()) {// entire E is needed break; } } } } // adjust E for (; lenE < outE.size(); lenE++) { seqE.pop_back(); } } currState = nextState; for (const auto& input : seqE) { nextState = fsm->getNextState(currState, input); outputState = (fsm->isOutputState()) ? fsm->getOutput(nextState, STOUT_INPUT) : DEFAULT_OUTPUT; outputTransition = (fsm->isOutputTransition()) ? fsm->getOutput(currState, input) : DEFAULT_OUTPUT; cs.emplace_back(make_unique<TestNodeC>(input, outputTransition, nextState, outputState)); currState = nextState; } update(currIdx - 1, cs, newlyConfirmed, verifiedTransition, verifiedState, verSeq, confirmedNodes, counter); processNewlyConfirmed(cs, newlyConfirmed, verifiedTransition, verifiedState, verSeq, confirmedNodes, counter, currIdx, lastConfIdx); break; } } } else {// find unverified transition vector<bool> covered(N, false); list<pair<state_t, sequence_in_t>> fifo; currState = cs.back()->state; covered[currState] = true; fifo.emplace_back(currState, sequence_in_t()); while (!fifo.empty()) { auto current = move(fifo.front()); fifo.pop_front(); for (input_t input = 0; input < P; input++) { auto nextState = fsm->getNextState(current.first, input); if (nextState == WRONG_STATE) continue; if (verifiedState[nextState] > 0) { for (auto nextInput = current.second.begin(); nextInput != current.second.end(); nextInput++) { nextState = fsm->getNextState(currState, *nextInput); outputState = (fsm->isOutputState()) ? fsm->getOutput(nextState, STOUT_INPUT) : DEFAULT_OUTPUT; outputTransition = (fsm->isOutputTransition()) ? fsm->getOutput(currState, *nextInput) : DEFAULT_OUTPUT; cs.emplace_back(make_unique<TestNodeC>(*nextInput, outputTransition, nextState, outputState)); cs.back()->confirmed = true; currState = nextState; } nextState = fsm->getNextState(currState, input); outputState = (fsm->isOutputState()) ? fsm->getOutput(nextState, STOUT_INPUT) : DEFAULT_OUTPUT; outputTransition = (fsm->isOutputTransition()) ? fsm->getOutput(currState, input) : DEFAULT_OUTPUT; lastConfIdx = seq_len_t(cs.size()); cs.emplace_back(make_unique<TestNodeC>(input, outputTransition, nextState, outputState)); cs.back()->confirmed = true; currIdx = seq_len_t(cs.size()); fifo.clear(); break; } if (!covered[nextState]) { covered[nextState] = true; sequence_in_t newPath(current.second); newPath.push_back(input); fifo.emplace_back(nextState, move(newPath)); } } } } } return getCS(fsm->isOutputState(), cs); }
void VsfsFuse::destory() { LOG(INFO) << "VsfsFuse is shutting down..."; instance_.reset(); }
GainType LKH::LKHAlg::FindTour() { GainType Cost; Node *t; int i; double EntryTime = GetTime(); if(!OrdinalTourCost.get()) OrdinalTourCost.reset(new GainType(0)); t = FirstNode; do t->OldPred = t->OldSuc = t->NextBestSuc = t->BestSuc = 0; while ((t = t->Suc) != FirstNode); if (Run == 1 && Dimension == DimensionSaved) { *OrdinalTourCost = 0; for (i = 1; i < Dimension; i++) *OrdinalTourCost += (this->*C)(&NodeSet[i], &NodeSet[i + 1]) - NodeSet[i].Pi - NodeSet[i + 1].Pi; *OrdinalTourCost += (this->*C)(&NodeSet[Dimension], &NodeSet[1]) - NodeSet[Dimension].Pi - NodeSet[1].Pi; *OrdinalTourCost /= Precision; } BetterCost = PLUS_INFINITY; if (MaxTrials > 0) HashInitialize(HTable); else { Trial = 1; ChooseInitialTour(); } for (Trial = 1; Trial <= MaxTrials; Trial++) { if (GetTime() - EntryTime >= TimeLimit) { if (TraceLevel >= 1) printff("*** Time limit exceeded ***\n"); break; } /* Choose FirstNode at random */ if (Dimension == DimensionSaved) FirstNode = &NodeSet[1 + Random() % Dimension]; else for (i = Random() % Dimension; i > 0; i--) FirstNode = FirstNode->Suc; ChooseInitialTour(); Cost = LinKernighan(); if (FirstNode->BestSuc) { /* Merge tour with current best tour */ t = FirstNode; while ((t = t->Next = t->BestSuc) != FirstNode); Cost = MergeWithTour(); } if (Dimension == DimensionSaved && Cost >= *OrdinalTourCost && BetterCost > *OrdinalTourCost) { /* Merge tour with ordinal tour */ for (i = 1; i < Dimension; i++) NodeSet[i].Next = &NodeSet[i + 1]; NodeSet[Dimension].Next = &NodeSet[1]; Cost = MergeWithTour(); } if (Cost < BetterCost) { if (TraceLevel >= 1) { /* printff("* %d: Cost = " GainFormat, Trial, Cost); if (Optimum != MINUS_INFINITY && Optimum != 0) printff(", Gap = %0.4f%%", 100.0 * (Cost - Optimum) / Optimum); printff(", Time = %0.2f sec. %s\n", fabs(GetTime() - EntryTime), Cost < Optimum ? "<" : Cost == Optimum ? "=" : ""); */ } BetterCost = Cost; RecordBetterTour(); if (Dimension == DimensionSaved && BetterCost < BestCost) WriteTour(OutputTourFileName, BetterTour, BetterCost); if (StopAtOptimum && BetterCost == Optimum) break; AdjustCandidateSet(); HashInitialize(HTable); HashInsert(HTable, Hash, Cost); } else if (TraceLevel >= 2) printff(" %d: Cost = " GainFormat ", Time = %0.2f sec.\n", Trial, Cost, fabs(GetTime() - EntryTime)); /* Record backbones if wanted */ if (Trial <= BackboneTrials && BackboneTrials < MaxTrials) { SwapCandidateSets(this); AdjustCandidateSet(); if (Trial == BackboneTrials) { if (TraceLevel >= 1) { printff("# %d: Backbone candidates ->\n", Trial); CandidateReport(); } } else SwapCandidateSets(this); } } if (BackboneTrials > 0 && BackboneTrials < MaxTrials) { if (Trial > BackboneTrials || (Trial == BackboneTrials && (!StopAtOptimum || BetterCost != Optimum))) SwapCandidateSets(this); t = FirstNode; do { free(t->BackboneCandidateSet); t->BackboneCandidateSet = 0; } while ((t = t->Suc) != FirstNode); } t = FirstNode; if (Norm == 0) { do t = t->BestSuc = t->Suc; while (t != FirstNode); } do (t->Suc = t->BestSuc)->Pred = t; while ((t = t->BestSuc) != FirstNode); if (Trial > MaxTrials) Trial = MaxTrials; ResetCandidateSet(); return BetterCost; }
typename IntegerImpl<T>::value_type IntegerImpl<T>::ftoi( MAPM const &d ) { MAPM const temp( d.sign() >= 0 ? d.floor() : d.ceil() ); unique_ptr<char[]> const buf( new char[ temp.exponent() + 3 ] ); temp.toIntegerString( buf.get() ); return ztd::aton<value_type>( buf.get() ); }
void retro_deinit(void) { app.reset(); }
void retro_get_system_av_info(struct retro_system_av_info *info) { app->get_system_av_info(*info); }
static void _idle() { _okinawa_demo->idle(); }
static void _reshape(int x, int y) { _okinawa_demo->reshape(x, y); }
void async_tm_add(unique_ptr<HandlerCallback<int64_t>> cb, int64_t a, int64_t b) override { cb->result(a + b); }
static void _display() { _okinawa_demo->display(); }
void Ex102SeekingNeuralApp::update() { v->steer( targets ); v->update(); }
void Shutdown(const wstring& className) { mGame->Shutdown(); UnregisterClass(className.c_str(), mWindow.hInstance); }
bool hasNext() { return camera_results->next(); }
bool retro_load_game(const struct retro_game_info *info) { last_input_state = LibretroGLApplication::InputState{}; auto name = app->get_application_name_short(); auto ms_name = name + "_multisample"; name += "_resolution"; string res = "Internal resolution; "; auto resolutions = app->get_resolutions(); for (auto& r : resolutions) res += to_string(r.width) + "x" + to_string(r.height) + "|"; res.resize(res.size() - 1); retro_variable variables[] = { { name.c_str(), res.c_str() }, { ms_name.c_str(), "Multisample; 1x|2x|4x" }, { nullptr, nullptr }, }; environ_cb(RETRO_ENVIRONMENT_SET_VARIABLES, variables); enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_XRGB8888; if (!environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) { log("XRGB8888 is not supported."); return false; } hw_render.context_reset = context_reset; hw_render.context_destroy = context_destroy; hw_render.bottom_left_origin = true; hw_render.depth = true; hw_render.stencil = true; #ifdef GL_DEBUG hw_render.debug_context = true; #endif hw_render.context_type = RETRO_HW_CONTEXT_OPENGL_CORE; app->get_context_version(hw_render.version_major, hw_render.version_minor); if (!environ_cb(RETRO_ENVIRONMENT_SET_HW_RENDER, &hw_render)) return false; const char *libretro = nullptr; if (!environ_cb(RETRO_ENVIRONMENT_GET_LIBRETRO_PATH, &libretro) || !libretro) { log("Can't determine libretro path."); return false; } ContextManager::get().set_dir(Path::basedir(libretro)); log("Loaded from dir: %s.", libretro); app->load(); update_variables(); struct retro_frame_time_callback cb = { frame_time_cb, 1000000 / 60 }; use_frame_time_cb = environ_cb(RETRO_ENVIRONMENT_SET_FRAME_TIME_CALLBACK, &cb); return true; }
static void _keyboard(unsigned char key, int x, int y) { _okinawa_demo->keyboard(key, x, y); }
void retro_unload_game(void) { app->unload(); }
void * worker_routine ( void * arg ) { // Verify that the version of the library that we linked against is // compatible with the version of the headers we compiled against. GOOGLE_PROTOBUF_VERIFY_VERSION; if ( arg ) { arg = NULL; } while ( 1 ) { // Receive a message zmq::message_t message; receiver.recv(&message); shared_ptr<Reply> r = make_shared<Reply>(); unique_ptr<::google::protobuf::io::CodedInputStream> coded_input(new ::google::protobuf::io::CodedInputStream(reinterpret_cast<unsigned char*>(message.data()), message.size())); coded_input->SetTotalBytesLimit(1073741824, 536870912); // total_bytes_limit=1024*1024*1024, warning_threshold=512*1024*1024 r->ParseFromCodedStream(coded_input.get()); if ( r->has_q() ) { const string& storeKey = getKey(r->q(), r->rt(), r->t()); if ( responses.find(storeKey) == responses.end() ) { responses[storeKey] = make_shared<Response>(); } const shared_ptr<Response>& spr = responses[storeKey]; if ( !(spr.get()) ) { cerr << "storeKey is UNIQUE: " << storeKey << "\n"; } else { spr->push_back(r); if ( r->has_s() || (r->has_c() && spr->size()==workers_count) ) { // all replies are here const shared_ptr<string>& ss = spr->getReply(); jsonise(*ss, *(spr->getReplies())); ss->append("}"); spr->setReady(); { lock_guard<mutex> lg(mtx); completed_responses[storeKey] = spr; } responses.erase(storeKey); } else if ( spr->size() == workers_count ) { // send it to thread pool to process shared_ptr<ProcessTask> pt(new ProcessTask(spr, storeKey)); pool->run(pt); // delete pt after finish job. responses.erase(storeKey); } } } else { cerr << "Invalid message for Reply which does not have query string." << "\n"; } } // Optional: Delete all global objects allocated by libprotobuf. google::protobuf::ShutdownProtobufLibrary(); pthread_exit(NULL); return NULL; }
void retro_get_system_info(struct retro_system_info *info) { retro_init(); app->get_system_info(*info); }
void recursive_parser_test::tear_down() { parser_.reset(nullptr); parser_factory_.reset(nullptr); }
ReturnFlag SIM::run_() { GAPopulation<CodeVInt, GAIndividual<CodeVInt>> subPopul(m_popsize); GAIndividual<CodeVInt> ia, ib; int i, n; double p; int flag, flag1; double bestlen = DBL_MAX; vector<int> arr(m_numDim); dynamic_cast<TermMean*>(m_term.get())->initialize(mean()); while (!ifTerminating()) { /*if(Global::msp_global->mp_problem->getEvaluations()/m_saveFre<m_num){ mean<<diffEdges()<<" "<<Global::msp_global->mp_problem->getEvaluations()<<endl; }*/ #ifdef OFEC_DEMON for (i = 0; i<this->getPopSize(); i++) updateBestArchive(this->m_pop[i]->self()); vector<Algorithm*> vp; vp.push_back(this); msp_buffer->updateBuffer_(&vp); #endif //cout<<Global::msp_global->mp_problem->getEvaluations()<<endl; n = 0; while (n<m_popsize) { flag = 0; flag1 = 0; selection(ia, ib); p = Global::msp_global->mp_uniformAlg->Next(); if (p <= m_PC) { *subPopul.getPop()[n++] = crossover(ia, ib); flag = 1; } if (flag == 0) { if (n<m_popsize - 1) { *subPopul.getPop()[n++] = ia; *subPopul.getPop()[n++] = ib; } else { *subPopul.getPop()[n++] = ia; flag1 = 1; } } p = Global::msp_global->mp_uniformAlg->Next(); if (p <= m_PM) { if (flag == 1 || flag1 == 1) mutation(*subPopul.getPop()[n - 1]); else { mutation(*subPopul.getPop()[n - 2]); mutation(*subPopul.getPop()[n - 1]); } } } for (i = 0; i<m_popsize; i++) subPopul.getPop()[i]->evaluate(); *(static_cast<GAPopulation<CodeVInt, GAIndividual<CodeVInt>>*>(this)) = subPopul; #ifdef OFEC_CONSOLE OptimalEdgeInfo::getOptimalEdgeInfo()->recordEdgeInfo<GAIndividual<CodeVInt>>(Global::msp_global.get(), Solution<CodeVInt>::getBestSolutionSoFar(), m_pop, m_num, m_popsize, m_saveFre); #endif m_iter++; } #ifdef OFEC_CONSOLE OptimalEdgeInfo::getOptimalEdgeInfo()->recordEdgeInfo<GAIndividual<CodeVInt>>(Global::msp_global.get(), Solution<CodeVInt>::getBestSolutionSoFar(), m_pop, m_num, m_popsize, m_saveFre, false); OptimalEdgeInfo::getOptimalEdgeInfo()->recordLastInfo(Global::msp_global->m_runId, Global::msp_global->mp_problem->getEvaluations()); #endif return Return_Terminate; }
void DecryptionManager::PacketHandler::handle(unique_ptr<Packet> packet) { if (packet->payloadSize_ != 0) { // In case of error or TCP handshake messages, just write packets back switch(state_) { case NOT_STARTED: state_ = INIT_SEC_AP_REQ; parseFirstMessage(packet.get()); break; case INIT_SEC_AP_REQ: if (packet->srcAddr_ != serverAddr_) { onError("Expecting server side mutual auth reply"); } else { state_ = MUTUAL_AUTH_AP_REP; parseSecondMessage(packet.get()); } break; case MUTUAL_AUTH_AP_REP: if (packet->srcAddr_ != clientAddr_) { onError("Expecting client side first empty token"); } else { state_ = FIRST_EMPTY_TOKEN; } break; case FIRST_EMPTY_TOKEN: if (packet->srcAddr_ != serverAddr_) { onError("Expecting server side security layer message"); } else { state_ = SECURITY_LAYER_MESSAGE_SERVER; } break; case SECURITY_LAYER_MESSAGE_SERVER: if (packet->srcAddr_ != clientAddr_) { onError("Expecting client side security layer message"); } else { state_ = SECURITY_LAYER_MESSAGE_CLIENT; } break; case SECURITY_LAYER_MESSAGE_CLIENT: if (packet->srcAddr_ != serverAddr_) { onError("Expecting server side second empty token"); } else { state_ = SECOND_EMPTY_TOKEN; } break; case SECOND_EMPTY_TOKEN: if (packet->srcAddr_ != clientAddr_) { onError("Expecting first encrypted application message"); } else { state_ = ENCRYPTED_MESSAGE; handleApplicationMessage(std::move(packet)); return; } break; case ENCRYPTED_MESSAGE: handleApplicationMessage(std::move(packet)); return; default: onError("Bug: wrong state"); } } decryptionManager_->writePacket(std::move(packet)); }
int32_t AppInterfaceImpl::sendMessageExisting(const CmdQueueInfo &sendInfo, unique_ptr<ZinaConversation> zinaConversation) { LOGGER(DEBUGGING, __func__, " -->"); errorCode_ = SUCCESS; // Don't send this to my own device if (sendInfo.queueInfo_toSibling && sendInfo.queueInfo_deviceId == scClientDevId_) { return SUCCESS; } string supplements = createSupplementString(sendInfo.queueInfo_attachment, sendInfo.queueInfo_attributes); if (zinaConversation == nullptr) { zinaConversation = ZinaConversation::loadConversation(ownUser_, sendInfo.queueInfo_recipient, sendInfo.queueInfo_deviceId, *store_); if (!zinaConversation->isValid()) { LOGGER(ERROR, "ZINA conversation is not valid. Owner: ", ownUser_, ", recipient: ", sendInfo.queueInfo_recipient, ", recipientDeviceId: ", sendInfo.queueInfo_deviceId); errorCode_ = zinaConversation->getErrorCode(); errorInfo_ = sendInfo.queueInfo_deviceId; getAndMaintainRetainInfo(sendInfo.queueInfo_transportMsgId & ~0xff, false); Utilities::wipeString(const_cast<string&>(sendInfo.queueInfo_attachment)); Utilities::wipeString(const_cast<string&>(sendInfo.queueInfo_attributes)); return errorCode_; } } cJSON* convJson = nullptr; LOGGER_BEGIN(INFO) convJson = zinaConversation->prepareForCapture(nullptr, true); LOGGER_END // Encrypt the user's message and the supplementary data if necessary MessageEnvelope envelope; int32_t result = ZinaRatchet::encrypt(*zinaConversation, sendInfo.queueInfo_message, envelope, supplements, *store_); Utilities::wipeString(const_cast<string&>(sendInfo.queueInfo_message)); Utilities::wipeString(supplements); LOGGER_BEGIN(INFO) convJson = zinaConversation->prepareForCapture(convJson, false); char* out = cJSON_PrintUnformatted(convJson); string convState(out); cJSON_Delete(convJson); free(out); MessageCapture::captureSendMessage(sendInfo.queueInfo_recipient, sendInfo.queueInfo_msgId, sendInfo.queueInfo_deviceId, convState, sendInfo.queueInfo_attributes, !sendInfo.queueInfo_attachment.empty(), *store_); LOGGER_END Utilities::wipeString(const_cast<string&>(sendInfo.queueInfo_attachment)); Utilities::wipeString(const_cast<string&>(sendInfo.queueInfo_attributes)); // If encrypt does not return encrypted data then report an error, code was set by the encrypt function if (result != SUCCESS) { LOGGER(ERROR, "Encryption failed, no wire message created, device id: ", sendInfo.queueInfo_deviceId); LOGGER(INFO, __func__, " <-- Encryption failed."); getAndMaintainRetainInfo(sendInfo.queueInfo_transportMsgId & ~0xff, false); return result; } result = zinaConversation->storeConversation(*store_); if (result != SUCCESS) { LOGGER(ERROR, "Storing ratchet data failed after encryption, device id: ", sendInfo.queueInfo_deviceId); LOGGER(INFO, __func__, " <-- Encryption failed."); return result; } /* * Create the message envelope: { "name": <string> # sender's name "scClientDevId": <string> # sender's long device id "supplement": <string> # supplementary data, encrypted, B64 "message": <string> # message, encrypted, B64 } */ envelope.set_name(ownUser_); envelope.set_scclientdevid(scClientDevId_); envelope.set_msgid(sendInfo.queueInfo_msgId); envelope.set_msgtype(static_cast<uint32_t>(sendInfo.queueInfo_transportMsgId & MSG_TYPE_MASK)); uint8_t binDevId[20]; size_t res = hex2bin(sendInfo.queueInfo_deviceId.c_str(), binDevId); if (res == 0) envelope.set_recvdevidbin(binDevId, 4); string serialized = envelope.SerializeAsString(); // We need to have them in b64 encoding, check if buffer is large enough. Allocate twice // the size of binary data, this is big enough to hold B64 plus paddling and terminator if (serialized.size() * 2 > tempBufferSize_) { delete tempBuffer_; tempBuffer_ = new char[serialized.size()*2]; tempBufferSize_ = serialized.size()*2; } size_t b64Len = b64Encode((const uint8_t*)serialized.data(), serialized.size(), tempBuffer_, tempBufferSize_); // replace the binary data with B64 representation serialized.assign(tempBuffer_, b64Len); #ifdef SC_ENABLE_DR_SEND uint32_t retainInfo = getAndMaintainRetainInfo(sendInfo.queueInfo_transportMsgId & ~0xff, true); if (retainInfo != 0) { doSendDataRetention(retainInfo, sendInfo); } #endif transport_->sendAxoMessage(sendInfo, serialized); LOGGER(DEBUGGING, __func__, " <--"); return SUCCESS; }
void DecryptionManager::writePacket(unique_ptr<Packet> packet) { capturer_->writePacket(packet.get()); }
void InputWidgetProxyCollection::insert( const string& key, unique_ptr<IInputWidgetProxy> proxy) { m_proxies[key] = proxy.release(); }
void SceneNode::addChild(unique_ptr<SceneNode> pChild) { m_pChildNodes.push_back(pChild.release()); }
namespace fuse { unique_ptr<VsfsFuse> instance_; VsfsFuse *vsfs; Status VsfsFuse::init(const string &basedir, const string &mnt, const string &host, int port, const string& sm) { LOG(INFO) << "VsfsFuse starts initilizing..."; // This function should be only called once. CHECK(instance_.get() == NULL) << "VsfsFuse should only be initialized once."; string absolute_basedir = fs::absolute(basedir).string(); string absolute_mnt = fs::absolute(mnt).string(); instance_.reset(new VsfsFuse(absolute_basedir, absolute_mnt, host, port, sm)); auto status = instance_->storage_manager()->init(); if (!status.ok()) { LOG(ERROR) << "Failed to initialize StorageManager: " << status.message(); return status; } vsfs = instance_.get(); LOG(INFO) << "VsfsFuse fully initialized."; status = vsfs->client_->init(); if (!status.ok()) { LOG(ERROR) << "Failed to initialize RPC connection to VSFS: " << status.message(); return status; } vsfs->client_->mkdir("/", 0777, fuse_get_context()->uid, fuse_get_context()->gid); return Status::OK; } void VsfsFuse::destory() { LOG(INFO) << "VsfsFuse is shutting down..."; instance_.reset(); } VsfsFuse* VsfsFuse::instance() { return instance_.get(); } VsfsFuse::VsfsFuse(const string &basedir, const string &mnt, const string &host, int port, const string& sm) : basedir_(basedir), mount_point_(mnt), host_(host), port_(port), client_(new VSFSRpcClient(host, port)) { if (sm == "posix") { storage_manager_.reset(new PosixStorageManager(basedir)); } else if (sm == "object") { storage_manager_.reset( new ObjectStorageManager(basedir, FLAGS_object_storage_dirwidth)); } else { CHECK(false) << "Unknown StorageManager type: " << sm; } } VsfsFuse::~VsfsFuse() { } const string& VsfsFuse::basedir() const { return basedir_; } string VsfsFuse::mnt_path(const string &vsfs_path) const { return (fs::path(mount_point_) / vsfs_path).string(); } void VsfsFuse::add_file(uint64_t fd, File* file) { if (!file) { return; } MutexGuard guard(obj_map_mutex_); fh_to_obj_map_[fd].reset(file); } Status VsfsFuse::close_file(uint64_t fd) { MutexGuard guard(obj_map_mutex_); auto it = fh_to_obj_map_.find(fd); CHECK(it != fh_to_obj_map_.end()); auto file_obj = it->second.get(); auto status = file_obj->close(); fh_to_obj_map_.erase(fd); return status; } File* VsfsFuse::get_file(uint64_t fd) { MutexGuard guard(obj_map_mutex_); auto it = fh_to_obj_map_.find(fd); if (it == fh_to_obj_map_.end()) { return nullptr; } else { return it->second.get(); } } // VSFS Operations void* vsfs_init(struct fuse_conn_info *conn) { LOG(INFO) << "Fuse component initializing..."; (void) conn; return nullptr; } void vsfs_destroy(void *data) { (void) data; VsfsFuse::destory(); } int vsfs_statfs(const char*, struct statvfs *stbuf) { auto status = VsfsFuse::instance()->storage_manager()->statfs(stbuf); if (!status.ok()) { LOG(ERROR) << "Failed to statvfs: " << status.message(); return status.error(); } return 0; } int vsfs_access(const char* path, int flag) { PosixPath vsp(path); if (!vsp.is_validate()) { return -EINVAL; } else if (!vsp.is_query()) { (void) flag; /// TODO(eddyxu): always success for now. return 0; // return access(abspath.c_str(), flag); } else if (vsp.is_query()) { assert(true); } else { return -ENOENT; } return 0; } int vsfs_getattr(const char* path, struct stat* stbuf) { PosixPath vsp(path); if (!vsp.is_validate()) { return -EINVAL; } if (vsp.is_query()) { stbuf->st_mode |= S_IFDIR; } else if (vsp.is_result()) { stbuf->st_mode |= S_IFLNK; stbuf->st_size = vsp.result().size(); } else { // TODO(eddyxu): replace with the below commented code when the writes can // update file size. RpcFileInfo file_info; auto status = VsfsFuse::instance()->client()->getattr(path, &file_info); if (!status.ok()) { LOG(ERROR) << "GETATTR: Failed to getattr from master server: " << status.message(); return status.error(); } stbuf->st_uid = file_info.uid; stbuf->st_gid = file_info.gid; stbuf->st_mode = file_info.mode; stbuf->st_atime = file_info.atime; stbuf->st_ctime = file_info.ctime; stbuf->st_mtime = file_info.mtime; if (S_ISDIR(file_info.mode) || S_ISLNK(file_info.mode)) { stbuf->st_size = file_info.size; return 0; } struct stat buf; status = VsfsFuse::instance()->storage_manager() ->getattr(path, file_info.object_id, &buf); if (!status.ok()) { return status.error(); } stbuf->st_size = buf.st_size; stbuf->st_ino = buf.st_ino; stbuf->st_dev = buf.st_dev; stbuf->st_nlink = buf.st_nlink; stbuf->st_rdev = buf.st_rdev; stbuf->st_blksize = buf.st_blksize; stbuf->st_blocks = buf.st_blocks; } return 0; } int vsfs_fgetattr(const char*, struct stat* stbuf, struct fuse_file_info* fi) { int ret = fstat(fi->fh, stbuf); if (ret == -1) { return -errno; } return 0; } int vsfs_ioctl(const char*, int cmd, void *arg, struct fuse_file_info* fi, unsigned int flags, void *data) { (void) flags; (void) data; int ret = ioctl(fi->fh, cmd, arg); if (ret == -1) { return -errno; } return 0; } int vsfs_utimens(const char* path, const struct timespec tv[2]) { return VsfsFuse::instance()->client() ->utimens(path, tv[0].tv_sec, tv[1].tv_sec).error(); } int vsfs_chmod(const char* path, mode_t mode) { return VsfsFuse::instance()->client()->chmod(path, mode).error(); } int vsfs_chown(const char* path, uid_t uid, gid_t gid) { return VsfsFuse::instance()->client()->chown(path, uid, gid).error(); } int vsfs_truncate(const char*, off_t) { return 0; } int vsfs_opendir(const char*, struct fuse_file_info*) { // TODO(lxu): check permission. return 0; } int vsfs_releasedir(const char* path, struct fuse_file_info* info) { (void) path; (void) info; return 0; } int vsfs_readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t, struct fuse_file_info*) { VLOG(0) << "Readdir: " << path; PosixPath vsp(path); filler(buf, ".", NULL, 0); filler(buf, "..", NULL, 0); Status status; if (vsp.is_query()) { ComplexQuery complex_query; status = complex_query.parse(path); vector<string> result_files; Status status = vsfs->client()->search(complex_query, &result_files); if (!status.ok()) { LOG(ERROR) << "Failed to search: " << status.message(); return status.error(); } LOG(INFO) << result_files.size() << " files are found."; for (const string &file : result_files) { struct stat stbuf; status = vsfs->client()->getattr(file, &stbuf); if (!status.ok()) { LOG(ERROR) << "Failed to get attribute for file: " << file << status.error(); return status.error(); } stbuf.st_mode |= S_IFLNK; string name(file.size(), 0); std::transform(file.begin(), file.end(), name.begin(), [](int c) { return c == '/' ? '#' : c; }); filler(buf, name.c_str(), &stbuf, 0); } } else { vector<string> subfiles; status = VsfsFuse::instance()->client()->readdir(path, &subfiles); if (!status.ok()) { return status.error(); } for (const auto& subfile : subfiles) { filler(buf, subfile.c_str(), NULL, 0); } } return 0; } /** * \brief Create a directory */ int vsfs_mkdir(const char* path, mode_t mode) { auto status = VsfsFuse::instance()->client() ->mkdir(path, mode, fuse_get_context()->uid, fuse_get_context()->gid); if (!status.ok()) { LOG(ERROR) << "Failed to mkdir: " << status.message(); return status.error(); } status = VsfsFuse::instance()->storage_manager()->mkdir(path, mode); return status.error(); } int vsfs_mknod(const char* path, mode_t mode, dev_t dev) { ObjectId oid; (void) dev; // handle case for S_IFCHR, S_IFBLK which needs dev Status status = vsfs->client()->create(path, mode, getuid(), getgid(), &oid); if (!status.ok()) { LOG(ERROR) << "Failed to mknod: " << status.message(); return status.error(); } return 0; } int vsfs_rmdir(const char* path) { auto status = VsfsFuse::instance()->client()->rmdir(path); if (!status.ok()) { LOG(ERROR) << "Failed to rmdir: " << path << ": " << status.message(); return status.error(); } status = VsfsFuse::instance()->storage_manager()->rmdir(path); return status.error(); } int vsfs_create(const char* path, mode_t mode, struct fuse_file_info *fi) { ObjectId oid; Status status = vsfs->client()->create(path, mode, getuid(), getgid(), &oid); if (!status.ok()) { LOG(ERROR) << "Failed to create file: " << status.message(); return status.error(); } File *file; status = VsfsFuse::instance()->storage_manager() ->open(path, oid, fi->flags | O_CREAT, mode, &file); if (!status.ok()) { LOG(ERROR) << "StorageManager failed to create file: " << status.message(); return status.error(); } int fd = file->fd(); fi->fh = fd; VsfsFuse::instance()->add_file(fd, file); return 0; } int vsfs_open(const char* path, struct fuse_file_info* fi) { ObjectId oid; auto status = vsfs->client()->open(path, &oid); if (!status.ok()) { LOG(ERROR) << "Failed to open file: " << status.message(); return status.error(); } File *file; status = VsfsFuse::instance()->storage_manager() ->open(path, oid, fi->flags, &file); if (!status.ok()) { LOG(ERROR) << "StorageManager failed to open file: " << status.message(); return status.error(); } int fd = file->fd(); VsfsFuse::instance()->add_file(fd, file); fi->fh = fd; return 0; } int vsfs_unlink(const char* path) { ObjectId obj_id; Status status = vsfs->client()->unlink(path, &obj_id); if (!status.ok()) { LOG(ERROR) << "Failed to remove a file from master server:" << status.message(); return status.error(); } status = VsfsFuse::instance()->storage_manager()->unlink(path, obj_id); return status.error(); } int vsfs_release(const char* path, struct fuse_file_info *fi) { auto status = VsfsFuse::instance()->close_file(fi->fh); if (!status.ok()) { LOG(ERROR) << "Closing fd=" << fi->fh; LOG(ERROR) << "Failed to release file: " << path << ": " << status.message(); } return status.error(); } int vsfs_readlink(const char* path, char* buf, size_t size) { PosixPath vsp(path); if (vsp.is_query()) { } else if (vsp.is_result()) { VLOG(1) << "Resolve query result: " << path; string result_file = vsp.result(); string linked_file(result_file.size(), 0); std::transform(result_file.begin(), result_file.end(), linked_file.begin(), [](int c) { return c == '#' ? '/' : c; }); string mnt_path = VsfsFuse::instance()->mnt_path(linked_file); strncpy(buf, mnt_path.c_str(), size); buf[mnt_path.size()] = 0; } else { ObjectId object_id; auto status = VsfsFuse::instance()->client()->object_id(path, &object_id); if (!status.ok()) { LOG(ERROR) << "Failed to get object ID for path: " << path; return status.error(); } ssize_t retlen; status = VsfsFuse::instance()->storage_manager() ->readlink(path, object_id, buf, size, &retlen); if (!status.ok()) { LOG(ERROR) << "Failed to read link: " << path << ": " << status.message(); return status.error(); } } return 0; } int vsfs_read(const char*, char *buf, size_t size, off_t offset, struct fuse_file_info* fi) { File *file_obj = VsfsFuse::instance()->get_file(fi->fh); if (!file_obj) { LOG(ERROR) << "File does not existed."; return -EBADF; } ssize_t nread = pread(fi->fh, buf, size, offset); if (nread == -1) { LOG(ERROR) << "VSFS_READ ERROR: " << strerror(errno); return -errno; } return nread; } int vsfs_write(const char*, const char* buf, size_t size, off_t offset, struct fuse_file_info *fi) { File *file_obj = VsfsFuse::instance()->get_file(fi->fh); if (!file_obj) { LOG(ERROR) << "File object does not exist."; return -EBADF; } ssize_t nwrite = file_obj->write(buf, size, offset); if (nwrite == -1) { LOG(ERROR) << strerror(errno); return -errno; } // TODO(lxu): need to update size in masterd. return nwrite; } int vsfs_flush(const char* , struct fuse_file_info* fi) { // We are using open(2), there is nothing to flush. int res; res = close(dup(fi->fh)); if (res == -1) { return -errno; } return 0; } int vsfs_getxattr(const char* path, const char* name, char *value, size_t vlen) { (void) path; (void) name; (void) value; (void) vlen; return 0; } #if defined(FUSE_29) int vsfs_flock(const char* path, struct fuse_file_info *fi, int op) { if (flock(fi->fh, op) == -1) { LOG(ERROR) << "Failed to flock(" << path << ", " << op << "), fd=" << fi->fh; return -errno; } return 0; } int vsfs_write_buf(const char*, struct fuse_bufvec* buf, off_t off, struct fuse_file_info* fi) { ssize_t nwrite = 0; ssize_t total_write = 0; File *file = VsfsFuse::instance()->get_file(fi->fh); if (!file) { return -EINVAL; } for (size_t i = 0; i < buf->count; i++) { nwrite = file->write(buf->buf[i].mem, buf->buf[i].size, off); if (nwrite == -1) { return -errno; } total_write += nwrite; } return total_write; } #endif int vsfs_lock(const char*, struct fuse_file_info* fi, int cmd, struct flock* flock) { if (fcntl(fi->fh, cmd, flock) == -1) { return -errno; } return 0; } int vsfs_fsync(const char*, int, struct fuse_file_info* fi) { if (fsync(fi->fh) == 0) { return 0; } return -errno; } int vsfs_symlink(const char* fpath, const char* link_path) { ObjectId oid; Status status = vsfs->client()->create( link_path, (0666 && fuse_get_context()->umask) | S_IFLNK, fuse_get_context()->uid, fuse_get_context()->gid, &oid); if (!status.ok()) { LOG(ERROR) << "Failed to create file in vsfs namespace: " << status.message(); return status.error(); } status = VsfsFuse::instance()->storage_manager() ->symlink(fpath, link_path, oid); if (!status.ok()) { LOG(ERROR) << "Failed to symlink: " << status.message(); return status.error(); } return 0; } } // namespace fuse
void retro_run(void) { bool updated = false; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated) update_variables(); GLuint fb = hw_render.get_current_framebuffer(); if (multisample) Framebuffer::set_back_buffer(ms_fbo); else Framebuffer::set_back_buffer(fb); Framebuffer::unbind(); LibretroGLApplication::InputState state{}; input_poll_cb(); float factor = float(1.0f / 0x8000); float analog_x = factor * input_state_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X); float analog_y = factor * input_state_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y); float analog_ry = factor * input_state_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y); float analog_rx = factor * input_state_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X); state.analog.x = analog_x; state.analog.y = analog_y; state.analog.rx = analog_rx; state.analog.ry = analog_ry; state.pressed.left = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT); state.pressed.right = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT); state.pressed.up = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP); state.pressed.down = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN); state.pressed.a = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A); state.pressed.b = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B); state.pressed.x = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X); state.pressed.y = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y); state.pressed.l = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L); state.pressed.r = input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R); state.triggered.left = state.pressed.left && !last_input_state.pressed.left; state.triggered.right = state.pressed.right && !last_input_state.pressed.right; state.triggered.up = state.pressed.up && !last_input_state.pressed.up; state.triggered.down = state.pressed.down && !last_input_state.pressed.down; state.triggered.a = state.pressed.a && !last_input_state.pressed.a; state.triggered.b = state.pressed.b && !last_input_state.pressed.b; state.triggered.x = state.pressed.x && !last_input_state.pressed.x; state.triggered.y = state.pressed.y && !last_input_state.pressed.y; state.triggered.l = state.pressed.l && !last_input_state.pressed.l; state.triggered.r = state.pressed.r && !last_input_state.pressed.r; last_input_state = state; if (!use_frame_time_cb) frame_delta = 1.0f / 60.0f; app->run(frame_delta, state); if (multisample) { ms_fbo.blit(fb, width, height, GL_COLOR_BUFFER_BIT); ms_fbo.invalidate(); } video_cb(RETRO_HW_FRAME_BUFFER_VALID, width, height, 0); }
VsfsFuse* VsfsFuse::instance() { return instance_.get(); }
int Server::isset(unique_ptr<Client>& c) { return isset(c->getFd()); }