Ejemplo n.º 1
0
 MPI_Int count() const
 {
     return count(MPI_TYPE_<T>::value());
 }
Ejemplo n.º 2
0
QSize TabBar::tabSizeHint(int index, bool fast) const
{
    if (!m_window->isVisible()) {
        // Don't calculate it when window is not visible
        // It produces invalid size anyway
        return QSize(-1, -1);
    }

    const int pinnedTabWidth = comboTabBarPixelMetric(ComboTabBar::PinnedTabWidth);
    const int minTabWidth = comboTabBarPixelMetric(ComboTabBar::NormalTabMinimumWidth);

    QSize size = ComboTabBar::tabSizeHint(index);

    // The overflowed tabs have same size and we can use this fast method
    if (fast) {
        size.setWidth(index >= pinnedTabsCount() ? minTabWidth : pinnedTabWidth);
        return size;
    }

    WebTab* webTab = qobject_cast<WebTab*>(m_tabWidget->widget(index));
    TabBar* tabBar = const_cast <TabBar*>(this);

    if (webTab && webTab->isPinned()) {
        size.setWidth(pinnedTabWidth);
    }
    else {
        int availableWidth = mainTabBarWidth() - comboTabBarPixelMetric(ExtraReservedWidth);

        if (availableWidth < 0) {
            return QSize(-1, -1);
        }

        const int normalTabsCount = ComboTabBar::normalTabsCount();
        const int maxTabWidth = comboTabBarPixelMetric(ComboTabBar::NormalTabMaximumWidth);

        if (availableWidth >= maxTabWidth * normalTabsCount) {
            m_normalTabWidth = maxTabWidth;
            size.setWidth(m_normalTabWidth);
        }
        else if (normalTabsCount > 0) {
            const int minActiveTabWidth = comboTabBarPixelMetric(ComboTabBar::ActiveTabMinimumWidth);

            int maxWidthForTab = availableWidth / normalTabsCount;
            int realTabWidth = maxWidthForTab;
            bool adjustingActiveTab = false;

            if (realTabWidth < minActiveTabWidth) {
                maxWidthForTab = normalTabsCount > 1 ? (availableWidth - minActiveTabWidth) / (normalTabsCount - 1) : 0;
                realTabWidth = minActiveTabWidth;
                adjustingActiveTab = true;
            }

            bool tryAdjusting = availableWidth >= minTabWidth * normalTabsCount;

            if (m_showCloseOnInactive != 1 && tabsClosable() && availableWidth < (minTabWidth + 25) * normalTabsCount) {
                // Hiding close buttons to save some space
                tabBar->setTabsClosable(false);
                tabBar->showCloseButton(currentIndex());
            }
            if (m_showCloseOnInactive == 1) {
                // Always showing close buttons
                tabBar->setTabsClosable(true);
                tabBar->showCloseButton(currentIndex());
            }

            if (tryAdjusting) {
                m_normalTabWidth = maxWidthForTab;

                // Fill any empty space (we've got from rounding) with active tab
                if (index == mainTabBarCurrentIndex()) {
                    if (adjustingActiveTab) {
                        m_activeTabWidth = (availableWidth - minActiveTabWidth
                                            - maxWidthForTab * (normalTabsCount - 1)) + realTabWidth;
                    }
                    else {
                        m_activeTabWidth = (availableWidth - maxWidthForTab * normalTabsCount) + maxWidthForTab;
                    }
                    size.setWidth(m_activeTabWidth);
                }
                else {
                    size.setWidth(m_normalTabWidth);
                }
            }
        }

        // Restore close buttons according to preferences
        if (m_showCloseOnInactive != 2 && !tabsClosable() && availableWidth >= (minTabWidth + 25) * normalTabsCount) {
            tabBar->setTabsClosable(true);

            // Hide close buttons on pinned tabs
            for (int i = 0; i < count(); ++i) {
                tabBar->updatePinnedTabCloseButton(i);
            }
        }
    }

    if (index == count() - 1) {
        WebTab* lastMainActiveTab = qobject_cast<WebTab*>(m_tabWidget->widget(mainTabBarCurrentIndex()));
        int xForAddTabButton = cornerWidth(Qt::TopLeftCorner) + pinTabBarWidth() + normalTabsCount() * m_normalTabWidth;

        if (lastMainActiveTab && m_activeTabWidth > m_normalTabWidth) {
            xForAddTabButton += m_activeTabWidth - m_normalTabWidth;
        }

        if (QApplication::layoutDirection() == Qt::RightToLeft) {
            xForAddTabButton = width() - xForAddTabButton;
        }

        emit tabBar->moveAddTabButton(xForAddTabButton);
    }

    return size;
}
Ejemplo n.º 3
0
	bool wait(std::chrono::duration<rep, period> t) {
		auto d = std::chrono::duration_cast<std::chrono::microseconds>(t);
		return wait(d.count());
	}
Ejemplo n.º 4
0
static ssize_t MSMachONameList_(const void *stuff, struct MSSymbolData *list, size_t nreq) {
    // XXX: ok, this is just pathetic; API fail much?
    size_t slide(0);
    for (uint32_t image(0), images(_dyld_image_count()); image != images; ++image)
        if (_dyld_get_image_header(image) == stuff) {
            slide = _dyld_get_image_vmaddr_slide(image);
            goto fat;
        }

    return -1;

fat:
    const uint8_t *base(reinterpret_cast<const uint8_t *>(stuff));
    const struct exec *buf(reinterpret_cast<const struct exec *>(base));

    if (OSSwapBigToHostInt32(buf->a_magic) == FAT_MAGIC) {
        struct host_basic_info hbi;
        {
            host_t host(mach_host_self());
            mach_msg_type_number_t count(HOST_BASIC_INFO_COUNT);
            if (host_info(host, HOST_BASIC_INFO, reinterpret_cast<host_info_t>(&hbi), &count) != KERN_SUCCESS)
                return -1;
            mach_port_deallocate(mach_task_self(), host);
        }

        const struct fat_header *fh(reinterpret_cast<const struct fat_header *>(base));
        uint32_t nfat_arch(OSSwapBigToHostInt32(fh->nfat_arch));
        const struct fat_arch *fat_archs(reinterpret_cast<const struct fat_arch *>(fh + 1));

        for (uint32_t i(0); i != nfat_arch; ++i)
            if (static_cast<cpu_type_t>(OSSwapBigToHostInt32(fat_archs[i].cputype)) == hbi.cpu_type) {
                buf = reinterpret_cast<const struct exec *>(base + OSSwapBigToHostInt32(fat_archs[i].offset));
                goto thin;
            }

        return -1;
    }

thin:
    const nlist_xx *symbols;
    const char *strings;
    size_t n;

    // XXX: this check looks really scary when it fails
    if (buf->a_magic == MH_MAGIC_XX) {
        const mach_header_xx *mh(reinterpret_cast<const mach_header_xx *>(base));
        const struct load_command *load_commands(reinterpret_cast<const struct load_command *>(mh + 1));

        const struct symtab_command *stp(NULL);
        const struct load_command *lcp;

        /* forlc (command, mh, LC_SYMTAB, struct symtab_command) {
            stp = command;
            goto found;
        } */

        lcp = load_commands;
        for (uint32_t i(0); i != mh->ncmds; ++i) {
            if (
                lcp->cmdsize % sizeof(long) != 0 || lcp->cmdsize <= 0 ||
                reinterpret_cast<const uint8_t *>(lcp) + lcp->cmdsize > reinterpret_cast<const uint8_t *>(load_commands) + mh->sizeofcmds
            )
                return -1;

            if (lcp->cmd == LC_SYMTAB) {
                if (lcp->cmdsize != sizeof(struct symtab_command))
                    return -1;
                stp = reinterpret_cast<const struct symtab_command *>(lcp);
                goto found;
            }

            lcp = reinterpret_cast<const struct load_command *>(reinterpret_cast<const uint8_t *>(lcp) + lcp->cmdsize);
        }

        return -1;

found:
        n = stp->nsyms;

        symbols = NULL;
        strings = NULL;

        /* forlc (command, mh, LC_SEGMENT_XX, segment_command_xx) {
            stp = command;
            goto found;
        } */

        lcp = load_commands;
        for (uint32_t i(0); i != mh->ncmds; ++i) {
            if (
                lcp->cmdsize % sizeof(long) != 0 || lcp->cmdsize <= 0 ||
                reinterpret_cast<const uint8_t *>(lcp) + lcp->cmdsize > reinterpret_cast<const uint8_t *>(load_commands) + mh->sizeofcmds
            )
                return -1;

            if (lcp->cmd == LC_SEGMENT_XX) {
                if (lcp->cmdsize < sizeof(segment_command_xx))
                    return -1;
                const segment_command_xx *segment(reinterpret_cast<const segment_command_xx *>(lcp));
                if (stp->symoff >= segment->fileoff && stp->symoff < segment->fileoff + segment->filesize)
                    symbols = reinterpret_cast<const nlist_xx *>(stp->symoff - segment->fileoff + segment->vmaddr + slide);
                if (stp->stroff >= segment->fileoff && stp->stroff < segment->fileoff + segment->filesize)
                    strings = reinterpret_cast<const char *>(stp->stroff - segment->fileoff + segment->vmaddr + slide);
            }

            lcp = reinterpret_cast<const struct load_command *>(reinterpret_cast<const uint8_t *>(lcp) + lcp->cmdsize);
        }

        if (symbols == NULL || strings == NULL)
            return -1;
        // XXX: detect a.out somehow?
    } else if (false) {
        /* XXX: is this right anymore?!? */
        symbols = reinterpret_cast<const nlist_xx *>(base + N_SYMOFF(*buf));
        strings = reinterpret_cast<const char *>(reinterpret_cast<const uint8_t *>(symbols) + buf->a_syms);
        n = buf->a_syms / sizeof(nlist_xx);
    } else return -1;

    size_t result(nreq);

    for (size_t m(0); m != n; ++m) {
        const nlist_xx *q(&symbols[m]);
        if (q->n_un.n_strx == 0 || (q->n_type & N_STAB) != 0)
            continue;

        const char *nambuf(strings + q->n_un.n_strx);
        //fprintf(stderr, " == %s\n", nambuf);

        for (size_t item(0); item != nreq; ++item) {
            struct MSSymbolData *p(list + item);
            if (p->name_ == NULL || strcmp(p->name_, nambuf) != 0)
                continue;

            p->name_ = NULL;

            p->value_ = q->n_value;
            if (p->value_ != 0)
                p->value_ += slide;

            p->type_ = q->n_type;
            p->desc_ = q->n_desc;
            p->sect_ = q->n_sect;

            if (--result == 0)
                return 0;
            break;
        }
    }

    return result;
}
Ejemplo n.º 5
0
void UsersList::selectOwner()
{
   for( int i = 0; i < count(); i++)
      if((item(i)->text() == username) && (false == item(i)->isSelected()))
         item(i)->setSelected( true);
}
Ejemplo n.º 6
0
void AssetServer::sendStatsPacket() {
    QJsonObject serverStats;
    
    auto stats = DependencyManager::get<NodeList>()->sampleStatsForAllConnections();
    
    for (const auto& stat : stats) {
        QJsonObject nodeStats;
        auto endTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(stat.second.endTime);
        QDateTime date = QDateTime::fromMSecsSinceEpoch(endTimeMs.count());
        
        static const float USEC_PER_SEC = 1000000.0f;
        static const float MEGABITS_PER_BYTE = 8.0f / 1000000.0f; // Bytes => Mbits
        float elapsed = (float)(stat.second.endTime - stat.second.startTime).count() / USEC_PER_SEC; // sec
        float megabitsPerSecPerByte = MEGABITS_PER_BYTE / elapsed; // Bytes => Mb/s
        
        QJsonObject connectionStats;
        connectionStats["1. Last Heard"] = date.toString();
        connectionStats["2. Est. Max (P/s)"] = stat.second.estimatedBandwith;
        connectionStats["3. RTT (ms)"] = stat.second.rtt;
        connectionStats["4. CW (P)"] = stat.second.congestionWindowSize;
        connectionStats["5. Period (us)"] = stat.second.packetSendPeriod;
        connectionStats["6. Up (Mb/s)"] = stat.second.sentBytes * megabitsPerSecPerByte;
        connectionStats["7. Down (Mb/s)"] = stat.second.receivedBytes * megabitsPerSecPerByte;
        nodeStats["Connection Stats"] = connectionStats;
        
        using Events = udt::ConnectionStats::Stats::Event;
        const auto& events = stat.second.events;
        
        QJsonObject upstreamStats;
        upstreamStats["1. Sent (P/s)"] = stat.second.sendRate;
        upstreamStats["2. Sent Packets"] = stat.second.sentPackets;
        upstreamStats["3. Recvd ACK"] = events[Events::ReceivedACK];
        upstreamStats["4. Procd ACK"] = events[Events::ProcessedACK];
        upstreamStats["5. Recvd LACK"] = events[Events::ReceivedLightACK];
        upstreamStats["6. Recvd NAK"] = events[Events::ReceivedNAK];
        upstreamStats["7. Recvd TNAK"] = events[Events::ReceivedTimeoutNAK];
        upstreamStats["8. Sent ACK2"] = events[Events::SentACK2];
        upstreamStats["9. Retransmitted"] = events[Events::Retransmission];
        nodeStats["Upstream Stats"] = upstreamStats;
        
        QJsonObject downstreamStats;
        downstreamStats["1. Recvd (P/s)"] = stat.second.receiveRate;
        downstreamStats["2. Recvd Packets"] = stat.second.receivedPackets;
        downstreamStats["3. Sent ACK"] = events[Events::SentACK];
        downstreamStats["4. Sent LACK"] = events[Events::SentLightACK];
        downstreamStats["5. Sent NAK"] = events[Events::SentNAK];
        downstreamStats["6. Sent TNAK"] = events[Events::SentTimeoutNAK];
        downstreamStats["7. Recvd ACK2"] = events[Events::ReceivedACK2];
        downstreamStats["8. Duplicates"] = events[Events::Duplicate];
        nodeStats["Downstream Stats"] = downstreamStats;
        
        QString uuid;
        auto nodelist = DependencyManager::get<NodeList>();
        if (stat.first == nodelist->getDomainHandler().getSockAddr()) {
            uuid = uuidStringWithoutCurlyBraces(nodelist->getDomainHandler().getUUID());
            nodeStats[USERNAME_UUID_REPLACEMENT_STATS_KEY] = "DomainServer";
        } else {
            auto node = nodelist->findNodeWithAddr(stat.first);
            uuid = uuidStringWithoutCurlyBraces(node ? node->getUUID() : QUuid());
            nodeStats[USERNAME_UUID_REPLACEMENT_STATS_KEY] = uuid;
        }
        
        serverStats[uuid] = nodeStats;
    }
    
    // send off the stats packets
    ThreadedAssignment::addPacketStatsAndSendStatsPacket(serverStats);
}
Ejemplo n.º 7
0
void GLWidget3D::generateTrainingData() {
	srand(2);

	QString baseResultDir = "C:\\Anaconda\\caffe\\data\\pmtree2dgrid\\pmtree2dgrid\\";

	if (QDir(baseResultDir).exists()) {
		QDir(baseResultDir).removeRecursively();
	}
	QDir().mkpath(baseResultDir);

	std::vector<int> count(4, 0);
	for (int n = 0; n < 300; ++n) {
		// 枝が地面にぶつからないよう、ランダムに生成
		while (true) {
			renderManager.removeObjects();
			tree.generateRandom();
			if (!tree.generateGeometry(&renderManager, false)) break;
		}

		// render the tree with color
		renderManager.renderingMode = RenderManager::RENDERING_MODE_BASIC;
		render();

		// cv::Mat形式に変換
		QImage img = grabFrameBuffer();
		cv::Mat imageMat = cv::Mat(img.height(), img.width(), CV_8UC4, img.bits(), img.bytesPerLine()).clone();

		// 2560x2560に変換
		cv::resize(imageMat, imageMat, cv::Size(2560, 2560));

		// render the tree with line rendering
		renderManager.renderingMode = RenderManager::RENDERING_MODE_LINE;
		render();

		// cv::Mat形式に変換
		QImage img2 = grabFrameBuffer();
		cv::Mat imageMat2 = cv::Mat(img2.height(), img2.width(), CV_8UC4, img2.bits(), img2.bytesPerLine()).clone();

		// 2560x2560に変換
		cv::resize(imageMat2, imageMat2, cv::Size(2560, 2560));

		// 10x10に分割
		int patch_width = imageMat.cols / 10;
		int patch_height = imageMat.rows / 10;
		int stride = patch_width / 3;
		for (int r = 0; r < imageMat.rows - patch_height; r += stride) {
			for (int c = 0; c < imageMat.cols - patch_width; c += stride) {
				cv::Mat patch(imageMat, cv::Rect(c, r, patch_width, patch_height));
				cv::Mat patch2(imageMat2, cv::Rect(c, r, patch_width, patch_height));

				// patchのタイプを計算
				int type = computePatchType(patch);

				// make directory
				QString resultDir = QString(baseResultDir + "pmtree2dgrid_%1\\").arg(type, 2, 10, QChar('0'));
				if (!QDir(resultDir).exists()) {
					QDir().mkdir(resultDir);
				}

				// 画像をファイルに保存
				QString filename = resultDir + QString("image_%1.png").arg(count[type]++, 6, 10, QChar('0'));
				cv::imwrite(filename.toUtf8().constData(), patch2);
			}
		}
	}
}
Ejemplo n.º 8
0
int main() {
    /*int c = 0;
    std::thread t(shit, 2, 3, std::ref(c));
    std::cout << c << std::endl;
    sc::Library lib("core.dll");
    modfunc f = (modfunc)lib.GetSymbol("initMod");
    f();*/

    //std::string hash = sha1::hash("x3JJHMbDL1EzLkh9GBhXDw==258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
    //std::string str = sc::str::tolower("x3JJHMbDL1 € EzLkh9GBh¢XDw==");

    //auto ef = sc::str::split("fu\nck", '\n');

    //std::cout << calculateConnectionHash(str);

    //std::cout << base64_decode("HSmrc0sMlYUkAGmm5OPpG2HaGWk=");

#ifdef _WIN32
    SetConsoleCtrlHandler((PHANDLER_ROUTINE)&ctrlHandler, TRUE);
    WSADATA wdata;
    if(WSAStartup(MAKEWORD(2, 2), &wdata) != 0)
        return false;
#else
    signal(SIGINT, sigHandler);
    signal(SIGTERM, sigHandler);
    signal(SIGABRT, sigHandler);
#endif

    auto req = sc::HTTPRequest::Get("http://chat.flashii.net/", {
        {"view", "auth"},
        {"arg1", "303"},
        {"arg2", "2ef2094972cc00f0860cd85e96a243eaac67497d"}
    });
    std::cout << req.content;

    //auto req = sc::HTTPRequest::Get("http://aroltd.com/");

    //std::string wowo = sc::net::packTime();

    sc::INI test;
    try {
        test = sc::INI("c_config.ini", {
            {"socket", {
                {"client_root", sc::INI::STRING},
                {"port",        sc::INI::INTEGER}
            }},
            {"structure", {
                {"backlog_length",  sc::INI::INTEGER},
                {"default_channel", sc::INI::STRING}
            }},
            {"limits", {
                {"max_conns_per_ip",        sc::INI::INTEGER},
                {"max_channel_depth",       sc::INI::INTEGER},
                {"max_channel_name_length", sc::INI::INTEGER},
                {"max_username_length",     sc::INI::INTEGER},
                {"max_message_length",      sc::INI::INTEGER},
                {"max_idle_time",           sc::INI::INTEGER}
            }}
        });
    } catch(std::exception &e) {
        std::cout << e.what() << std::endl;
        return -1;
    }

    std::string a = test["socket"]["port"];

    sc::Socket client;
    if(!sock.Init(6770)) {
        std::cout << "Could not open socket on port 6770! Error: " << std::endl;
        return -1;
    }
    sock.SetBlocking(false);

    int status;
    auto conns = std::map<std::string, ThreadContext*>();
    while(true) {
        if((status = sock.Accept(client)) == 0) {
            if(conns.count(client.GetIPAddress()) == 0) {
                auto tmp = new ThreadContext(new sc::Socket(client));
                conns[client.GetIPAddress()] = tmp;
                std::thread(connectionThread, tmp).detach();
            } else
                conns[client.GetIPAddress()]->PushSocket(new sc::Socket(client));
        } else if(status == -1) break;

        for(auto i = conns.begin(); i != conns.end(); ) {
            if(i->second->IsDone()) {
                delete i->second;
                i = conns.erase(i);
            } else ++i;
        }
    }

    sock.Close();

#ifdef _WIN32
    WSACleanup();
#endif

    return 0;
}
Ejemplo n.º 9
0
void CTabWidget::update(int c)
{
	if(_visible)
	{
		move_panel(_panel, _pos.y(), _pos.x());
		//top_panel(_panel);
		wclear(_window);

		if(_listenKeys)
		{
			if(c == KEY_LEFT)
			{
				if(currentIndex() - 1 >= 0)
					setCurrentIndex(currentIndex() - 1);
				else
					setCurrentIndex(count() - 1);
			}
			else if(c == KEY_RIGHT)
			{
				if(currentIndex() + 1 < int(count()))
					setCurrentIndex(currentIndex() + 1);
				else
					setCurrentIndex(0);
			}
		}

		uint tw = _size.width() - _leftMargin - _rightMargin;

		// Is left mouse button pressed?
#ifdef __PDCURSES__
		bool leftClick = focused() && Mouse_status.button[0] == BUTTON_PRESSED;
#else
		bool leftClick = false;
		MEVENT event;
		if(getmouse(&event) == OK)
			leftClick = focused() && (event.bstate & BUTTON1_PRESSED);
#endif

		int k = 0;
		for(uint i = 0; i < _widgets.size(); ++i)
		{
			if(leftClick)
			{
				if(_mousePos.x() >= _pos.x() + _leftMargin + k &&
				   _mousePos.x() < _pos.x() + _leftMargin + k + _widgets[i]->name().size() &&
				   _mousePos.y() == (_bottom ? _pos.y() + _size.height() - 1 : _pos.y()))
				{
					// select tab
					setCurrentIndex(i);
				}
			}

			if(currentIndex() == i)
				wattr_on(_window, A_BOLD, 0);

			mvwaddstr(_window, _bottom ? _size.height() - 1 : 0, _leftMargin + k, _widgets[i]->name().c_str());

			if(_currentIndex == i)
				wattr_off(_window, A_BOLD, 0);

			k += _widgets[i]->name().size() + 1;
		}

		if(_layout)
		{
			if(_changed)
			{
				DEBUG_ui("CTabWidget::update, 0");
				_layout->setSize(_size.width(), _size.height() - 1);
				_layout->setPosition(_pos.x(), _bottom ? _pos.y() : _pos.y() + 1);
				_changed = false;
				DEBUG_ui("CTabWidget::update, 1");
			}

			_layout->update(c);
		}
	}
}
Ejemplo n.º 10
0
 template<typename Stream> inline void print(Stream & os) {
     os << "ValueType: " << typeid(value_type).name() << " " << std::endl;
     os << "Count: " << count() << " " << std::endl;
 }
Ejemplo n.º 11
0
// CREATE OR REPLACE FUNCTION pgr_dijkstraViaVertices(sql text, vertices anyarray, directed boolean default true,
void
do_pgr_dijkstraViaVertex(
        pgr_edge_t  *data_edges,    size_t total_tuples,
        int64_t  *via_vidsArr,      size_t size_via_vidsArr,
        bool directed,
        bool strict,
        bool U_turn_on_edge,
        Routes_t **return_tuples,   size_t *return_count,
        char ** err_msg){
    std::ostringstream log;
    try {

        if (total_tuples == 1) {
            log << "Requiered: more than one tuple\n";
            (*return_tuples) = NULL;
            (*return_count) = 0;
            *err_msg = strdup(log.str().c_str());
            return;
        }

        graphType gType = directed? DIRECTED: UNDIRECTED;
        const auto initial_size = total_tuples;

        std::deque< Path >paths;
        log << "Inserting vertices into a c++ vector structure\n";
        std::vector< int64_t > via_vertices(via_vidsArr, via_vidsArr + size_via_vidsArr);

        if (directed) {
            log << "Working with directed Graph\n";
            Pgr_base_graph< DirectedGraph > digraph(gType, initial_size);
            digraph.graph_insert_data(data_edges, total_tuples);
            pgr_dijkstraViaVertex(digraph, via_vertices, paths, strict, U_turn_on_edge, log);
        } else {
            log << "Working with Undirected Graph\n";
            Pgr_base_graph< UndirectedGraph > undigraph(gType, initial_size);
            undigraph.graph_insert_data(data_edges, total_tuples);
            pgr_dijkstraViaVertex(undigraph, via_vertices, paths, strict, U_turn_on_edge, log);
        }

        size_t count(count_tuples(paths));

        if (count == 0) {
            (*return_tuples) = NULL;
            (*return_count) = 0;
            log << 
                "No paths found between Starting and any of the Ending vertices\n";
            *err_msg = strdup(log.str().c_str());
            return;
        }

        // get the space required to store all the paths
        (*return_tuples) = get_memory(count, (*return_tuples));
        log << "Converting a set of paths into the tuples\n";
        (*return_count) = (get_route(return_tuples, paths));
        (*return_tuples)[count - 1].edge = -2;

#ifndef DEBUG
        *err_msg = strdup("OK");
#else
        *err_msg = strdup(log.str().c_str());
#endif
    } catch ( ... ) {
        log << "Caught unknown expection!\n";
        *err_msg = strdup(log.str().c_str());
    }
}
Ejemplo n.º 12
0
TabBar::~TabBar()
{
    while (count() > 0)
        removeTab(0);
}
Ejemplo n.º 13
0
void TabBar::dragLeaveEvent(QDragLeaveEvent *AEvent)
{
    if (!rect().contains(mapFromGlobal(QCursor::pos())))
        FLayout->moveItem(FPressedIndex, FLayout->orderToIndex(count()-1));
    QFrame::dragLeaveEvent(AEvent);
}
Ejemplo n.º 14
0
	void beginEvent(const std::string& label)
	{
		auto now = std::chrono::duration_cast<time_unit>(
					std::chrono::high_resolution_clock::now() - frameBegin);
		currentStack.push({label, now.count(), 0, {} });
	}
Ejemplo n.º 15
0
const KmerAffect&KmerAffectAnalyser::getAffectation(int i) const{
  assert(i >= 0 && i < count());
  return affectations[i];
}
Ejemplo n.º 16
0
void QTextHtmlImporter::import()
{
    cursor.beginEditBlock();
    hasBlock = true;
    forceBlockMerging = false;
    compressNextWhitespace = RemoveWhiteSpace;
    blockTagClosed = false;
    for (currentNodeIdx = 0; currentNodeIdx < count(); ++currentNodeIdx) {
        currentNode = &at(currentNodeIdx);
        wsm = textEditMode ? QTextHtmlParserNode::WhiteSpacePreWrap : currentNode->wsm;

        /*
         * process each node in three stages:
         * 1) check if the hierarchy changed and we therefore passed the
         *    equivalent of a closing tag -> we may need to finish off
         *    some structures like tables
         *
         * 2) check if the current node is a special node like a
         *    <table>, <ul> or <img> tag that requires special processing
         *
         * 3) if the node should result in a QTextBlock create one and
         *    finally insert text that may be attached to the node
         */

        /* emit 'closing' table blocks or adjust current indent level
         * if we
         *  1) are beyond the first node
         *  2) the current node not being a child of the previous node
         *      means there was a tag closing in the input html
         */
        if (currentNodeIdx > 0 && (currentNode->parent != currentNodeIdx - 1)) {
            blockTagClosed = closeTag();
            // visually collapse subsequent block tags, but if the element after the closed block tag
            // is for example an inline element (!isBlock) we have to make sure we start a new paragraph by setting
            // hasBlock to false.
            if (blockTagClosed
                && !currentNode->isBlock()
                && currentNode->id != Html_unknown)
            {
                hasBlock = false;
            } else if (hasBlock) {
                // when collapsing subsequent block tags we need to clear the block format
                QTextBlockFormat blockFormat = currentNode->blockFormat;
                blockFormat.setIndent(indent);

                QTextBlockFormat oldFormat = cursor.blockFormat();
                if (oldFormat.hasProperty(QTextFormat::PageBreakPolicy)) {
                    QTextFormat::PageBreakFlags pageBreak = oldFormat.pageBreakPolicy();
                    if (pageBreak == QTextFormat::PageBreak_AlwaysAfter)
                        /* We remove an empty paragrah that requested a page break after.
                           moving that request to the next paragraph means we also need to make
                            that a pagebreak before to keep the same visual appearance.
                        */
                        pageBreak = QTextFormat::PageBreak_AlwaysBefore;
                    blockFormat.setPageBreakPolicy(pageBreak);
                }

                cursor.setBlockFormat(blockFormat);
            }
        }

        if (currentNode->displayMode == QTextHtmlElement::DisplayNone) {
            if (currentNode->id == Html_title)
                doc->setMetaInformation(QTextDocument::DocumentTitle, currentNode->text);
            // ignore explicitly 'invisible' elements
            continue;
        }

        if (processSpecialNodes() == ContinueWithNextNode)
            continue;

        // make sure there's a block for 'Blah' after <ul><li>foo</ul>Blah
        if (blockTagClosed
            && !hasBlock
            && !currentNode->isBlock()
            && !currentNode->text.isEmpty() && !currentNode->hasOnlyWhitespace()
            && currentNode->displayMode == QTextHtmlElement::DisplayInline) {

            QTextBlockFormat block = currentNode->blockFormat;
            block.setIndent(indent);

            appendBlock(block, currentNode->charFormat);

            hasBlock = true;
        }

        if (currentNode->isBlock()) {
            if (processBlockNode() == ContinueWithNextNode)
                continue;
        }

        if (currentNode->charFormat.isAnchor() && !currentNode->charFormat.anchorName().isEmpty()) {
            namedAnchors.append(currentNode->charFormat.anchorName());
        }

        if (appendNodeText())
            hasBlock = false; // if we actually appended text then we don't
                              // have an empty block anymore
    }

    cursor.endEditBlock();
}
Ejemplo n.º 17
0
affect_infos KmerAffectAnalyser::getMaximum(const KmerAffect &before, 
                                               const KmerAffect &after, 
                                               float ratioMin,
                                               int maxOverlap) {
  /* currentValue is the  { affectations[t] == before | t \in 1..i  } - | { affectations[i] == after | t \in 1..i }  */
  int currentValue;
  int span = kms.getS();
  int length = count();

  if (maxOverlap > span)
    maxOverlap = span;

  /* Initialize results */
  affect_infos results;
  results.max_found = false;
  results.max_value = 0;
  results.first_pos_max = results.last_pos_max = -1;
  results.nb_before_left = results.nb_before_right = results.nb_after_right = results.nb_after_left = 0;
  currentValue = 0;

  for (int i = 0; i < min(length,span - maxOverlap); i++) {
    if (affectations[i] == after) {
      currentValue--;
      results.nb_after_right++;
    }
  }

  for (int i = span - maxOverlap; i < length; i++) {
    /* i - span + maxOverlap, to avoir overlapping k-mers */


    /* Read the current affectations, and store them both in currentValue and at the right of the previous maximum.
       The affectation of 'before' is interpreted relatively to span and maxOverlap */

    if (affectations[i - span + maxOverlap] == before) {
      currentValue++;
      results.nb_before_right++;
    } 
    if (affectations[i] == after) {
      currentValue--;
      results.nb_after_right++;
    }

    /* Now currentValue = | { affectations[t - span + maxOverlap] == 'before' | t \in span-maxOverlap..i } | - | { affectations[i] == 'after' | t \in 0..i } | */

    /* If we raise above the max, or if we continue a previous maximum (even from a distant position), store in results */
    if (currentValue >= results.max_value) {
      if (currentValue > results.max_value)
        results.first_pos_max = i;
      results.max_value = currentValue;
      results.last_pos_max = i;

      /* What was at the right of the previous maximum is now at the left of the current maximum */
      results.nb_after_left += results.nb_after_right;
      results.nb_before_left += results.nb_before_right;
      results.nb_after_right = 0;
      results.nb_before_right = 0;
    }
  }
  for (int i = length - span + maxOverlap; i < length && i >= 0; i++) {
    if (affectations[i] == before)
      results.nb_before_right++;
  }

  left_evalue = kms.getProbabilityAtLeastOrAbove(before,
                                                 results.nb_before_left,
                                                 1 + results.first_pos_max);
  right_evalue = kms.getProbabilityAtLeastOrAbove(after,
                                                  results.nb_after_right,
                                                  seq.size() - 1 - results.last_pos_max);

  /* Main test: 
     1) do we have enough affectations in good positions ('before' at the left and 'after' at the right) ?
     We tolerate some of them in bad positions, but there must be 'ratioMin' more in good positions
     2) there should be at least one 'before' and one 'after' (? CHECK ?)
  */

  if (results.nb_after_right >= results.nb_before_right*ratioMin
      && (results.nb_after_right > 0 || results.nb_before_right == 0)
      && currentValue < results.max_value
      && results.max_value > 0) {
    results.max_found = true;
    return results;
  }
  return results;
}
int main(int argc, char* argv[]) {

	if (argc < 2 ) {
		printUsage();
		exit(2);
	}
	int samplecount = atoi(argv[1]);
	int readwritedescp[2];
	int processId = 0, exitId = 0, index = 0;
	unsigned long long int start = 0, end = 0;
	double mean_counteroverhead = 0, stddev_counteroverhead = 0,\
	       mean_processoverhead = 0, stddev_processoverhead = 0,\
	       mean_processswitchoverhead = 0, stddev_processswitchoverhead = 0;
		   
	double processOverheadArray[samplecount];
	double processswitchOverheadArray[samplecount];

	mean_counteroverhead = getCounteroverhead(samplecount, &stddev_counteroverhead);

	if (!pipe2(readwritedescp, O_NONBLOCK))
		printf("Pipe created successfully!\n");
	else
		printf("Some problem with pipe creation\n");


	// MEASURE THE PROCESS CREATION TIME
	for ( index = 0; index < samplecount; index++) {
		// start the counter before forking - this will account the process creation time
		start = count();
		if ((processId = fork()) != 0) {
			exitId = wait();
			read(readwritedescp[0], (void*)&end, sizeof(end));
		}
		else {
			// as soon as new process starts executing, stop the timer
			end = count();
			write(readwritedescp[1], (void*)&end, sizeof(end));
			exit(1);
		}
		processOverheadArray[index] = end-start-mean_counteroverhead;
	}

	mean_processoverhead = getMeanStddev(processOverheadArray, samplecount, &stddev_processoverhead);
	printResult(samplecount, mean_processoverhead, stddev_processoverhead, "PROCESS CREATION TIME - cycles");
	printResult(samplecount, getDurationinMicroSec(mean_processoverhead),\
	                         getDurationinMicroSec(stddev_processoverhead),\
							 "PROCESS CREATION TIME - microsec");

	// MEASURE THE CONTEXT SWITCH TIME
	for ( index = 0; index < samplecount; index++) {
		if ((processId = fork()) != 0) {
			// as opposed to process creation time, start the timer just before doing a context switch
			start = count();
			exitId = wait();
			read(readwritedescp[0], (void*)&end, sizeof(end));
		}
		else {
			// stop the counter as soon as the child starts executing
			end = count();
			write(readwritedescp[1], (void*)&end, sizeof(end));
			exit(1);
		}

		processswitchOverheadArray[index] = end-start-mean_counteroverhead;
	}

	mean_processswitchoverhead= getMeanStddev(processswitchOverheadArray, samplecount, &stddev_processswitchoverhead) ;
	printResult(samplecount, mean_processswitchoverhead, stddev_processswitchoverhead, "CONTEXTSWITCH TIME - cycles");
	printResult(samplecount, getDurationinMicroSec(mean_processswitchoverhead),\
	                         getDurationinMicroSec(stddev_processswitchoverhead),\
							 "CONTEXTSWITCH TIME - microsec");

	return 0;
}
Ejemplo n.º 19
0
HRESULT CMpcAudioRenderer::GetAudioDevice(IMMDevice** ppMMDevice)
{
    TRACE(_T("CMpcAudioRenderer::GetAudioDevice\n"));

    CComPtr<IMMDeviceEnumerator> enumerator;
    IMMDeviceCollection* devices = nullptr;
    IPropertyStore* pProps = nullptr;
    HRESULT hr = enumerator.CoCreateInstance(__uuidof(MMDeviceEnumerator));

    if (hr != S_OK) {
        TRACE(_T("CMpcAudioRenderer::GetAudioDevice - failed to create MMDeviceEnumerator!\n"));
        return hr;
    }

    TRACE(_T("CMpcAudioRenderer::GetAudioDevice - Target end point: %s\n"), m_csSound_Device);

    if (GetAvailableAudioDevices(&devices) == S_OK && devices) {
        UINT count(0);
        hr = devices->GetCount(&count);
        if (hr != S_OK) {
            TRACE(_T("CMpcAudioRenderer::GetAudioDevice - devices->GetCount failed: (0x%08x)\n"), hr);
            return hr;
        }

        for (ULONG i = 0 ; i < count ; i++) {
            LPWSTR pwszID = nullptr;
            IMMDevice* endpoint = nullptr;
            hr = devices->Item(i, &endpoint);
            if (hr == S_OK) {
                hr = endpoint->GetId(&pwszID);
                if (hr == S_OK) {
                    if (endpoint->OpenPropertyStore(STGM_READ, &pProps) == S_OK) {

                        PROPVARIANT varName;
                        PropVariantInit(&varName);

                        // Found the configured audio endpoint
                        if ((pProps->GetValue(PKEY_Device_FriendlyName, &varName) == S_OK) && (m_csSound_Device == varName.pwszVal)) {
                            TRACE(_T("CMpcAudioRenderer::GetAudioDevice - devices->GetId OK, num: (%d), pwszVal: %s, pwszID: %s\n"), i, varName.pwszVal, pwszID);
                            enumerator->GetDevice(pwszID, ppMMDevice);
                            SAFE_RELEASE(devices);
                            *(ppMMDevice) = endpoint;
                            CoTaskMemFree(pwszID);
                            pwszID = nullptr;
                            PropVariantClear(&varName);
                            SAFE_RELEASE(pProps);
                            return S_OK;
                        } else {
                            PropVariantClear(&varName);
                            SAFE_RELEASE(pProps);
                            SAFE_RELEASE(endpoint);
                            CoTaskMemFree(pwszID);
                            pwszID = nullptr;
                        }
                    }
                } else {
                    TRACE(_T("CMpcAudioRenderer::GetAudioDevice - devices->GetId failed: (0x%08x)\n"), hr);
                }
            } else {
                TRACE(_T("CMpcAudioRenderer::GetAudioDevice - devices->Item failed: (0x%08x)\n"), hr);
            }

            CoTaskMemFree(pwszID);
            pwszID = nullptr;
        }
    }

    TRACE(_T("CMpcAudioRenderer::GetAudioDevice - Unable to find selected audio device, using the default end point!\n"));
    hr = enumerator->GetDefaultAudioEndpoint(eRender, eConsole, ppMMDevice);

    SAFE_RELEASE(devices);

    return hr;
}
Ejemplo n.º 20
0
Archivo: zzdual.c Proyecto: ozay6367/oz
main()
{
int n,l,e,g,i,j,var,mne,c=1,pivot,k=0,k1=0,me[10],pi[10];
float A[10][10],nb[10],bv[10],max[10],C[10][10];
printf("enter no of variables\n");
scanf("%d",&var);
printf("enter no of constraints of less-equal sign\n");
scanf("%d",&l);
printf("enter no of constraints of equal sign\n");
scanf("%d",&e);
printf("enter no of constraints of greater sign\n");
scanf("%d",&g);
n=l+e+g;
printf("enter the coefficients with left hand side coeff:1st input greater than sign input then rest\n");
for(i=0;i<n;i++)
{
for(j=0;j<=var;j++)
{
scanf("%f",&A[i][j]);
}
}
printf("enter the max/min terms:if you want to input min then input it with -ve sign\n");
for(i=0;i<=var;i++)
{
scanf("%f",&max[i]);
}
for(i=0;i<n;i++)
{
nb[i]=0;
}
for(i=0;i<=var;i++)
{
if(max[i]<=0)
{
printf("%f\n",max[i]);
bv[i]=-max[i];
}
}
for(j=0;j<=var;j++)
{
A[n][j]=bv[j];
}
for(i=0;i<=n;i++)
{
for(j=0;j<=var;j++)
{
A[i][j]=-A[i][j];
}
}
printf("your matrix:\n");
for(i=0;i<=n;i++)
{
for(j=0;j<=var;j++)
{
printf("%f\t",A[i][j]);
}
printf("\n");
}
for(i=0;i<var;i++)
{
    pi[i]=0;
    me[i]=0;
}
do
{
for(i=0;i<=n;i++)
{
for(j=0;j<=var;j++)
{
C[i][j]=0;//inserting 0 in new matrix
}
}
c=count(A,n,var);
printf("c=%d\n",c);
mne=neg(A,n,var);
me[k1++]=mne;
printf("mne=%d\n",mne);
pivot=pivo(A,n,var,mne);
pi[k++]=pivot;
printf("pivot=%d\n",pivot);
for(i=0;i<=n;i++)
{
for(j=0;j<=var;j++)
{
if((i!=mne) || (j!=pivot))
{
C[i][j]=(A[i][j]*A[mne][pivot]-A[i][pivot]*A[mne][j])/A[mne][pivot];//inserting rest of the elements in the c array
}
}
}
for(i=0;i<=n;i++)//inserting elements in c array of pivot column
{
if(i!=mne)
{
 C[i][pivot]=A[i][pivot]*mod(1/A[mne][pivot]);
}
else
{
C[mne][pivot]=1/A[mne][pivot];
}
}
for(j=0;j<=var;j++)//inserting elements in c array of most negative row
{
if(j!=pivot)
{
C[mne][j]=A[mne][j]*(1/A[mne][pivot]);
}
else
{
C[mne][pivot]=1/A[mne][pivot];
}
}
for(i=0;i<=n;i++)
{
for(j=0;j<=var;j++)
{
A[i][j]=C[i][j];
}
}
printf("your matrix in computation stage\n");
for(i=0;i<=n;i++)
{
for(j=0;j<=var;j++)
{
printf("%f\t",C[i][j]);
}
printf("\n");
}
}while(c!=0);
printf("your matrix after computation:\n");
for(i=0;i<=n;i++)
{
for(j=0;j<=var;j++)
{
printf("%f\t",A[i][j]);
}
printf("\n");
}
printf("your optimum values is:%f\n",A[n][var]);
printf("your values of each variables:\n");
    for(i=k;i>0;i--)
    {
        if(pi[i]!=i)
        {
            printf("x%d=%f\n",pi[i]+2,A[me[i]][var]);
        }
        else
        {
            int t=0;
            printf("x%d=%d\n",pi[i]+2,t);
        }
    }
    int x1=0,x2=0;
    printf("x%d=%d\n",x1+1,x2);
}
Ejemplo n.º 21
0
void EnumerationView::updateUi()
{
    auto const identifier = util::StringConverter::toUtf8QString(m_parameter->identifier());
    auto const description = util::StringConverter::toUtf8QString(m_parameter->description());
    auto const number = QVariant(m_parameter->number()).toString();
    auto const access = m_parameter->access().value();
    auto const schema = util::StringConverter::toUtf8QString(m_parameter->schema());

    if (m_view->identifierText->text() != identifier)
        m_view->identifierText->setText(identifier);

    if (m_view->descriptionText->text() != description)
        m_view->descriptionText->setText(description);

    if (m_view->schemaText->text() != schema)
        m_view->schemaText->setText(schema);

    if (m_view->numberText->text() != number)
        m_view->numberText->setText(number);

    auto const count = m_view->valueComboBox->count();
    auto const sequenceCountEquals = m_parameter->size() == count;
    auto sequenceChanged = !sequenceCountEquals;

    if (sequenceCountEquals)
    {
        auto it = m_parameter->begin();
        auto index = 0;
        for( ; index < count; ++index, ++it)
        {
            auto const text = ::util::StringConverter::toUtf8StdString(m_view->valueComboBox->itemText(index));
            if(*it != text)
                break;
        }

        sequenceChanged = !(index == count);
    }

    if (sequenceChanged)
    {
        auto box = m_view->valueComboBox;
        auto const first = m_parameter->begin();
        auto const last = m_parameter->end();
        while(box->count() > 0)
            box->removeItem(0);

        std::for_each(first, last, [&box](std::string const& item)
        {
            auto const text = util::StringConverter::toUtf8QString(item);
            box->addItem(text);
        });
    }

    auto const index = m_parameter->index();
    if (m_view->valueComboBox->currentIndex() != index)
        m_view->valueComboBox->setCurrentIndex(index);

    if (m_view->accessBox->currentIndex() != access)
        m_view->accessBox->setCurrentIndex(access);

    auto const hasStreamIdentifier = m_parameter->hasStreamIdentifier();
    if (m_view->checkUseStreamIdentifier->isChecked() != hasStreamIdentifier)
        m_view->checkUseStreamIdentifier->setChecked(hasStreamIdentifier);

    auto const hasStreamDescriptor = m_parameter->hasStreamDescriptor();
    if (m_view->checkUseStreamDescriptor->isChecked() != hasStreamDescriptor)
        m_view->checkUseStreamDescriptor->setChecked(hasStreamDescriptor);

    if (hasStreamIdentifier)
    {
        auto const streamIdentifier = m_parameter->streamIdentifier();
        if (m_view->streamIdentifierBox->value() != streamIdentifier && m_view->streamIdentifierBox->hasFocus() == false)
            m_view->streamIdentifierBox->setValue(streamIdentifier);
    }
    else
    {
        if (m_view->streamIdentifierBox->value() != -1)
            m_view->streamIdentifierBox->setValue(-1);
    }

    if (hasStreamDescriptor)
    {
        auto const descriptor = m_parameter->streamDescriptor();
        auto const offset = descriptor->offset();
        auto const format = QString::fromStdString(util::StreamFormatConverter::toString(descriptor->format()));

        if (m_view->streamOffsetBox->value() != offset && m_view->streamOffsetBox->hasFocus() == false)
            m_view->streamOffsetBox->setValue(offset);

        if (m_view->streamFormatBox->currentText() != format)
        {
            auto const index = m_view->streamFormatBox->findText(format);
            m_view->streamFormatBox->setCurrentIndex(index);
        }
    }
    else
    {
        if (m_view->streamFormatBox->currentIndex() != 0)
            m_view->streamFormatBox->setCurrentIndex(0);

        if (m_view->streamOffsetBox->value() != 0)
            m_view->streamOffsetBox->setValue(0);
    }

    if (m_parameter->dirtyState().isSet(::gadget::ParameterField::SubscriptionCount))
    {
        auto const subscriptions = m_parameter->subscribers();
        std::unique_ptr<std::stringstream> stream;
        stream.reset( new std::stringstream());
        auto const suffix = subscriptions != 1 ? "subscribers" : "subscriber";
        *stream.get() << "Streaming (" << subscriptions << " " << suffix << ")";

        m_view->streamingGroupBox->setTitle(QString::fromStdString(stream->str()));
    }
}
Ejemplo n.º 22
0
int HistoryManager::rowCount(const QModelIndex&) const {
  return count();
}
Ejemplo n.º 23
0
void UsersList::selectAll( bool select, const QListWidgetItem * skip)
{
   for( int i = 0; i < count(); i++)
      if((item(i)->text() != username) && (skip != item(i)))
         item(i)->setSelected( select);
}
Ejemplo n.º 24
0
void output(Node* t) {
    int n = count(t);
    REP(i, n) {
        cout << get(t, i)->val << " ";
    }
Ejemplo n.º 25
0
QCList::~QCList()
{
#if defined(DEBUG)
    ASSERT( count() == 0 );
#endif
}
Ejemplo n.º 26
0
Node* update(Node* t) {
    t->cnt = 1 + count(t->lch) + count(t->rch);
    t->sum = t->val + sum(t->lch) + sum(t->rch);
    t->min_v = min(t->val, min( min(t->lch), min(t->rch) ));
    return t;
}
Ejemplo n.º 27
0
void TabBar::tabInserted(int index)
{
    Q_UNUSED(index)

    setVisible(!(count() == 1 && m_hideTabBarWithOneTab));
}
Ejemplo n.º 28
0
	size_t Mapper2d::
	UpdateObstacles(index_buffer_t const * add,
									bool force_add,
									index_buffer_t * remove,
									draw_callback * cb)
	{
		size_t count(0);
		m_swipe_hole_buffer.clear();
		m_swipe_repair_buffer.clear();
		
		if (remove) {
			
			// remove former W-obstacles
			index_buffer_t spurious;
			for (index_buffer_t::const_iterator is(remove->begin()); is != remove->end(); ++is) {
				ssize_t const ix0(is->v0);
				ssize_t const iy0(is->v1);
				if ( ! m_travmap->IsWObst(ix0, iy0)) {
					PDEBUG("skip source %zd %zd because not W-obst\n", ix0, iy0);
					spurious.insert(*is);
					continue;
				}
				
				if (m_travmap->IsValid(ix0, iy0)) {
					PDEBUG("wipe source %zd %zd\n", ix0, iy0);
					++count;
					m_travmap->SetFree(ix0, iy0, cb);
				}
				else
					PDEBUG("source %zd %zd is out of bounds\n", ix0, iy0);
			}
			
			// should normally be a no-op
			for (index_buffer_t::const_iterator is(spurious.begin()); is != spurious.end(); ++is)
				remove->erase(*is);
			
			// determine the areas influenced by the former W-obstacles:
			// inner areas are later wiped, outer areas only scanned for
			// already existing W-obstacles
			for (index_buffer_t::const_iterator is(remove->begin()); is != remove->end(); ++is) {
				ssize_t const ix0(is->v0);
				ssize_t const iy0(is->v1);
				for (removemask_t::const_iterator ir(m_removemask.begin());
						 ir != m_removemask.end(); ++ir) {
					ssize_t const tx(ix0 + ir->first.v0);
					ssize_t const ty(iy0 + ir->first.v1);
					if (m_travmap->IsWObst(tx, ty)) {
						PDEBUG("add again target %zd %zd because W-obst\n", tx, ty);
						m_swipe_repair_buffer.insert(index_t(tx, ty));
					}
					else if (ir->second && ( ! m_travmap->IsFree(tx, ty))) {
						PDEBUG("wipe target %zd %zd\n", tx, ty);
						m_swipe_hole_buffer.insert(index_t(tx, ty));
					}
				}
			}
			
			// wipe out the region of influence of each removed W-obstacle
			for (index_buffer_t::const_iterator iw(m_swipe_hole_buffer.begin());
					 iw != m_swipe_hole_buffer.end(); ++iw)
				m_travmap->SetFree(iw->v0, iw->v1, cb);
			count += m_swipe_hole_buffer.size();
			
			// add back all the W-obstacles which have a region of influence
			// that intersects the set of cells that were just wiped (set
			// force add to true, because we did not set these cells to
			// W-obstacle cost)
			for (index_buffer_t::const_iterator ia(m_swipe_repair_buffer.begin());
					 ia != m_swipe_repair_buffer.end(); ++ia)
				count += AddOneObstacle(*ia, true, cb);
		}
		
		// forcing optional, depends on user
		if (add)
			for (index_buffer_t::const_iterator ia(add->begin()); ia != add->end(); ++ia)
				count += AddOneObstacle(*ia, force_add, cb);
		
		return count;
	}
Ejemplo n.º 29
0
int CSMWorld::Data::count (RecordBase::State state) const
{
    return
        count (state, mGlobals) +
        count (state, mGmsts) +
        count (state, mSkills) +
        count (state, mClasses) +
        count (state, mFactions) +
        count (state, mRaces) +
        count (state, mSounds) +
        count (state, mScripts) +
        count (state, mRegions) +
        count (state, mBirthsigns) +
        count (state, mSpells) +
        count (state, mCells) +
        count (state, mEnchantments) +
        count (state, mBodyParts) +
        count (state, mLand) +
        count (state, mLandTextures) +
        count (state, mSoundGens) +
        count (state, mMagicEffects) +
        count (state, mReferenceables) +
        count (state, mPathgrids);
}
Ejemplo n.º 30
0
 const Output* solve( const Input* in, Output* out ) {
   auto counter = CounterPointer(new Counter(in));
   out->result = counter->count();
   return out;
 }