bool EventStreamHandler<ButtonsType>::InitializeQueues(
    const google::protobuf::RepeatedPtrField<StartGamePB::ConnectedPortPB>&
        ports) {
  if (ports.size() > 4) {
    LOG(ERROR) << "Too many ports. Expected 0 to 4, saw " << ports.size();
    return false;
  }

  std::set<Port> handled_ports;

  int local_ports_connected = 0;

  for (const StartGamePB::ConnectedPortPB connected_port : ports) {
    Port port_id = connected_port.port();

    if (port_id == PORT_ANY) {
      LOG(ERROR)
          << "Server returned connected port with unexpected value PORT_ANY.";
      return false;
    }

    if (handled_ports.find(port_id) != handled_ports.end()) {
      LOG(ERROR) << "Duplicate port returned from server: "
                 << Port_Name(port_id);
      return false;
    }

    // Actually initialize the port as either local or remote.
    if (local_ports_.find(port_id) != local_ports_.end()) {
      VLOG(3) << "Inserting local queue for connected port:\n"
              << connected_port.DebugString();
      input_queues_.emplace(port_id, std::unique_ptr<ButtonsInputQueue>(
                                         ButtonsInputQueue::MakeLocalQueue(
                                             connected_port.delay_frames())));
      ++local_ports_connected;
    } else {
      VLOG(3) << "Inserting remote queue for connected port:\n"
              << connected_port.DebugString();
      input_queues_.emplace(port_id, std::unique_ptr<ButtonsInputQueue>(
                                         ButtonsInputQueue::MakeRemoteQueue(
                                             connected_port.delay_frames())));
    }

    handled_ports.insert(port_id);
  }

  // Make sure all local ports were connected.
  if (local_ports_.size() != local_ports_connected) {
    LOG(ERROR) << "Failed to connect local ports: ";
    for (const Port local_port : local_ports_) {
      if (handled_ports.find(local_port) == handled_ports.end()) {
        LOG(ERROR) << Port_Name(local_port);
      }
    }

    return false;
  }

  return true;
}
void DiffWrapperBase<T, TDiff>::GetExtraElementDiffs(
    google::protobuf::RepeatedPtrField<ElementDiff> *dst, int i, int j,
    const google::protobuf::RepeatedPtrField<Element> &old_elements,
    const google::protobuf::RepeatedPtrField<Element> &new_elements) {
 assert(dst != nullptr);
 while (i < old_elements.size()) {
    const Element &old_element = old_elements.Get(i);
    ElementDiff *diff = dst->Add();
    Element *old_elementp = nullptr;
    if (!diff || !(old_elementp = diff->mutable_old())) {
      llvm::errs() << "Failed to add diff element\n";
      ::exit(1);
    }
    *old_elementp = old_element;
    diff->set_index(i);
    i++;
 }
 while (j < new_elements.size()) {
    const Element &new_element = new_elements.Get(j);
    ElementDiff *diff = dst->Add();
    Element *new_elementp = nullptr;
    if (!diff || !(new_elementp = diff->mutable_new_())) {
      llvm::errs() << "Failed to add diff element\n";
      ::exit(1);
    }
    *new_elementp = new_element;
    diff->set_index(j);
    j++;
 }
}
template<class TS, class TD> void unwrapCollection(const ::google::protobuf::RepeatedPtrField<TS> src,
    std::vector<TD>& dst) {
    std::back_insert_iterator<std::vector<TD> > backInsertIter(dst);

    dst.clear();

    std::copy(src.begin(), src.end(), backInsertIter);
}
Exemple #4
0
std::vector<T> convert(const google::protobuf::RepeatedPtrField<T>& items)
{
  std::vector<T> result;
  for (int i = 0; i < items.size(); i++) {
    result.push_back(items.Get(i));
  }

  return result;
}
void zina::deserializeVectorClock(const google::protobuf::RepeatedPtrField<VClock> &protoVc, vectorclock::VectorClock<string> *vc)
{
    int32_t numClocks = protoVc.size();

    for (int i = 0; i < numClocks; i++) {
        const VClock &vcData = protoVc.Get(i);
        vc->insertNodeWithValue(vcData.device_id(), vcData.value());
    }
}
Exemple #6
0
bool operator==(const ::google::protobuf::RepeatedPtrField<T>& a, const ::google::protobuf::RepeatedPtrField<T>& b) {
	if (a.size() != b.size())
		return false;
	for (auto aiter=a.begin(), biter=b.begin(); aiter != a.end(); aiter++, biter++ ) {
		if (*aiter != *biter)
			return false;
	}

	return true;
}
void unwrapCollection(const ::google::protobuf::RepeatedPtrField<ObjectWrapper>& src, std::vector<TD>& dst) {
    dst.clear();

    for (auto it = src.begin(); it != src.end(); ++it) {
        const ObjectWrapper& el = (*it);

        TD result;

        unwrap(el, result);

        dst.push_back(result);
    }
}
Exemple #8
0
void SpotifyService::FillPlaylist(
    QStandardItem* item,
    const google::protobuf::RepeatedPtrField<pb::spotify::Track>& tracks) {
  if (item->hasChildren()) item->removeRows(0, item->rowCount());

  for (int i = 0; i < tracks.size(); ++i) {
    Song song;
    SongFromProtobuf(tracks.Get(i), &song);

    QStandardItem* child = CreateSongItem(song);

    item->appendRow(child);
  }
}
bool UserManager::init(const ::google::protobuf::RepeatedPtrField<UserOptions>& user_options)
{
	int o_size = user_options.size();
	for (int i = 0; i < o_size; ++i) {
		const UserOptions& user = user_options.Get(i);
		UserInfo* uinfo = new UserInfo(user.name(), user.file_name());
		uinfo->pending_events = new PendingEvents(user.file_name());
		if (!uinfo->pending_events->init()) {
			LOG(ERROR, "Failed to init user \"%s\"", user.name().c_str());
			return false;
		}
		_users[user.name()] = uinfo;
	}
	return true;
}
bool DiffWrapperBase<T, TDiff>::GetElementDiffs(
    google::protobuf::RepeatedPtrField<ElementDiff> *dst,
    const google::protobuf::RepeatedPtrField<Element> &old_elements,
    const google::protobuf::RepeatedPtrField<Element> &new_elements) {
  bool differs = false;
  assert(dst != nullptr);
  int i = 0;
  int j = 0;
  while (i < old_elements.size() && j < new_elements.size()) {
    const Element &old_element = old_elements.Get(i);
    const Element &new_element = new_elements.Get(i);

    if (Diff(old_element, new_element)) {
      ElementDiff *diff = dst->Add();
      Element *old_elementp = nullptr;
      Element *new_elementp = nullptr;
      if (!diff || !(old_elementp = diff->mutable_old()) ||
          !(new_elementp = diff->mutable_new_())) {
        llvm::errs() << "Failed to add diff element\n";
        ::exit(1);
      }
      *old_elementp = old_element;
      *new_elementp = new_element;
      diff->set_index(i);
      differs = true;
    }
    i++;
    j++;
  }
  if (old_elements.size() != new_elements.size()) {
    GetExtraElementDiffs(dst, i, j, old_elements, new_elements);
    differs = true;
  }
  return differs;
}
bool CUserShopStrategy::Init( CUser* pUser, 
							 const ::google::protobuf::RepeatedPtrField< ::db_user_shop >& shop_data, 
							 const ::google::protobuf::RepeatedPtrField< ::db_user_shop_buy >& shop_buy_data)
{
	ASSERT(pUser);
	ASSERT(m_mapWeightFactor.empty());
	m_mapWeightFactor.clear();

	m_pUser = pUser;

	for (::google::protobuf::RepeatedPtrField< ::db_user_shop >::const_iterator it = shop_data.begin() ; it != shop_data.end() ; ++it){
		ASSERT(m_userShopType2Shop.find((CShop::ESHOPTYPE)it->shop_type()) == m_userShopType2Shop.end());
		CShop* pShop = new CShop((CShop::ESHOPTYPE)it->shop_type());
		ASSERT(pShop);
		//pShop->eShopType = (CShop::ESHOPTYPE)it->shop_type();					//商店类型
		pShop->iLastAutoRefreshTime = it->last_auto_refresh_time();				//上一次的自动刷新时间
		pShop->iLastManualRefreshTime = it->last_manual_refresh_time();			//上一次的手动刷新时间
		pShop->iLastDayManualRefreshNum = it->last_day_manual_refresh_num();	//最后时间当日手动刷新的次数 
		pShop->iRandomOpenStartTimestamp = it->random_open_start_timestamp();
		pShop->iRandomOpenEndTimestamp = it->random_open_end_timestamp();

		//pShop->iTotalManualRefreshNum = it->total_manual_refresh_num();		//总共的手动刷新次数

		m_userShopType2Shop[pShop->eShopType] = pShop;

		//初始化商店信息
		for (::google::protobuf::RepeatedPtrField< ::db_user_shop_item >::const_iterator itIn = it->items().begin() ; itIn != it->items().end() ; ++itIn){
			stShopItem* pItem = new stShopItem(*itIn);
			bool r = pShop->Append(pItem);
			ASSERT(r && "商店添加道具失败!");
			if (!r){
				delete pItem;
				return false;
			}
		}
	}

	//初始化购买信息
	for (::google::protobuf::RepeatedPtrField< ::db_user_shop_buy >::const_iterator it = shop_buy_data.begin() ; it != shop_buy_data.end() ; ++it){
		std::pair<EELEMENTTYPE, UINT32> key = std::make_pair((EELEMENTTYPE)it->element_type(), it->element_id());
		//ASSERT(m_mapWeightFactor.find(key) == m_mapWeightFactor.end());
		if (m_mapWeightFactor.find(key) != m_mapWeightFactor.end()){
			return false;
		}

		bool isNeed = pUser->IsUserHeroEquipEvolutionNeed((EELEMENTTYPE)it->element_type(), it->element_id());
		CShopItemWeightFactor* factor = new CShopItemWeightFactor(it->last_day_buy_num(), it->last_buy_time(), isNeed);
		m_mapWeightFactor[key] = factor;
	}

	return true;
}
Exemple #12
0
std::vector<T> convert(const google::protobuf::RepeatedPtrField<T>& items)
{
  return std::vector<T>(items.begin(), items.end());
}
e_gsc_errorcode CUserShopStrategy::GetShopInfo(c_gs_shop_info_req::PULLTYPE get_type, user_shop_ESHOPTYPE shop_type, gs_dbs_user_info_op_req &db_req, ::google::protobuf::RepeatedPtrField< ::user_shop > &c_res )
{
	if (get_type == c_gs_shop_info_req::ONE){
		if ( !user_shop_ESHOPTYPE_IsValid(shop_type)){//是否是有效的商店类型
			//c_res.set_error_code(e_gsc_errorcode_unknown_error);
			return e_gsc_errorcode_unknown_error;
		}

		CShop::ESHOPTYPE eShopType = (CShop::ESHOPTYPE)shop_type;
		bool is_open_and_create_new_shop = false;
		if(CheckShopOpen(eShopType, true, is_open_and_create_new_shop)){
			CShop* pShop = _get_shop(eShopType);
			ASSERT(pShop);//check中如果开放了 需要创建就会创建!

			if (is_open_and_create_new_shop){//
				gs_dbs_user_info_op_req::struct_op_shop* op_shop = db_req.add_shops();
				op_shop->set_shop_op_type(gs_dbs_user_info_op_req::struct_op_shop::CREATE);
				pShop->Fill(op_shop->mutable_shop(), c_res.Add());
			}
			else{//不是新开的 则可能要做auto_refresh
				UINT32 new_stamp = 0;
				if(pShop->IsNeedAutoRefresh(new_stamp)){
					bool r = AutoRefreshShop(pShop, new_stamp, db_req, c_res.Add());//告诉db刷新商店! 不需要在这里给客户端 下面会统一给
					ASSERT(r);
				}
				else{
					pShop->Fill(NULL, c_res.Add());
				}
			}
		}
		else{
			//return e_gsc_errorcode_shop_no_unlock;//商店还未解锁 单个商店没有拉到也不是给错误码 因为是数组 给空数组即可
		}
	}
	else if (get_type == c_gs_shop_info_req::ALL){
		for (UINT32 iShopType = CShop::ESHOPTYPE_MIN +1 ; iShopType < CShop::ESHOPTYPE_MAX ; ++iShopType){
			CShop::ESHOPTYPE eShopType = (CShop::ESHOPTYPE)iShopType;
			bool is_open_and_create_new_shop = false;
			if(CheckShopOpen(eShopType, true, is_open_and_create_new_shop)){
				CShop* pShop = _get_shop(eShopType);
				ASSERT(pShop);

				if (is_open_and_create_new_shop){//
					gs_dbs_user_info_op_req::struct_op_shop* op_shop = db_req.add_shops();
					op_shop->set_shop_op_type(gs_dbs_user_info_op_req::struct_op_shop::CREATE);
					pShop->Fill(op_shop->mutable_shop(), c_res.Add());
				}
				else{//不是新开的 则可能要做auto_refresh
					UINT32 new_stamp = 0;
					if(pShop->IsNeedAutoRefresh(new_stamp)){
						bool r = AutoRefreshShop(pShop, new_stamp, db_req, c_res.Add());//告诉db刷新商店! 不需要在这里给客户端 下面会统一给
						ASSERT(r);
					}
					else{
						pShop->Fill(NULL, c_res.Add());
					}
				}
			}
		}
	}
	else{
		//c_res.set_error_code(e_gsc_errorcode_unknown_error);
		return e_gsc_errorcode_unknown_error;
	}

	//c_res.set_error_code(e_gsc_errorcode_success);
	return e_gsc_errorcode_success;
}
Exemple #14
0
std::unique_ptr<Ephemeris<Frame>> Ephemeris<Frame>::ReadFromPreBourbakiMessages(
    google::protobuf::RepeatedPtrField<
        serialization::Plugin::CelestialAndProperties> const& messages,
    Length const& fitting_tolerance,
    typename Ephemeris<Frame>::FixedStepParameters const& fixed_parameters) {
  LOG(INFO) << "Reading "<< messages.SpaceUsedExcludingSelf()
            << " bytes in pre-Bourbaki compatibility mode ";
  std::vector<not_null<std::unique_ptr<MassiveBody const>>> bodies;
  std::vector<DegreesOfFreedom<Frame>> initial_state;
  std::vector<std::unique_ptr<DiscreteTrajectory<Frame>>> histories;
  std::set<Instant> initial_time;
  std::set<Instant> final_time;
  for (auto const& message : messages) {
    serialization::Celestial const& celestial = message.celestial();
    bodies.emplace_back(MassiveBody::ReadFromMessage(celestial.body()));
    histories.emplace_back(DiscreteTrajectory<Frame>::ReadFromMessage(
        celestial.history_and_prolongation().history(), /*forks=*/{}));
    auto const prolongation =
        DiscreteTrajectory<Frame>::ReadPointerFromMessage(
            celestial.history_and_prolongation().prolongation(),
            histories.back().get());
    typename DiscreteTrajectory<Frame>::Iterator const history_begin =
        histories.back()->Begin();
    initial_state.push_back(history_begin.degrees_of_freedom());
    initial_time.insert(history_begin.time());
    final_time.insert(prolongation->last().time());
  }
  CHECK_EQ(1, initial_time.size());
  CHECK_EQ(1, final_time.size());
  LOG(INFO) << "Initial time is " << *initial_time.cbegin()
            << ", final time is " << *final_time.cbegin();

  // Construct a new ephemeris using the bodies and initial states and time
  // extracted from the serialized celestials.
  auto ephemeris = std::make_unique<Ephemeris<Frame>>(std::move(bodies),
                                                      initial_state,
                                                      *initial_time.cbegin(),
                                                      fitting_tolerance,
                                                      fixed_parameters);

  // Extend the continuous trajectories using the data from the discrete
  // trajectories.
  std::set<Instant> last_state_time;
  for (int i = 0; i < histories.size(); ++i) {
    not_null<MassiveBody const*> const body = ephemeris->unowned_bodies_[i];
    auto const& history = histories[i];
    int const j = ephemeris->serialization_index_for_body(body);
    auto continuous_trajectory = ephemeris->trajectories_[j];

    typename DiscreteTrajectory<Frame>::Iterator it = history->Begin();
    Instant last_time = it.time();
    DegreesOfFreedom<Frame> last_degrees_of_freedom = it.degrees_of_freedom();
    for (; it != history->End(); ++it) {
      Time const duration_since_last_time = it.time() - last_time;
      if (duration_since_last_time == fixed_parameters.step_) {
        // A time in the discrete trajectory that is aligned on the continuous
        // trajectory.
        last_time = it.time();
        last_degrees_of_freedom = it.degrees_of_freedom();
        continuous_trajectory->Append(last_time, last_degrees_of_freedom);
      } else if (duration_since_last_time > fixed_parameters.step_) {
        // A time in the discrete trajectory that is not aligned on the
        // continuous trajectory.  Stop here, we'll use prolong to recompute the
        // rest.
        break;
      }
    }

    // Fill the |last_state_| for this body.  It will be the starting state for
    // Prolong.
    last_state_time.insert(last_time);
    ephemeris->last_state_.positions[j] = last_degrees_of_freedom.position();
    ephemeris->last_state_.velocities[j] = last_degrees_of_freedom.velocity();
  }
  CHECK_EQ(1, last_state_time.size());
  ephemeris->last_state_.time = *last_state_time.cbegin();
  LOG(INFO) << "Last time in discrete trajectories is "
            << *last_state_time.cbegin();

  // Prolong the ephemeris to the final time.  This might create discrepancies
  // from the discrete trajectories.
  ephemeris->Prolong(*final_time.cbegin());

  return ephemeris;
}
Exemple #15
0
void PeerListModel::updatePeers(const google::protobuf::RepeatedPtrField<Protos::GUI::State::Peer>& peers, const QSet<Common::Hash>& peersDownloadingOurData)
{
   Common::SortedArray<Peer*> peersToRemove = this->orderedPeers;
   QList<Peer*> peersToAdd;

   for (int i = 0; i < peers.size(); i++)
   {
      const Common::Hash peerID(peers.Get(i).peer_id().hash());
      const QString& nick = Common::ProtoHelper::getStr(peers.Get(i), &Protos::GUI::State::Peer::nick);
      const QString& coreVersion = Common::ProtoHelper::getStr(peers.Get(i), &Protos::GUI::State::Peer::core_version);
      const quint64 sharingAmount(peers.Get(i).sharing_amount());
      const TransferInformation transferInformation { peers.Get(i).download_rate(), peers.Get(i).upload_rate(),  peersDownloadingOurData.contains(peerID) };
      const QHostAddress ip =
         peers.Get(i).has_ip() ?
            Common::ProtoHelper::getIP(peers.Get(i).ip()) :
            QHostAddress();

      Peer* peer = this->indexedPeers[peerID];
      int j = this->orderedPeers.indexOf(peer);
      if (j != -1)
      {
         peersToRemove.remove(peer);
         if (peer->nick != nick)
         {
            if (this->currentSortType == Protos::GUI::Settings::BY_NICK)
            {
               this->beginRemoveRows(QModelIndex(), j, j);
               this->orderedPeers.remove(peer);
               this->endRemoveRows();
               peer->nick = nick;
               peersToAdd << peer;
            }
            else
            {
               peer->nick = nick;
               emit dataChanged(this->createIndex(j, 1), this->createIndex(j, 1));
            }
         }
         if (peer->sharingAmount != sharingAmount)
         {
            if (this->currentSortType == Protos::GUI::Settings::BY_SHARING_AMOUNT)
            {
               this->beginRemoveRows(QModelIndex(), j, j);
               this->orderedPeers.remove(peer);
               this->endRemoveRows();
               peer->sharingAmount = sharingAmount;
               peersToAdd << peer;
            }
            else
            {
               peer->sharingAmount = sharingAmount;
               emit dataChanged(this->createIndex(j, 1), this->createIndex(j, 1));
            }
         }
         if (peer->transferInformation != transferInformation)
         {
            peer->transferInformation = transferInformation;
            emit dataChanged(this->createIndex(j, 0), this->createIndex(j, 0));
         }

         peer->ip = ip;
         peer->coreVersion = coreVersion;
      }
      else
      {
         peersToAdd << new Peer(peerID, nick, coreVersion, sharingAmount, ip, transferInformation);
      }
   }

   QList<Common::Hash> peerIDsRemoved;
   for (Common::SortedArray<Peer*>::Iterator i(peersToRemove); i.hasNext();)
   {
      Peer* const peer = i.next();
      peerIDsRemoved << peer->peerID;
      int j = this->orderedPeers.indexOf(peer);
      if (j != -1)
      {
         this->beginRemoveRows(QModelIndex(), j, j);
         this->indexedPeers.remove(peer->peerID);
         this->orderedPeers.remove(peer);
         delete peer;
         this->endRemoveRows();
      }
   }

   if (!peerIDsRemoved.isEmpty())
      emit peersRemoved(peerIDsRemoved);

   for (QListIterator<Peer*> i(peersToAdd); i.hasNext();)
   {
      Peer* const peer = i.next();
      int pos = this->orderedPeers.insert(peer);
      this->beginInsertRows(QModelIndex(), pos, pos);
      this->indexedPeers.insert(peer->peerID, peer);
      this->endInsertRows();
   }
}