예제 #1
0
void
InventoryImpl::draw()
{
  Vector2f pos = Vector2f(400, 300);

  int num_items = items.size();
  float step_angle = (2.0f * math::pi) / static_cast<float>(num_items);

  for(int i = 0; i < int(items.size()); ++i)
  {
    const InventoryItem& item = items[(i+current_item) % items.size()];
    Vector2f draw_pos = pos + Vector2f(128.0f, 0.0f).rotate(step_angle * static_cast<float>(i) - math::pi/2.0f + add_angle);

    if (i == 0 && moving == 0)
    {
      slothighlight.draw(draw_pos);
      Fonts::current()->vera20->draw_center(Vector2f(draw_pos.x, draw_pos.y - 64), item.name);
    }
    else
    {
      slot.draw(draw_pos);
    }

    item.sprite.draw(draw_pos - Vector2f(32,32));
  }
}
예제 #2
0
void
InventoryImpl::draw()
{
  Vector pos = Vector(400, 300); // View::current()->screen_Player::currently->get_pos();

  int num_items = items.size();
  float step_angle = (2*M_PI) / num_items;

  for(int i = 0; i < int(items.size()); ++i)
    {
      const InventoryItem& item = items[(i+current_item)%items.size()];
      Vector draw_pos = pos + Vector(128, 0).rotate(step_angle * i - M_PI/2 + add_angle);

      if (i == 0 && moving == 0)
        {
          slothighlight.draw(draw_pos);
          Fonts::vera20->draw_center(draw_pos.x, draw_pos.y - 64, item.name);
        }
      else
        {
          slot.draw(draw_pos);
        }

      item.sprite.draw(draw_pos - Vector(32,32));
    }
}
예제 #3
0
void RowCollection<Group,Hash>::flushOneRowInBuffer(size_t rowId, Items const& items) {
    assert(rowId<_counts.size());

    vector<boost::shared_ptr<ChunkIterator> > chunkIterators(_attributes.size());

    try {
        if (! isLastChunkFull(rowId)) { // only get chunk iterators if there exists a non-full last chunk.
            getChunkIterators(chunkIterators, rowId);
        }

        for (size_t v=0; v<items.size(); ++v) {
            vector<Value> const& item = items[v];

            if (isLastChunkFull(rowId)) { // when the last chunk was full, get the iterators here (right before append)
                getChunkIterators(chunkIterators, rowId);
            }

            for (size_t i=0; i<_attributes.size(); ++i) {
                chunkIterators[i]->writeItem(item[i]);
            }
            ++ _counts[rowId];

            if (isLastChunkFull(rowId)) { // after append, flush and clear the chunk iterators if the last chunk becomes full
                for (size_t i=0; i<_attributes.size(); ++i) {
                    chunkIterators[i]->flush();
                    chunkIterators[i].reset();
                }
            } else {
                for (size_t i=0; i<_attributes.size(); ++i) {
                    ++ (*chunkIterators[i]);
                }
            }
        }

        if (items.size()>0 && !isLastChunkFull(rowId)) {
            assert(chunkIterators[0]);
            for (size_t i=0; i<_attributes.size(); ++i) {
                chunkIterators[i]->flush();
                chunkIterators[i].reset();
            }
        } else {
            assert(! chunkIterators[0]);
        }
    } catch (std::exception& e) {
        LOG4CXX_DEBUG(logger, "[RowCollection] std::exception in RowIterator::appendItems(): " << e.what());
        throw;
    } catch (...) {
        LOG4CXX_DEBUG(logger, "[RowCollection] (...) exception in RowIterator::appendItem()" );
        throw;
    }
}
예제 #4
0
void Search::UpdateItemCounts(const Items &items) {
    unfiltered_item_count_ = items.size();

    filtered_item_count_total_ = 0;
    for (auto &item : items_)
        filtered_item_count_total_ += item->count();
}
예제 #5
0
void
InventoryImpl::update(float delta, const Controller& controller)
{
  float step_angle = (2.0f * math::pi) / static_cast<float>(items.size());
  if (fabsf(add_angle) > step_angle)
  {
    if (moving == 1)
      decr_current_item();
    else if (moving == -1)
      incr_current_item();

    moving = 0;
    add_angle = 0;
  }

  if (controller.get_axis_state(X_AXIS) < -0.5f)
  {
    if (moving == 1)
    {
      add_angle = -step_angle + add_angle;
      decr_current_item();
    }

    moving = -1;
  }
  else if (controller.get_axis_state(X_AXIS) > 0.5f)
  {
    if (moving == -1)
    {
      add_angle = step_angle + add_angle;
      incr_current_item();
    }

    moving =  1;
  }

  if (moving == -1)
  {
    add_angle -= 3 * delta;
  }
  else if (moving == 1)
  {
    add_angle += 3 * delta;
  }

  if (moving == 0)
  {
    if (controller.button_was_pressed(OK_BUTTON) ||
        controller.button_was_pressed(CANCEL_BUTTON) ||
        controller.button_was_pressed(INVENTORY_BUTTON))
    {
      GameSession::current()->set_control_state(GameSession::GAME);
    }
  }
}
예제 #6
0
파일: client.cpp 프로젝트: mamatias/uaf
    void Client::processPersistentRequests(_Store& store)
    {
        // create a typedef for the vector holding the correct type of items
        typedef std::vector<typename _Store::Item> Items;

        // get the items that need to be reconstructed
        Items items = store.getBadItems();

        if (items.size() > 0)
            logger_->debug("A total of %d persistent requests need to be re-processed",
                           items.size());

        // loop through the items and process them
        // (We don't have to care about the Status result of the processRequest function,
        // since processPersistentRequests() is called automatically by a thread, and this
        // thread doesn't perform any actions in case of failures.)
        for (typename Items::iterator it = items.begin(); it != items.end(); ++it)
            processRequest<typename _Store::ServiceType>(
                    it->request,
                    it->badTargetsMask,
                    it->result);
    }
예제 #7
0
        //  Algorithm to calculate the edit operations to allow
        //_ replaceing items without model reset
        inline void replace(const Items &newItems, int from = 0)
        {
            using namespace kamd::utils::member_matcher;

#if 0
            QDBG << "===\nOld items {";
            for (const auto& item: m_items) {
                QDBG << item;
            }
            QDBG << "}";

            QDBG << "New items to be added at " << from << " {";
            for (const auto& item: newItems) {
                QDBG << item;
            }
            QDBG << "}";
#endif


            // Based on 'The string to string correction problem
            // with block moves' paper by Walter F. Tichy
            //
            // In essence, it goes like this:
            //
            // Take the first element from the new list, and try to find
            // it in the old one. If you can not find it, it is a new item
            // item - send the 'inserted' event.
            // If you did find it, test whether the following items also
            // match. This detects blocks of items that have moved.
            //
            // In this example, we find 'b', and then detect the rest of the
            // moved block 'b' 'c' 'd'
            //
            // Old items:  a[b c d]e f g
            //               ^
            //              /
            // New items: [b c d]a f g
            //
            // After processing one block, just repeat until the end of the
            // new list is reached.
            //
            // Then remove all remaining elements from the old list.
            //
            // The main addition here compared to the original papers is that
            // our 'strings' can not hold two instances of the same element,
            // and that we support updating from arbitrary position.

            auto newBlockStart = newItems.cbegin();

            // How many items should we add?
            // This should remove the need for post-replace-trimming
            // in the case where somebody called this with too much new items.
            const int maxToReplace = m_countLimit - from;

            if (maxToReplace <= 0) return;

            const auto newItemsEnd =
                newItems.size() <= maxToReplace ? newItems.cend() :
                                                  newItems.cbegin() + maxToReplace;


            // Finding the blocks until we reach the end of the newItems list
            //
            // from = 4
            // Old items: X Y Z U a b c d e f g
            //                      ^ oldBlockStart points to the first element
            //                        of the currently processed block in the old list
            //
            // New items: _ _ _ _ b c d a f g
            //                    ^ newBlockStartIndex is the index of the first
            //                      element of the block that is currently being
            //                      processed (with 'from' offset)

            while (newBlockStart != newItemsEnd) {

                const int newBlockStartIndex
                    = from + std::distance(newItems.cbegin(), newBlockStart);

                const auto oldBlockStart = std::find_if(
                    m_items.begin() + from, m_items.end(),
                    member(&ResultSet::Result::resource) == newBlockStart->resource());

                if (oldBlockStart == m_items.end()) {
                    // This item was not found in the old cache, so we are
                    // inserting a new item at the same position it had in
                    // the newItems array
                    d->q->beginInsertRows(QModelIndex(), newBlockStartIndex,
                                          newBlockStartIndex);

                    m_items.insert(newBlockStartIndex, *newBlockStart);
                    d->q->endInsertRows();

                    // This block contained only one item, move on to find
                    // the next block - it starts from the next item
                    ++newBlockStart;

                } else {
                    // We are searching for a block of matching items.
                    // This is a reimplementation of std::mismatch that
                    // accepts two complete ranges that is available only
                    // since C++14, so we can not use it.
                    auto newBlockEnd = newBlockStart;
                    auto oldBlockEnd = oldBlockStart;

                    while (newBlockEnd != newItemsEnd &&
                           oldBlockEnd != m_items.end() &&
                           newBlockEnd->resource() == oldBlockEnd->resource()) {
                        ++newBlockEnd;
                        ++oldBlockEnd;
                    }

                    // We have found matching blocks
                    // [newBlockStart, newBlockEnd) and [oldBlockStart, newBlockEnd)
                    const int oldBlockStartIndex
                        = std::distance(m_items.begin() + from, oldBlockStart);

                    const int blockSize
                        = std::distance(oldBlockStart, oldBlockEnd);

                    if (oldBlockStartIndex != newBlockStartIndex) {
                        // If these blocks do not have the same start,
                        // we need to send the move event.

                        // Note: If there is a crash here, it means we
                        // are getting a bad query which has duplicate
                        // results

                        d->q->beginMoveRows(QModelIndex(), oldBlockStartIndex,
                                            oldBlockStartIndex + blockSize - 1,
                                            QModelIndex(), newBlockStartIndex);

                        // Moving the items from the old location to the new one
                        kamd::utils::slide(
                                oldBlockStart, oldBlockEnd,
                                m_items.begin() + newBlockStartIndex);

                        d->q->endMoveRows();
                    }

                    // Skip all the items in this block, and continue with
                    // the search
                    newBlockStart = newBlockEnd;
                }
            }

            // We have avoided the need for trimming for the most part,
            // but if the newItems list was shorter than needed, we still
            // need to trim the rest.
            trim(from + newItems.size());

            // Check whether we got an item representing a non-existent file,
            // if so, schedule its removal from the database
            for (const auto &item: newItems) {
                if (item.resource().startsWith('/') && !QFile(item.resource()).exists()) {
                    d->q->forgetResource(item.resource());
                }
            }
        }
예제 #8
0
파일: Module_DMAP.cpp 프로젝트: vezzi/ERNE
/* static */
void Module_DMAP::generic_worker_single_thr(Module_DMAP * search, int id) {
	Mask * sequences;
	int read_seq;
	vector<Mask> printable_solutions;
	Transmitting_Result received;

	if (search->my_rank == 0) {
		sequences = new Mask[SEQUENCES_FOR_BLOCK];
		read_seq = read_sequences(search->input_file1, SEQUENCES_FOR_BLOCK, sequences, search->fastqformat, search->gui_output);
	} else {
		received = search->receive_from_previous(id);
		sequences = received.first;
		read_seq = received.second;
	}

	while (read_seq != 0) {
		Items solutions;
		//ItemsGapped solutions_gapped;
		t_errors calculated_errors;

		for (int i = 0; i < read_seq; i++) {
			Mask & s = sequences[i];
			if (search->my_rank == 0 and search->trim) {
					//	check_routine(sequences[i], 0);
					s.quality_trimming_MOTT(search->min_phred_value_MOTT,search->min_mean_quality,search->min_size);
			}
			if (s.status_discarded()) {
				if (s.status_low_complexity())
					s.low_complexity  =true; //s.set_type(low_complexity);
				else
					s.low_quality = true; //s.set_type(quality_discarded);
				printable_solutions.push_back(s);
				continue;
			}
			if (search->auto_errors)
				calculated_errors = round((double)s.get_good_length() / search->errors_rate);
			else
				calculated_errors = search->common_errors_allowed;
			if (search->my_rank != 0 and s.algn > 0 and s.NM < calculated_errors)
				calculated_errors = s.NM;
			t_errors count = 0;
			for (t_pattern_length i = s.get_good_region_start()-1; (i < s.get_good_region_stop()) and (count <= calculated_errors); i++)
				if (s.sequence[i] == 'N' or s.sequence[i] == 'n')
					count++;
			if (count > calculated_errors) {
				//s.set_type(alignments_not_found);
				printable_solutions.push_back(s);
				continue;
			}

			/** ALIGNMENT **/
			solutions.clear();

			if (search->my_rank == 0 and search->contamination_check) {
				search->CR.search(s.get_good_sequence(),solutions,calculated_errors);
				if (solutions.size() > 0)
					s.contaminated = true;
			}

			if (not s.contaminated)
				search->H.search(s.get_good_sequence(),solutions,calculated_errors);
			if (solutions.size() == 0) {
				/** Try gapped **/
				/*
				solutions_gapped.clear();
				if (search->gap)
					search->H.search_gapped(s.get_good_sequence(),solutions_gapped,search->seed_sizes,search->seed_errors,calculated_errors,search->max_gap);
				*/
				/*
				if (solutions_gapped.size() == 0) {// size 0 means no alignment found
				*/
					//s.set_type(alignments_not_found);
					printable_solutions.push_back(s);
					continue;
				/*
				} else {
					if (not search->printAll) {
						Random_Choice_Result r;
						bool improved = (s.NM + s.NM_gap) > (solutions_gapped.at(0).errors1 + solutions_gapped.at(0).errors2);

						if (improved)
							r = Search_MPI::random_choice_from_previous(0,solutions_gapped.size());
						else
							r = Search_MPI::random_choice_from_previous(s.algn,solutions_gapped.size());
						if (not improved and r.first) {
							// take the previous solution
							s.algn += solutions_gapped.size();
						} else {
							// update solution
							const ResultItemGapped & HM = solutions_gapped.at(r.second);
							s.globalPosition = HM.GlobalPosition1;
							if (improved)
								s.algn = solutions_gapped.size();
							else
								s.algn += solutions_gapped.size();
							s.HI = 1;
							s.IH = 1;
							s.primary = true;
							s.strand = HM.strand;
							s.NM = HM.errors1;
							s.NM_gap = HM.errors2;
							s.contig = HM.contig;
							s.position = HM.GlobalPosition1 - search->H.globaltolocal.startPositions[HM.contig] + 1 ;
							s.position_gap = HM.GlobalPosition2 - search->H.globaltolocal.startPositions[HM.contig] + 1 ;
							s.length1_gap = HM.length1;
							s.length2_gap = HM.length2;
							s.contig = search->contig_conversion.convert(s.contig);

						}
						printable_solutions.push_back(s);


					} else { // printALL
				*/
						/*
						unsigned int processed=0;
						unsigned int alignments;
						(search->toBePrinted < solutions_gapped.size()) ? alignments = search->toBePrinted : alignments = solutions_gapped.size() ;
						while(processed < alignments) {
							const ResultItemGapped & HM = solutions_gapped.at(processed);
							s.globalPosition = HM.GlobalPosition1;
							s.algn = alignments;
							s.HI =1;
							s.IH =1;
							(processed == 0 ) ? s.primary = true : s.primary = false;
							s.strand = HM.strand;
							s.NM = HM.errors1;
							s.NM_gap = HM.errors2;
							s.contig = HM.contig ;
							s.position = HM.GlobalPosition1 - search->H.globaltolocal.startPositions[HM.contig] + 1 ;
							s.position_gap = HM.GlobalPosition2 - search->H.globaltolocal.startPositions[HM.contig] + 1 ;
							s.length1_gap = HM.length1;
							s.length2_gap = HM.length2;
							s.contaminated = contaminated;
							printable_solutions.push_back(s);
							processed++;
						}
						 */
/*
						ERROR_CHANNEL << "--print-all option not implemented yet!" << endl;
						exit(3);
					}
				}
				*/
			} else if (not search->printAll) {
				sort(solutions.begin(), solutions.end(), ResultItem::less()); // sort solutions
				solutions.erase(unique(solutions.begin(), solutions.end(), ResultItem::equal()), solutions.end());

				Random_Choice_Result r;
				bool improved = (s.NM + s.NM_gap) > (solutions.at(0).errors);

				if (improved)
					r = Module_DMAP::random_choice_from_previous(0,solutions.size());
				else {
					r = Module_DMAP::random_choice_from_previous(s.algn,solutions.size());
					s.algn += solutions.size();
				}
				if (not r.first) {
					const ResultItem & HM = solutions.at(r.second);
					s.HI = 1;
					s.IH = 1;
					s.primary = true;
					s.globalPosition = HM.globalPosition;
					s.strand = HM.strand;
					s.NM = HM.errors;
					s.NM_gap = 0;
					if ((search->my_rank == 0) and s.contaminated) {
						s.contig = search->CR.globalToLocal.searchContig(HM.globalPosition); // find the contig/scaffold
						s.position = HM.globalPosition - search->CR.globalToLocal.startPositions[s.contig] + 1;
						s.contig = search->contig_conversion.convert(s.contig);
					} else {
						s.contig = search->H.globalToLocal.searchContig(HM.globalPosition); // find the contig/scaffold
						s.position = HM.globalPosition - search->H.globalToLocal.startPositions[s.contig] + 1;
						s.contig = search->contig_conversion.convert(s.contig);
					}
				}
				printable_solutions.push_back(s);
				continue;
			} else { // printAll
				/*
				// memorize all printable solutions
				sort(solutions.begin(), solutions.end(), ResultItem::less()); // sort solutions
				solutions.erase(unique(solutions.begin(), solutions.end(), ResultItem::equal()), solutions.end());
				unsigned int processed=0;
				unsigned int alignments;
				(search->toBePrinted < solutions.size()) ? alignments = search->toBePrinted : alignments = solutions.size() ;
				while(processed < alignments) {
					// while I print enough solution or there are no more solutions
					const ResultItem & HM = solutions.at(processed);
					s.globalPosition = HM.GlobalPosition;
					s.algn = solutions.size();
					s.IH = alignments;
					s.HI = processed+1;
					(processed == 0 ) ? s.primary = true : s.primary = false;
					s.strand = HM.strand;
					s.NM = HM.errors;
					if (contaminated) {
						s.contig = search->CR.globaltolocal.searchContig(HM.GlobalPosition); // find the contig/scaffold
						s.position = HM.GlobalPosition - search->CR.globaltolocal.startPositions[s.contig] + 1;
					} else {
						s.contig = search->H.globaltolocal.searchContig(HM.GlobalPosition); // find the contig/scaffold
						s.position = HM.GlobalPosition - search->H.globaltolocal.startPositions[s.contig] + 1;
					}
					s.contaminated = contaminated;
					printable_solutions.push_back(s);
				}
				 */

				ERROR_CHANNEL << "--print-all option not implemented yet!" << endl;
				exit(3);
			}
		}

		if (search->my_rank == (search->nprocs-1)) {
			// now print all
			for(unsigned int i=0; i < printable_solutions.size(); i++)
				search->output_samfile.print_output(printable_solutions.at(i));
			search->processed += read_seq;
		} else // send data to next node
			search->send_to_next(printable_solutions,id);

		delete [] sequences;
		printable_solutions.clear();

		if (search->my_rank == 0) {
			sequences = new Mask[SEQUENCES_FOR_BLOCK];
			read_seq = read_sequences(search->input_file1, SEQUENCES_FOR_BLOCK, sequences, search->fastqformat, search->gui_output);
			if (read_seq == 0)
				delete [] sequences;
		} else {
			received = search->receive_from_previous(id);
			sequences = received.first;
			read_seq = received.second;
		}
	}

}
예제 #9
0
 void decr_current_item() { 
   if (current_item == 0)
     current_item = items.size() - 1;
   else
     current_item -= 1;
 }
예제 #10
0
 void incr_current_item() { 
   if (current_item == int(items.size()) - 1)
     current_item = 0;
   else
     current_item += 1;
 }
예제 #11
0
int OTWS_Wordseg_x(otws_t handle, 
        const string& sent,
        vector<string>& words) {

    OTWS_Engine *engine = reinterpret_cast<OTWS_Engine *>(handle);
    words.clear();

    RawSentence *tag_sent = new TagSent();
    vector<string> chars;
    int numChars = UTF::getCharactersFromUTF8String(sent, &chars);

    // something for debug.
    cerr << "TOKEN: ";
    for (int i = 0; i < numChars; ++ i) {
        cerr << chars[i] << " | ";
        tag_sent->append(new TagItem(chars[i], "X"));
    }
    cerr << endl;

    Instance *inst = (engine)->extractor->extract(tag_sent, false);
    Items *items = inst->items();

    Labels* labels = engine->decoder->decode(inst,
            engine->model->getParameter("PARAMETER"))->best();

    Alphabet *labelsDict = engine->model->getAlphabet("LABELS");

    // something for debug.
    for (int i = 0; i < labels->size(); ++ i) {
        cerr << labelsDict->rlookup(labels->at(i)) << 
            "(" << labels->at(i) << ") ";
    }
    cerr << "| label size: " << labels->size() << endl;

    string tag;
    string word;

    for (int i = 0; i < items->size(); ) {
        tag = labelsDict->rlookup(labels->at(i));

        if ("S" == tag) {
            word = chars[i];
            words.push_back(word);
            ++ i;
        } else if ("B" == tag) {
            word = "";
            while ("E" != tag && i < items->size()){
                word = word + chars[i];
                tag = labelsDict->rlookup(labels->at(i));
                ++ i;
            }
            words.push_back(word);
        } else {
            cerr << "Exception asserted." << endl;
            words.clear();
            return -1;
        }
    }

    return words.size();
}
예제 #12
0
 size_t items_size() {
   return items_.size();
 }
QList<ShopTemplateManager::ShopTemplateSection> ShopTemplateManager::FetchFromItemsKey(const QString &key, const Items &items, QHash<QString, QString> *options) {
    QList<ShopTemplateManager::ShopTemplateSection> result;
    if (items.size() > 0){
        Items matchingItems;

        bool includeNoBuyouts = options->contains("include.ignored");
        ShopTemplateContainType containType = CONTAIN_TYPE_NONE;

        if (key == "everything") {
            matchingItems = items;
        }
        else if (key.startsWith("stash:")) {
            int index = key.indexOf(":");
            QString name = (index + 1 >= key.length()) ? "" : key.mid(index + 1);
            if (!name.isEmpty()) {
                for (const std::shared_ptr<Item> &item : items) {
                    if (QString::fromStdString(item->location().GetLabel()).compare(name, Qt::CaseInsensitive) == 0) {
                        matchingItems.push_back(item);
                    }
                }
            }
        }
        else {
            Items pool = items;
            QStringList keyParts = key.split("+", QString::SkipEmptyParts);
            for (QString part : keyParts) {
                if (templateMatchers.contains(part)) {
                    matchingItems = FindMatchingItems(pool, part);
                }
                else {
                    // todo(novynn): phase these out? Prefer {Normal+Helmet} over {NormalHelmet}
                    bool matchedRarity = false;
                    const QStringList rarities = {"normal", "magic", "rare", "unique"};
                    for (QString rarity : rarities) {
                        if (part.startsWith(rarity)) {
                            QString type = part.mid(rarity.length());

                            matchingItems = FindMatchingItems(pool, rarity);
                            matchingItems = FindMatchingItems(matchingItems, type);
                            matchedRarity = true;
                        }
                    }

                    if (matchedRarity) continue;

                    if (part.endsWith("gems")) {
                        if (part == "gems" || part == "allgems") {
                            matchingItems = FindMatchingItems(pool, "gems");
                        }
                        else {
                            const QStringList gemTypes = {"AoE", "Attack", "Aura", "Bow", "Cast", "Chaining", "Chaos",
                                                          "Cold", "Curse", "Duration", "Fire", "Lightning", "Melee", "Mine", "Minion",
                                                          "Movement", "Projectile", "Spell", "Totem", "Trap", "Support"};
                            for (QString gemType : gemTypes) {
                                if (!part.startsWith(gemType, Qt::CaseInsensitive)) continue;

                                // This will never just be first key (?)
                                QString firstKey = gemType.toLower() + "gems";
                                matchingItems = FindMatchingItems(pool, firstKey);

                                if (part != firstKey) {
                                    // supportlightninggems
                                    QString secondKey = part.mid(gemType.length());
                                    matchingItems = FindMatchingItems(matchingItems, secondKey);
                                }
                            }
                        }
                    }
                }
                pool = matchingItems;
            }
        }

        // Only select items from your stash unless specified
        if (!options->contains("include.character")) {
            matchingItems = Items::fromStdVector(
                        from(matchingItems.toStdVector())
                        .where([](const std::shared_ptr<Item> item) { return item->location().type() == ItemLocationType::STASH; })
                        .toVector()
                     );
        }

        if (matchingItems.size() == 0)
            return result;

        if (containType == CONTAIN_TYPE_NONE && options->contains("wrap")) containType = CONTAIN_TYPE_WRAP;
        if (containType == CONTAIN_TYPE_NONE && options->contains("group")) containType = CONTAIN_TYPE_GROUP;

        switch (containType) {
            case (CONTAIN_TYPE_WRAP): {
                QString header = "Items";
                Buyout buyout = {};

                if (options->contains("header")) {
                    header = options->value("header");
                }

                const std::shared_ptr<Item> first = matchingItems.first();
                if (parent_->buyout_manager().Exists(*first)) buyout = parent_->buyout_manager().Get(*first);

                bool sameBuyout = from(matchingItems.toStdVector()).all([this, buyout](const std::shared_ptr<Item> item) {
                    Buyout thisBuyout = {};
                    if (parent_->buyout_manager().Exists(*item)) thisBuyout = parent_->buyout_manager().Get(*item);
                    return BuyoutManager::Equal(thisBuyout, buyout);
                });

                if (sameBuyout) {
                    header += BuyoutManager::Generate(buyout);
                }

                QStringList temp = WriteItems(matchingItems, !sameBuyout, includeNoBuyouts);
                if (!temp.isEmpty()) {
                    result << ShopTemplateSection(temp, SECTION_TYPE_SPOILER, header);
                }
                break;
            }
            case CONTAIN_TYPE_GROUP: {
                QMultiMap<QString, std::shared_ptr<Item>> itemsMap;

                for (auto &item : matchingItems) {
                    Buyout b = {};
                    if (parent_->buyout_manager().Exists(*item))
                        b = parent_->buyout_manager().Get(*item);
                    itemsMap.insert(BuyoutManager::Generate(b), item);
                }

                for (QString buyout : itemsMap.uniqueKeys()) {
                    Items itemList = itemsMap.values(buyout).toVector();
                    if (itemList.size() == 0)
                        continue;
                    QString header = buyout;
                    if (header.isEmpty()) header = "Offers Accepted";
                    QStringList temp = WriteItems(itemList, false, includeNoBuyouts);
                    if (temp.isEmpty())
                        continue;

                    result << ShopTemplateSection(temp, SECTION_TYPE_SPOILER, header);
                }
                break;
            }
            default: {
                QStringList temp = WriteItems(matchingItems, true, includeNoBuyouts);
                result << ShopTemplateSection(temp, SECTION_TYPE_NONE);
                break;
            }
        }
    }

    return result;
}
예제 #14
0
size_t FillTreeClass<T>::setTreeInternal(T& _safelocker, Items& _items, const ::profiler::timestamp_t& _beginTime, const ::profiler::BlocksTree::children_t& _children, EasyTreeWidgetItem* _parent, EasyTreeWidgetItem* _frame, EasyTreeWidgetItem* _thread, ::profiler::timestamp_t _left, ::profiler::timestamp_t _right, bool _strict, ::profiler::timestamp_t& _duration, bool _colorizeRows)
{
    size_t total_items = 0;
    for (auto child_index : _children)
    {
        if (_safelocker.interrupted())
            break;

        auto& gui_block = easyBlock(child_index);
        const auto& child = gui_block.tree;
        const auto startTime = child.node->begin();
        const auto endTime = child.node->end();
        const auto duration = endTime - startTime;
        _duration += duration;

        if (startTime > _right || endTime < _left)
        {
            continue;
        }

        auto item = new EasyTreeWidgetItem(child_index, _parent);

        auto name = *child.node->name() != 0 ? child.node->name() : easyDescriptor(child.node->id()).name();
        item->setText(COL_NAME, ::profiler_gui::toUnicode(name));
        item->setTimeSmart(COL_DURATION, duration);
        item->setTimeMs(COL_BEGIN, startTime - _beginTime);
        item->setTimeMs(COL_END, endTime - _beginTime);
        item->setData(COL_PERCENT_SUM_PER_THREAD, Qt::UserRole, 0);

        if (child.per_thread_stats != nullptr) // if there is per_thread_stats then there are other stats also
        {
            const auto& per_thread_stats = child.per_thread_stats;
            const auto& per_parent_stats = child.per_parent_stats;
            const auto& per_frame_stats = child.per_frame_stats;

            auto percentage = duration == 0 ? 0 : ::profiler_gui::percent(duration, _parent->duration());
            auto percentage_sum = ::profiler_gui::percent(per_parent_stats->total_duration, _parent->duration());
            item->setData(COL_PERCENT_PER_PARENT, Qt::UserRole, percentage);
            item->setText(COL_PERCENT_PER_PARENT, QString::number(percentage));
            item->setData(COL_PERCENT_SUM_PER_PARENT, Qt::UserRole, percentage_sum);
            item->setText(COL_PERCENT_SUM_PER_PARENT, QString::number(percentage_sum));

            if (_frame != nullptr)
            {
                if (_parent != _frame)
                {
                    percentage = duration == 0 ? 0 : ::profiler_gui::percent(duration, _frame->duration());
                    percentage_sum = ::profiler_gui::percent(per_frame_stats->total_duration, _frame->duration());
                }

                item->setData(COL_PERCENT_PER_FRAME, Qt::UserRole, percentage);
                item->setText(COL_PERCENT_PER_FRAME, QString::number(percentage));
                item->setData(COL_PERCENT_SUM_PER_FRAME, Qt::UserRole, percentage_sum);
                item->setText(COL_PERCENT_SUM_PER_FRAME, QString::number(percentage_sum));
            }
            else
            {
                item->setData(COL_PERCENT_PER_FRAME, Qt::UserRole, 0);
                item->setData(COL_PERCENT_SUM_PER_FRAME, Qt::UserRole, 0);

                if (_thread)
                {
                    auto percentage_per_thread = ::profiler_gui::percent(duration, _thread->selfDuration());
                    item->setData(COL_PERCENT_PER_PARENT, Qt::UserRole, percentage_per_thread);
                    item->setText(COL_PERCENT_PER_PARENT, QString::number(percentage_per_thread));
                }
                else
                {
                    item->setData(COL_PERCENT_PER_PARENT, Qt::UserRole, 0);
                }
            }


            if (per_thread_stats->calls_number > 1 || !EASY_GLOBALS.display_only_relevant_stats)
            {
                item->setTimeSmart(COL_MIN_PER_THREAD, per_thread_stats->min_duration, "min ");
                item->setTimeSmart(COL_MAX_PER_THREAD, per_thread_stats->max_duration, "max ");
                item->setTimeSmart(COL_AVERAGE_PER_THREAD, per_thread_stats->average_duration());
                item->setTimeSmart(COL_DURATION_SUM_PER_THREAD, per_thread_stats->total_duration);
            }

            item->setData(COL_NCALLS_PER_THREAD, Qt::UserRole, per_thread_stats->calls_number);
            item->setText(COL_NCALLS_PER_THREAD, QString::number(per_thread_stats->calls_number));

            if (_thread)
            {
                auto percentage_per_thread = ::profiler_gui::percent(per_thread_stats->total_duration, _thread->selfDuration());
                item->setData(COL_PERCENT_SUM_PER_THREAD, Qt::UserRole, percentage_per_thread);
                item->setText(COL_PERCENT_SUM_PER_THREAD, QString::number(percentage_per_thread));
            }


            if (per_parent_stats->calls_number > 1 || !EASY_GLOBALS.display_only_relevant_stats)
            {
                item->setTimeSmart(COL_MIN_PER_PARENT, per_parent_stats->min_duration, "min ");
                item->setTimeSmart(COL_MAX_PER_PARENT, per_parent_stats->max_duration, "max ");
                item->setTimeSmart(COL_AVERAGE_PER_PARENT, per_parent_stats->average_duration());
                item->setTimeSmart(COL_DURATION_SUM_PER_PARENT, per_parent_stats->total_duration);
            }

            item->setData(COL_NCALLS_PER_PARENT, Qt::UserRole, per_parent_stats->calls_number);
            item->setText(COL_NCALLS_PER_PARENT, QString::number(per_parent_stats->calls_number));


            if (per_frame_stats->calls_number > 1 || !EASY_GLOBALS.display_only_relevant_stats)
            {
                item->setTimeSmart(COL_MIN_PER_FRAME, per_frame_stats->min_duration, "min ");
                item->setTimeSmart(COL_MAX_PER_FRAME, per_frame_stats->max_duration, "max ");
                item->setTimeSmart(COL_AVERAGE_PER_FRAME, per_frame_stats->average_duration());
                item->setTimeSmart(COL_DURATION_SUM_PER_FRAME, per_frame_stats->total_duration);
            }

            item->setData(COL_NCALLS_PER_FRAME, Qt::UserRole, per_frame_stats->calls_number);
            item->setText(COL_NCALLS_PER_FRAME, QString::number(per_frame_stats->calls_number));
        }
        else
        {
            if (_frame == nullptr && _thread != nullptr)
            {
                auto percentage_per_thread = ::profiler_gui::percent(duration, _thread->selfDuration());
                item->setData(COL_PERCENT_PER_PARENT, Qt::UserRole, percentage_per_thread);
                item->setText(COL_PERCENT_PER_PARENT, QString::number(percentage_per_thread));
            }
            else
            {
                item->setData(COL_PERCENT_PER_PARENT, Qt::UserRole, 0);
            }

            item->setData(COL_PERCENT_SUM_PER_PARENT, Qt::UserRole, 0);
            item->setData(COL_PERCENT_SUM_PER_THREAD, Qt::UserRole, 0);
        }

        const auto color = easyDescriptor(child.node->id()).color();
        //const auto bgColor = ::profiler_gui::fromProfilerRgb(::profiler::colors::get_red(color), ::profiler::colors::get_green(color), ::profiler::colors::get_blue(color));
        const auto fgColor = ::profiler_gui::textColorForRgb(color);// 0x00ffffff - bgColor;
        item->setBackgroundColor(color);
        item->setTextColor(fgColor);

        auto item_index = static_cast<uint32_t>(_items.size());
        _items.push_back(item);

        size_t children_items_number = 0;
        ::profiler::timestamp_t children_duration = 0;
        if (!child.children.empty())
        {
            children_items_number = FillTreeClass<T>::setTreeInternal(_safelocker, _items, _beginTime, child.children, item, _frame ? _frame : item, _thread, _left, _right, _strict, children_duration, _colorizeRows);
            if (_safelocker.interrupted())
                break;
        }

        int percentage = 100;
        auto self_duration = duration - children_duration;
        if (children_duration > 0 && duration > 0)
        {
            percentage = ::profiler_gui::percent(self_duration, duration);
        }

        item->setTimeSmart(COL_SELF_DURATION, self_duration);
        item->setData(COL_SELF_DURATION_PERCENT, Qt::UserRole, percentage);
        item->setText(COL_SELF_DURATION_PERCENT, QString::number(percentage));

        if (children_items_number > 0 || !_strict || (startTime >= _left && endTime <= _right))
        {
            total_items += children_items_number + 1;
            gui_block.tree_item = item_index;

            if (_colorizeRows)
                item->colorize(_colorizeRows);

            if (gui_block.expanded)
                item->setExpanded(true);
        }
        else
        {
            _items.pop_back();
            delete item;
        }
    }

    return total_items;
}
예제 #15
0
void FillTreeClass<T>::setTreeInternal2(T& _safelocker, Items& _items, ThreadedItems& _topLevelItems, const ::profiler::timestamp_t& _beginTime, const ::profiler_gui::TreeBlocks& _blocks, ::profiler::timestamp_t _left, ::profiler::timestamp_t _right, bool _strict, bool _colorizeRows)
{
    //size_t blocksNumber = 0;
    //for (const auto& block : _blocks)
    //    blocksNumber += calculateTotalChildrenNumber(*block.tree);
    //    //blocksNumber += block.tree->total_children_number;
    //m_items.reserve(blocksNumber + _blocks.size()); // blocksNumber does not include root blocks

    RootsMap threadsMap;

    const auto u_thread = ::profiler_gui::toUnicode("thread");
    int i = 0, total = static_cast<int>(_blocks.size());
    //const QSignalBlocker b(this);
    for (const auto& block : _blocks)
    {
        if (_safelocker.interrupted())
            break;

        auto& gui_block = easyBlock(block.tree);
        const auto startTime = gui_block.tree.node->begin();
        const auto endTime = gui_block.tree.node->end();
        if (startTime > _right || endTime < _left)
        {
            _safelocker.setProgress((90 * ++i) / total);
            continue;
        }

        ::profiler::timestamp_t duration = 0;
        EasyTreeWidgetItem* thread_item = nullptr;
        auto thread_item_it = threadsMap.find(block.root->thread_id);
        if (thread_item_it != threadsMap.end())
        {
            thread_item = thread_item_it->second;
        }
        else
        {
            thread_item = new EasyTreeWidgetItem();

            QString threadName;
            if (block.root->got_name())
            {
                QString rootname(::profiler_gui::toUnicode(block.root->name()));
                if (rootname.contains(u_thread, Qt::CaseInsensitive))
                    threadName = ::std::move(QString("%1 %2").arg(rootname).arg(block.root->thread_id));
                else
                    threadName = ::std::move(QString("%1 Thread %2").arg(rootname).arg(block.root->thread_id));
            }
            else
            {
                threadName = ::std::move(QString("Thread %1").arg(block.root->thread_id));
            }

            thread_item->setText(COL_NAME, threadName);

            if (!block.root->children.empty())
                duration = blocksTree(block.root->children.back()).node->end() - blocksTree(block.root->children.front()).node->begin();

            thread_item->setTimeSmart(COL_DURATION, duration);
            thread_item->setBackgroundColor(::profiler_gui::SELECTED_THREAD_BACKGROUND);
            thread_item->setTextColor(::profiler_gui::SELECTED_THREAD_FOREGROUND);

            // Sum of all children durations:
            thread_item->setTimeSmart(COL_SELF_DURATION, block.root->active_time);

            threadsMap.insert(::std::make_pair(block.root->thread_id, thread_item));
        }

        auto item = new EasyTreeWidgetItem(block.tree, thread_item);
        duration = endTime - startTime;

        auto name = *gui_block.tree.node->name() != 0 ? gui_block.tree.node->name() : easyDescriptor(gui_block.tree.node->id()).name();
        item->setText(COL_NAME, ::profiler_gui::toUnicode(name));
        item->setTimeSmart(COL_DURATION, duration);
        item->setTimeMs(COL_BEGIN, startTime - _beginTime);
        item->setTimeMs(COL_END, endTime - _beginTime);

        item->setData(COL_PERCENT_PER_FRAME, Qt::UserRole, 0);

        auto percentage_per_thread = ::profiler_gui::percent(duration, block.root->active_time);
        item->setData(COL_PERCENT_PER_PARENT, Qt::UserRole, percentage_per_thread);
        item->setText(COL_PERCENT_PER_PARENT, QString::number(percentage_per_thread));

        if (gui_block.tree.per_thread_stats != nullptr) // if there is per_thread_stats then there are other stats also
        {
            const auto& per_thread_stats = gui_block.tree.per_thread_stats;
            const auto& per_parent_stats = gui_block.tree.per_parent_stats;
            const auto& per_frame_stats = gui_block.tree.per_frame_stats;


            if (per_thread_stats->calls_number > 1 || !EASY_GLOBALS.display_only_relevant_stats)
            {
                item->setTimeSmart(COL_MIN_PER_THREAD, per_thread_stats->min_duration, "min ");
                item->setTimeSmart(COL_MAX_PER_THREAD, per_thread_stats->max_duration, "max ");
                item->setTimeSmart(COL_AVERAGE_PER_THREAD, per_thread_stats->average_duration());
                item->setTimeSmart(COL_DURATION_SUM_PER_THREAD, per_thread_stats->total_duration);
            }

            item->setData(COL_NCALLS_PER_THREAD, Qt::UserRole, per_thread_stats->calls_number);
            item->setText(COL_NCALLS_PER_THREAD, QString::number(per_thread_stats->calls_number));

            percentage_per_thread = ::profiler_gui::percent(per_thread_stats->total_duration, block.root->active_time);
            item->setData(COL_PERCENT_SUM_PER_THREAD, Qt::UserRole, percentage_per_thread);
            item->setText(COL_PERCENT_SUM_PER_THREAD, QString::number(percentage_per_thread));


            if (per_parent_stats->calls_number > 1 || !EASY_GLOBALS.display_only_relevant_stats)
            {
                item->setTimeSmart(COL_MIN_PER_PARENT, per_parent_stats->min_duration, "min ");
                item->setTimeSmart(COL_MAX_PER_PARENT, per_parent_stats->max_duration, "max ");
                item->setTimeSmart(COL_AVERAGE_PER_PARENT, per_parent_stats->average_duration());
                item->setTimeSmart(COL_DURATION_SUM_PER_PARENT, per_parent_stats->total_duration);
            }

            item->setData(COL_NCALLS_PER_PARENT, Qt::UserRole, per_parent_stats->calls_number);
            item->setText(COL_NCALLS_PER_PARENT, QString::number(per_parent_stats->calls_number));


            if (per_frame_stats->calls_number > 1 || !EASY_GLOBALS.display_only_relevant_stats)
            {
                item->setTimeSmart(COL_MIN_PER_FRAME, per_frame_stats->min_duration, "min ");
                item->setTimeSmart(COL_MAX_PER_FRAME, per_frame_stats->max_duration, "max ");
                item->setTimeSmart(COL_AVERAGE_PER_FRAME, per_frame_stats->average_duration());
                item->setTimeSmart(COL_DURATION_SUM_PER_FRAME, per_frame_stats->total_duration);
            }

            item->setData(COL_NCALLS_PER_FRAME, Qt::UserRole, per_frame_stats->calls_number);
            item->setText(COL_NCALLS_PER_FRAME, QString::number(per_frame_stats->calls_number));
        }
        else
        {
            item->setData(COL_PERCENT_SUM_PER_THREAD, Qt::UserRole, 0);
            item->setText(COL_PERCENT_SUM_PER_THREAD, "");
        }

        const auto color = easyDescriptor(gui_block.tree.node->id()).color();
        //const auto bgColor = ::profiler_gui::fromProfilerRgb(::profiler::colors::get_red(color), ::profiler::colors::get_green(color), ::profiler::colors::get_blue(color));
        const auto fgColor = ::profiler_gui::textColorForRgb(color);//0x00ffffff - bgColor;
        item->setBackgroundColor(color);
        item->setTextColor(fgColor);

        auto item_index = static_cast<unsigned int>(_items.size());
        _items.push_back(item);

        size_t children_items_number = 0;
        ::profiler::timestamp_t children_duration = 0;
        if (!gui_block.tree.children.empty())
        {
            children_items_number = FillTreeClass<T>::setTreeInternal(_safelocker, _items, _beginTime, gui_block.tree.children, item, item, thread_item, _left, _right, _strict, children_duration, _colorizeRows);
            if (_safelocker.interrupted())
                break;
        }

        int percentage = 100;
        auto self_duration = duration - children_duration;
        if (children_duration > 0 && duration > 0)
        {
            percentage = static_cast<int>(0.5 + 100. * static_cast<double>(self_duration) / static_cast<double>(duration));
        }

        item->setTimeSmart(COL_SELF_DURATION, self_duration);
        item->setData(COL_SELF_DURATION_PERCENT, Qt::UserRole, percentage);
        item->setText(COL_SELF_DURATION_PERCENT, QString::number(percentage));

        if (children_items_number > 0 || !_strict || (startTime >= _left && endTime <= _right))
        {
            //total_items += children_items_number + 1;
            gui_block.tree_item = item_index;

            if (_colorizeRows)
                item->colorize(_colorizeRows);

            if (gui_block.expanded)
                item->setExpanded(true);

        }
        else
        {
            _items.pop_back();
            delete item;
        }

        _safelocker.setProgress((90 * ++i) / total);
    }

    i = 0;
    total = static_cast<int>(threadsMap.size());
    for (auto& it : threadsMap)
    {
        auto item = it.second;

        if (item->childCount() > 0)
        {
            //addTopLevelItem(item);
            //m_roots[it.first] = item;

            //_items.push_back(item);
            _topLevelItems.emplace_back(it.first, item);

            //++total_items;
        }
        else
        {
            delete item;
        }

        _safelocker.setProgress(90 + (10 * ++i) / total);
    }

    _safelocker.setDone();
    //return total_items;
}
예제 #16
0
DecodeResults *
SegmentDecoder :: decode(Instance *inst, Parameter *param) {

    Items *items = inst->items();
    int len = items->size();
    int numFeatures = m_Model->getAlphabet("FEATURES")->size();
    int numLabels   = m_Model->getAlphabet("LABELS")->size();

    double **uniScoreCache = new double *[len];
    for (int i = 0; i < len; ++ i) {
        uniScoreCache[i] = new double[numLabels];
        Item *item = items->at(i);
        for (int label = 0; label < numLabels; ++ label) {
            uniScoreCache[i][label] = 0.0;

            int sz = item->size(label);
            for (int j = 0; j < sz; ++ j) {
                uniScoreCache[i][label] += param->value(item->at(j, label));
            }
        }
    }

    double **biScoreCache = new double *[numLabels + 1];
    for (int prevLabel = 0; prevLabel <= numLabels; ++ prevLabel) {
        biScoreCache[prevLabel] = new double[numLabels];
        for (int currLabel = 0; currLabel < numLabels; ++ currLabel) {
            biScoreCache[prevLabel][currLabel] = param->value(
                    numFeatures * numLabels
                    + prevLabel * numLabels
                    + currLabel);

        }
    }

    KHeap<DecodeState> **states = new KHeap<DecodeState> *[len];
    for (int i = 0; i < len; ++ i) {
        states[i] = new KHeap<DecodeState>[numLabels];
        for (int j = 0; j < numLabels; ++ j) {
            states[i][j].setK(m_Agenda);
        }
    }

    for (int i = 0; i < len; ++ i) {
        // fprintf(stderr, "i=%d\n", i);
        for (int currLabel = 0; currLabel < numLabels; ++ currLabel) {
            if (i == 0) {
                // fprintf(stderr, "!%d->%d\n", numLabels, currLabel);
                if (m_Legal[numLabels][currLabel] == 0) {
                    continue;
                }

                double score = uniScoreCache[0][currLabel] + biScoreCache[numLabels][currLabel];
                states[i][currLabel].insert(DecodeState(currLabel, score, NULL));
            } else {
                for (int prevLabel = 0; prevLabel < numLabels; ++ prevLabel) {
                    if (m_Legal[prevLabel][currLabel] == 0)
                        continue;
                    for (int j = 0; j < states[i - 1][prevLabel].size(); ++ j) {
                        DecodeState *prev = states[i - 1][prevLabel].at(j);
                        double score = prev->score + 
                            uniScoreCache[i][currLabel] + biScoreCache[prevLabel][currLabel];
                        // printf("#%d->%d\n", prevLabel, currLabel);
                        states[i][currLabel].insert(DecodeState(currLabel, score, prev));
                    }
                }
            }
        }
    }

    vector<DecodeState> result_cache;

    for (int label = 0; label < numLabels; ++ label) {
        for (int i = 0; i < states[len - 1][label].size(); ++ i) {
            result_cache.push_back( *states[len - 1][label].at(i) );
        }
    }
    sort( result_cache.begin(), result_cache.end() );

    DecodeResults *ret = new CppDecodeResults();

    for (int i = 0; ((i < m_Agenda) && (result_cache.size() - i > 0)); ++ i) {
        Labels* single = new CppLabels(len);

        int pos = len - 1;
        DecodeState *now = &result_cache[result_cache.size() - i - 1];
        //DecodeState *now = result_cache.at(i);
        for (; pos >= 0; -- pos, now = now->prev) {
            single->set(now->label, pos);
        }
        ret->append( single );
    }

    for (int i = 0; i < len; ++ i)        { delete []uniScoreCache[i]; } delete []uniScoreCache;
    for (int i = 0; i <= numLabels; ++ i) { delete []biScoreCache[i];  } delete []biScoreCache;
    for (int i = 0; i < len; ++ i)        { delete []states[i];        } delete []states;

    return ret;
}