/*
    QMPlay2 is a video and audio player.
    Copyright (C) 2010-2020  Błażej Szczygieł

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <PlaylistWidget.hpp>

#include <QMPlay2Extensions.hpp>
#include <MenuBar.hpp>
#include <Demuxer.hpp>
#include <Reader.hpp>
#include <Main.hpp>

#include <QResizeEvent>
#include <QHeaderView>
#include <QFileInfo>
#include <QMimeData>
#include <QPainter>
#include <QDrag>
#include <QMenu>
#include <QDir>

static inline QStringList getDirEntries(const QString &pth)
{
    return QDir(pth).entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name | QDir::DirsFirst);
}
static inline void prependPath(QStringList &dirEntries, const QString &pth)
{
    for (int i = 0; i < dirEntries.count(); ++i)
        dirEntries[i].prepend(pth);
}

static void entryCreated(const QString &url, int insertChildAt, QStringList &existingEntries)
{
    const QString fileName = Functions::fileName(url);
    if (insertChildAt < 0 || insertChildAt >= existingEntries.count())
        existingEntries.append(fileName);
    else
        existingEntries.insert(insertChildAt, fileName);
}

static inline MenuBar::Playlist *playlistMenu()
{
    return QMPlay2GUI.menuBar->playlist;
}

/* PlaylistItem class */
class PlaylistItem : public QTreeWidgetItem
{
public:
    bool operator <(const QTreeWidgetItem &other) const override
    {
        if (treeWidget() && treeWidget()->sortColumn() == 2)
        {
            return (data(2, Qt::UserRole) < other.data(2, Qt::UserRole));
        }
        return QTreeWidgetItem::operator <(other);
    }
};

/* UpdateEntryThr class */
UpdateEntryThr::UpdateEntryThr(PlaylistWidget &pLW) :
    pendingUpdates(0),
    pLW(pLW),
    timeChanged(false)
{
    qRegisterMetaType<ItemUpdated>("ItemUpdated");
    qRegisterMetaType<QTreeWidgetItem *>("QTreeWidgetItem *");
    connect(this, SIGNAL(finished()), this, SLOT(finished()));
}

void UpdateEntryThr::updateEntry(QTreeWidgetItem *item, const QString &name, double length)
{
    if (!item || !pLW.getChildren(PlaylistWidget::ONLY_NON_GROUPS).contains(item))
        return;
    mutex.lock();
    itemsToUpdate += {item, pLW.getUrl(item), item->data(2, Qt::UserRole).toDouble(), name, length};
    mutex.unlock();
    if (!isRunning())
    {
        ioCtrl.resetAbort();
        start();
    }
}

void UpdateEntryThr::run()
{
    const bool displayOnlyFileName = QMPlay2Core.getSettings().getBool("DisplayOnlyFileName");
    while (!ioCtrl.isAborted())
    {
        mutex.lock();
        if (itemsToUpdate.isEmpty())
        {
            mutex.unlock();
            break;
        }
        ItemToUpdate itu = itemsToUpdate.dequeue();
        mutex.unlock();

        bool updateTitle = true;
        QString url = itu.url;

        ItemUpdated iu;
        iu.item = itu.item;

        if (itu.name.isNull() && itu.length == -2.0)
        {
            Functions::getDataIfHasPluginPrefix(url, &url, &itu.name, &iu.icon, &ioCtrl);
            iu.updateIcon = true;

            IOController<Demuxer> &demuxer = ioCtrl.toRef<Demuxer>();
            if (Demuxer::create(url, demuxer))
            {
                if (!displayOnlyFileName && itu.name.isEmpty())
                    itu.name = demuxer->title();
                itu.length = demuxer->length();
                demuxer.reset();
            }
            else
                updateTitle = false;
        }
        else
        {
            iu.updateIcon = false;
        }

        //Don't update title for network streams if title exists and new title doesn't exists
        if (updateTitle && (displayOnlyFileName || url.startsWith("file://") || !itu.name.isEmpty()))
        {
            if (displayOnlyFileName || itu.name.isEmpty())
                iu.name = Functions::fileName(url, false);
            else
                iu.name = itu.name;
        }

        if (qFuzzyCompare(itu.length, itu.oldLength))
            iu.updateLength = false;
        else
        {
            iu.updateLength = true;
            iu.length = itu.length;
            timeChanged = true;
        }

        pendingUpdates.ref();
        QMetaObject::invokeMethod(this, "updateItem", Q_ARG(ItemUpdated, iu));
    }
}
void UpdateEntryThr::stop()
{
    ioCtrl.abort();
    wait(TERMINATE_TIMEOUT);
    if (isRunning())
    {
        terminate();
        wait(1000);
        ioCtrl.reset();
    }
}

void UpdateEntryThr::updateItem(ItemUpdated iu)
{
    if (iu.updateIcon)
        pLW.setEntryIcon(iu.icon, iu.item);
    if (!iu.name.isNull())
        iu.item->setText(0, iu.name);
    if (iu.updateLength)
    {
        iu.item->setText(2, Functions::timeToStr(iu.length));
        iu.item->setData(2, Qt::UserRole, iu.length);
    }
    if (iu.item == pLW.currentPlaying)
        QMetaObject::invokeMethod(QMPlay2GUI.mainW, "updateWindowTitle", Q_ARG(QString, iu.item->text(0)));
    pendingUpdates.deref();
}
void UpdateEntryThr::finished()
{
    if (timeChanged)
    {
        pLW.refresh(PlaylistWidget::REFRESH_GROUPS_TIME);
        timeChanged = false;
    }
    pLW.modifyMenu();
}

/* AddThr class */
AddThr::AddThr(PlaylistWidget &pLW) :
    pLW(pLW),
    inProgress(false)
{
    connect(this, SIGNAL(finished()), this, SLOT(finished()));
}

void AddThr::setData(const QStringList &_urls, const QStringList &_existingEntries, QTreeWidgetItem *_par, bool _loadList, SYNC _sync)
{
    ioCtrl.resetAbort();

    urls = _urls;
    existingEntries = _existingEntries;
    par = _par;
    loadList = _loadList;
    sync = _sync;

    firstItem = nullptr;
    lastItem = pLW.currentItem();

    pLW.setItemsResizeToContents(false);

    emit pLW.visibleItemsCount(-1);

    if (sync)
    {
        while (par->childCount())
            delete par->child(0);
        pLW.refresh(PlaylistWidget::REFRESH_CURRPLAYING);
    }

    if (!inProgress)
    {
        emit status(true);
        emit QMPlay2Core.busyCursor();
    }

    if (!loadList)
    {
        if (!inProgress)
        {
            pLW.rotation = 0;
            pLW.animationTimer.start(50);
            playlistMenu()->stopLoading->setVisible(true);
            inProgress = true;
        }
        start();
    }
    else
    {
        inProgress = true;
        run();
    }
}
void AddThr::setDataForSync(const QString &pth, QTreeWidgetItem *par, bool notDir)
{
    if (notDir)
        setData({pth}, {}, par, false, FILE_SYNC); //File synchronization needs only one file!
    else
    {
        QStringList dirEntries = getDirEntries(pth);
        prependPath(dirEntries, pth);
        setData(dirEntries, {}, par, false, DIR_SYNC);
    }
}

void AddThr::stop()
{
    if (pLW.addTimer.isActive())
    {
        pLW.addTimer.stop();
        pLW.enqueuedAddData.clear();
    }
    ioCtrl.abort();
    wait(TERMINATE_TIMEOUT);
    if (isRunning())
    {
        terminate();
        wait(1000);
        ioCtrl.reset();
    }
}

void AddThr::changeItemText0(QTreeWidgetItem *tWI, QString name)
{
    if (!tWI->data(0, Qt::UserRole + 2).toBool()) //It can be set in "EntryProperties::accept()"
        tWI->setText(0, name);
    tWI->setData(0, Qt::UserRole + 2, QVariant());
}
void AddThr::modifyItemFlags(QTreeWidgetItem *tWI, int flags)
{
    PlaylistWidget::setEntryFont(tWI, flags);
    tWI->setData(0, Qt::UserRole + 1, flags);
}
void AddThr::deleteTreeWidgetItem(QTreeWidgetItem *tWI)
{
    delete tWI;
}

void AddThr::run()
{
    Functions::DemuxersInfo demuxersInfo;
    for (Module *module : QMPlay2Core.getPluginsInstance())
        for (const Module::Info &mod : module->getModulesInfo())
            if (mod.type == Module::DEMUXER)
                demuxersInfo += {mod.name, mod.icon.isNull() ? module->icon() : mod.icon, mod.extensions};
    add(urls, par, demuxersInfo, existingEntries.isEmpty() ? nullptr : &existingEntries, loadList);
    if (currentThread() == pLW.thread()) //jeżeli funkcja działa w głównym wątku
        finished();
}

bool AddThr::add(const QStringList &urls, QTreeWidgetItem *parent, const Functions::DemuxersInfo &demuxersInfo, QStringList *existingEntries, bool loadList)
{
    const bool displayOnlyFileName = QMPlay2Core.getSettings().getBool("DisplayOnlyFileName");
    QTreeWidgetItem *currentItem = parent;
    QSet<int> playlistIndexesToSkip;
    bool added = false;

    if (!loadList && QMPlay2Core.getSettings().getBool("SkipPlaylistsWithinFiles"))
    {
        // Don't load playlist within other files
        const auto e = Playlist::extensions();
        for (int i = 0; i < urls.size(); ++i)
        {
            const QString ext = Functions::fileExt(urls.at(i)).toLower();
            if (e.contains(ext))
                playlistIndexesToSkip.insert(i);
        }
        if (playlistIndexesToSkip.count() == urls.count())
            playlistIndexesToSkip.clear();
    }

    for (int i = 0; i < urls.size(); ++i)
    {
        if (ioCtrl.isAborted())
            break;

        if (playlistIndexesToSkip.contains(i))
            continue;

        const QString entryName = QMPlay2Core.getNameForUrl(urls.at(i)); // Get the default entry name - it'll be used if doesn't exist in stream

        QString url = Functions::Url(urls.at(i));

        int insertChildAt = -1;
        if (existingEntries)
        {
            //For quick group sync only - find where to place the new item
            const QString newUrl = url.startsWith("file://") ? url.mid(7) : url;
            const QString newFileName = Functions::fileName(newUrl);
            const QString filePath = Functions::filePath(newUrl);
            const bool newIsDir = QFileInfo(newUrl).isDir();
            insertChildAt = existingEntries->count();
            for (int i = 0; i < insertChildAt; ++i)
            {
                const QString fileName = existingEntries->at(i);
                const bool isDir = QFileInfo(filePath + fileName).isDir();
                if ((newIsDir && !isDir) || (newIsDir == isDir && fileName > newFileName))
                {
                    insertChildAt = i;
                    break;
                }
            }
        }

        QString name;
        const Playlist::Entries entries = Playlist::read(url, &name);
        if (!name.isEmpty()) //Loading playlist
        {
            QTreeWidgetItem *playlistParent = currentItem;
            if (loadList) //Loading QMPlay2 playlist on startup
                pLW.clear(); //This can be executed only from GUI thread!
            else
            {
                const QString groupName = Functions::fileName(url, false);
                if (sync != FILE_SYNC)
                    playlistParent = pLW.newGroup(groupName, url, currentItem, insertChildAt, existingEntries); //Adding a new playlist group
                else
                {
                    //Reuse current playlist group
                    QMetaObject::invokeMethod(this, "changeItemText0", Q_ARG(QTreeWidgetItem *, currentItem), Q_ARG(QString, groupName));
                    sync = NO_SYNC;
                }
            }
            QTreeWidgetItem *tmpFirstItem = insertPlaylistEntries(entries, playlistParent, demuxersInfo, insertChildAt, existingEntries);
            if (!firstItem)
                firstItem = tmpFirstItem;
            added = !entries.isEmpty();
            if (loadList)
                break;
        }
        else if (!loadList)
        {
            const QString dUrl = url.startsWith("file://") ? url.mid(7) : QString();
            if (QFileInfo(dUrl).isDir()) //dodawanie podkatalogu
            {
                if (pLW.currPthToSave.isNull())
                    pLW.currPthToSave = dUrl;
                QStringList dirEntries = getDirEntries(dUrl);
                if (!dirEntries.isEmpty())
                {
                    url = Functions::cleanPath(url);
                    QTreeWidgetItem *p = pLW.newGroup(Functions::fileName(url), url, currentItem, insertChildAt, existingEntries);
                    for (int j = dirEntries.size() - 1; j >= 0; j--)
                    {
                        dirEntries[j].prepend(url);
#ifdef Q_OS_WIN
                        dirEntries[j].replace("file://", "file:///");
#endif
                    }
                    if (add(dirEntries, p, demuxersInfo))
                        added = true;
                    else
                    {
                        if (existingEntries)
                            existingEntries->removeOne(p->text(0));
                        QMetaObject::invokeMethod(this, "deleteTreeWidgetItem", Q_ARG(QTreeWidgetItem *, p));
                    }
                }
            }
            else
            {
                bool hasOneEntry = pLW.dontUpdateAfterAdd;
                bool tracksAdded = false;

                Playlist::Entry entry;
                entry.url = url;

                if (!pLW.dontUpdateAfterAdd) //Don't try to get the real address from extension plugin in this case (no needed for tracks)
                    Functions::getDataIfHasPluginPrefix(url, &url, &entry.name, nullptr, &ioCtrl, demuxersInfo);
                IOController<Demuxer> &demuxer = ioCtrl.toRef<Demuxer>();
                Demuxer::FetchTracks fetchTracks(pLW.dontUpdateAfterAdd);
                if (Demuxer::create(url, demuxer, &fetchTracks))
                {
                    if (sync == FILE_SYNC && fetchTracks.tracks.count() <= 1)
                        hasOneEntry = false; //Don't allow adding single file when syncing a file group
                    else if (fetchTracks.tracks.isEmpty())
                    {
                        if (!displayOnlyFileName && entry.name.isEmpty())
                            entry.name = demuxer->title();
                        entry.length = demuxer->length();
                        hasOneEntry = true;
                    }
                    else
                    {
                        QTreeWidgetItem *tmpFirstItem = insertPlaylistEntries(fetchTracks.tracks, currentItem, demuxersInfo, insertChildAt, existingEntries);
                        if (!firstItem)
                            firstItem = tmpFirstItem;
                        hasOneEntry = false;
                        tracksAdded = true;
                    }
                    demuxer.reset();
                }
                else if (!fetchTracks.isOK)
                    hasOneEntry = false; //Don't add entry to list if error occured

                if (sync == FILE_SYNC && (!fetchTracks.isOK || fetchTracks.tracks.count() <= 1))
                {
                     //Change group name to "url" if error or only single file for file sync
                    QString groupName = url;
                    if (groupName.startsWith("file://"))
                        groupName.remove("file://");
                    QMetaObject::invokeMethod(this, "changeItemText0", Q_ARG(QTreeWidgetItem *, currentItem), Q_ARG(QString, groupName));
                }

                if (hasOneEntry)
                {
                    if (entry.name.isEmpty())
                    {
                        if (entryName.isEmpty())
                            entry.name = Functions::fileName(url, false);
                        else
                            entry.name = entryName;
                    }
                    currentItem = pLW.newEntry(entry, currentItem, demuxersInfo, insertChildAt, existingEntries);
                    if (!firstItem)
                        firstItem = currentItem;
                }

                if (hasOneEntry || tracksAdded)
                {
                    if (pLW.currPthToSave.isNull() && QFileInfo(dUrl).isFile())
                        pLW.currPthToSave = Functions::filePath(dUrl);
                    added = true;
                }

                pLW.dontUpdateAfterAdd = false;
            }
        }
    }
    return added;
}
QTreeWidgetItem *AddThr::insertPlaylistEntries(const Playlist::Entries &entries, QTreeWidgetItem *parent, const Functions::DemuxersInfo &demuxersInfo, int insertChildAt, QStringList *existingEntries)
{
    QList<QTreeWidgetItem *> groupList;
    const int queueSize = pLW.queue.size();
    QTreeWidgetItem *firstItem = nullptr;
    for (const Playlist::Entry &entry : entries)
    {
        QTreeWidgetItem *currentItem = nullptr, *tmpParent, *createdItem = nullptr;
        int insertCurrChildAt;
        QStringList *currExistingEntries;
        const int idx = entry.parent - 1;
        if (idx >= 0 && groupList.size() > idx)
        {
            tmpParent = groupList.at(idx);
            insertCurrChildAt = -1;
            currExistingEntries = nullptr;
        }
        else
        {
            tmpParent = parent;
            insertCurrChildAt = insertChildAt;
            currExistingEntries = existingEntries;
        }
        if (entry.GID)
        {
            if (sync != FILE_SYNC)
            {
                createdItem = pLW.newGroup(entry.name, entry.url, tmpParent, insertCurrChildAt, currExistingEntries);
                groupList += createdItem;
            }
            else
            {
                 //Reuse current file group
                QMetaObject::invokeMethod(this, "changeItemText0", Q_ARG(QTreeWidgetItem *, tmpParent), Q_ARG(QString, entry.name));
                groupList += tmpParent;
            }
        }
        else
        {
            currentItem = createdItem = pLW.newEntry(entry, tmpParent, demuxersInfo, insertCurrChildAt, currExistingEntries);
            if (entry.queue) //Rebuild queue
            {
                for (int j = pLW.queue.size(); j <= queueSize + entry.queue - 1; ++j)
                    pLW.queue += nullptr;
                pLW.queue[queueSize + entry.queue - 1] = currentItem;
            }
            if (!firstItem)
                firstItem = currentItem;
        }

        if (createdItem)
        {
            const int entryAdditionalFlags = (entry.flags &~ Playlist::Entry::Selected);
            if (entryAdditionalFlags)
                QMetaObject::invokeMethod(this, "modifyItemFlags", Q_ARG(QTreeWidgetItem *, createdItem), Q_ARG(int, entryAdditionalFlags));
        }

        if (entry.flags & Playlist::Entry::Selected)
            firstItem = entry.GID ? groupList.last() : currentItem;
    }
    return firstItem;
}

void AddThr::finished()
{
    if (pLW.addTimer.isActive())
        return; //Don't finish, because this thread will be started soon again
    if (!pLW.currPthToSave.isNull())
    {
        QMPlay2GUI.setCurrentPth(pLW.currPthToSave);
        pLW.currPthToSave.clear();
    }
    pLW.animationTimer.stop();
    pLW.viewport()->update();
    pLW.setAnimated(false);
    pLW.refresh();
    pLW.setItemsResizeToContents(true);
    if (firstItem && ((pLW.selectAfterAdd && pLW.currentItem() != firstItem && pLW.currentItem() == lastItem) || !pLW.currentItem()))
        pLW.setCurrentItem(firstItem);
    pLW.selectAfterAdd = false;
    pLW.setAnimated(true);
    pLW.processItems();
    emit pLW.returnItem(firstItem);
    urls.clear();
    existingEntries.clear();
    playlistMenu()->stopLoading->setVisible(false);
    if (!pLW.currentPlaying && !pLW.currentPlayingUrl.isEmpty())
    {
        for (QTreeWidgetItem *tWI : pLW.findItems(QString(), Qt::MatchRecursive | Qt::MatchContains))
            if (pLW.getUrl(tWI) == pLW.currentPlayingUrl)
            {
                pLW.setCurrentPlaying(tWI);
                break;
            }
    }
    emit QMPlay2Core.restoreCursor();
    emit status(false);
    inProgress = false;
}

/*PlaylistWidget class*/
PlaylistWidget::PlaylistWidget() :
    addThr(*this),
    updateEntryThr(*this),
    repaintAll(false)
{
    setContextMenuPolicy(Qt::CustomContextMenu);
    setEditTriggers(QAbstractItemView::NoEditTriggers);
    setDragDropMode(QAbstractItemView::InternalMove);
    setAlternatingRowColors(true);
    setSelectionMode(QAbstractItemView::ExtendedSelection);
    setIndentation(12);
    setColumnCount(3);
    setAnimated(true);
    header()->setStretchLastSection(false);
    setHeaderHidden(true);
    header()->setSectionResizeMode(0, QHeaderView::Stretch);
    header()->hideSection(1);
    setItemsResizeToContents(true);
    setIconSize({22, 22});

    currentPlaying = nullptr;
    selectAfterAdd = hasHiddenItems = dontUpdateAfterAdd = false;

    connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(popupContextMenu(const QPoint &)));
    connect(this, SIGNAL(itemSelectionChanged()), this, SLOT(modifyMenu()));
    connect(&animationTimer, SIGNAL(timeout()), this, SLOT(animationUpdate()));
    connect(&addTimer, SIGNAL(timeout()), this, SLOT(addTimerElapsed()));
    connect(&addThr, SIGNAL(status(bool)), this, SIGNAL(addStatus(bool)));
    connect(playlistMenu(), &MenuBar::Playlist::aboutToShow, this, &PlaylistWidget::createExtensionsMenu);
}

QString PlaylistWidget::getUrl(QTreeWidgetItem *tWI) const
{
    if (!tWI)
        tWI = currentItem();
    return tWI ? tWI->data(0, Qt::UserRole).toString() : QString();
}

void PlaylistWidget::setItemsResizeToContents(bool b)
{
    const QHeaderView::ResizeMode rm = b ? QHeaderView::ResizeToContents : QHeaderView::Fixed;
    for (int i = 1; i <= 2; ++i)
        header()->setSectionResizeMode(i, rm);
}

void PlaylistWidget::sortCurrentGroup(int column, Qt::SortOrder sortOrder)
{
    QTreeWidgetItem *item = selectedItems().isEmpty() ? nullptr : currentItem();
    while (item && !isGroup(item))
        item = item->parent();
    if (item)
        item->sortChildren(column, sortOrder);
    else
        sortItems(column, sortOrder);
}

bool PlaylistWidget::add(const QStringList &urls, QTreeWidgetItem *par, const QStringList &existingEntries, bool loadList, bool forceEnqueue)
{
    if (urls.isEmpty())
        return false;
    if (!forceEnqueue && enqueuedAddData.isEmpty() && canModify())
        addThr.setData(urls, existingEntries, par, loadList);
    else
    {
        enqueuedAddData += {urls, existingEntries, par, loadList};
        if (!addTimer.isActive())
            addTimer.start(1);
    }
    return true;
}
bool PlaylistWidget::add(const QStringList &urls, bool atEndOfList)
{
    selectAfterAdd = true;
    return add(urls, atEndOfList ? nullptr : (selectedItems().isEmpty() ? nullptr : currentItem()));
}
void PlaylistWidget::sync(const QString &pth, QTreeWidgetItem *par, bool notDir)
{
    if (canModify())
        addThr.setDataForSync(pth, par, notDir);
}
void PlaylistWidget::quickSync(const QString &pth, QTreeWidgetItem *par, bool recursive, QTreeWidgetItem *&itemToNull)
{
    if (canModify())
    {
        bool mustRefresh = false;
        quickSyncScanDirs(pth, par, mustRefresh, recursive, itemToNull);
        if (mustRefresh && canModify())
        {
            refresh();
            processItems();
        }
    }
}

void PlaylistWidget::setCurrentPlaying(QTreeWidgetItem *tWI)
{
    if (!tWI)
        return;
    currentPlaying = tWI;
    /* Ikona */
    currentPlayingItemIcon = currentPlaying->data(0, Qt::DecorationRole);
    QMPlay2GUI.setTreeWidgetItemIcon(currentPlaying, QMPlay2Core.getIconFromTheme("media-playback-start"), 0, this);
}

void PlaylistWidget::clear()
{
    if (!canModify())
        return;
    queue.clear();
    clearCurrentPlaying();
    QTreeWidget::clear();
}
void PlaylistWidget::clearCurrentPlaying(bool url)
{
    currentPlaying = nullptr;
    if (url)
        currentPlayingUrl.clear();
    currentPlayingItemIcon.clear();
    modifyMenu();
}

QList<QTreeWidgetItem *> PlaylistWidget::topLevelNonGroupsItems() const
{
    QList<QTreeWidgetItem *> items;
    int count = topLevelItemCount();
    for (int i = 0; i < count; i++)
    {
        QTreeWidgetItem *tWI = topLevelItem(i);
        if (!tWI->parent() && !isGroup(tWI))
            items += tWI;
    }
    return items;
}
QList<QUrl> PlaylistWidget::getUrls() const
{
    QList<QUrl> urls;

    QStringList protocolsToAvoid;
    for (Module *module : QMPlay2Core.getPluginsInstance())
        for (const Module::Info &mod : module->getModulesInfo())
            if (mod.type == Module::DEMUXER && !mod.name.contains(' '))
                protocolsToAvoid += mod.name;

    for (QTreeWidgetItem *tWI : selectedItems())
    {
        QString url = getUrl(tWI);
        if (!url.isEmpty() && !url.contains("://{"))
        {
            const int idx = url.indexOf(':');
            if (idx > -1 && !protocolsToAvoid.contains(url.left(idx)))
            {
#ifdef Q_OS_WIN
                if (url.mid(4, 5) != ":////")
                    url.replace("file://", "file:///");
#endif
                urls += url;
            }
        }
    }

    return urls;
}

QTreeWidgetItem *PlaylistWidget::newGroup()
{
    QTreeWidgetItem *parent = selectedItems().isEmpty() ? nullptr : currentItem();
    return newGroup(QString(), QString(), parent, isGroup(parent) ? 0 : -1, nullptr);
}

QList <QTreeWidgetItem * > PlaylistWidget::getChildren(CHILDREN children, const QTreeWidgetItem *parent) const
{
    QList<QTreeWidgetItem *> list;
    if (!parent)
        parent = invisibleRootItem();
    const int count = parent->childCount();
    for (int i = 0; i < count; i++)
    {
        QTreeWidgetItem *tWI = parent->child(i);
        const bool group = isGroup(tWI);
        if
        (
            ((children & ONLY_NON_GROUPS) && !group) ||
            ((children & ONLY_GROUPS)     &&  group)
        ) list += tWI;
        if (group)
            list += getChildren(children, tWI);
    }
    return list;
}

bool PlaylistWidget::canModify(bool all) const
{
    if (addThr.isRunning())
        return false;
    if (all)
    {
        if (updateEntryThr.isRunning() || updateEntryThr.hasPendingUpdates())
            return false;
        switch (QAbstractItemView::state())
        {
            case QAbstractItemView::NoState:
            case QAbstractItemView::AnimatingState:
                return true;
            default:
                return false;
        }
    }
    return true;
}

void PlaylistWidget::enqueue()
{
    for (QTreeWidgetItem *tWI : selectedItems())
    {
        if (isGroup(tWI))
            continue;
        if (queue.contains(tWI))
        {
            tWI->setText(1, QString());
            queue.removeOne(tWI);
        }
        else
            queue += tWI;
    }
    refresh(REFRESH_QUEUE);
}
void PlaylistWidget::refresh(REFRESH Refresh)
{
    const QList<QTreeWidgetItem *> items = getChildren(ONLY_NON_GROUPS);
    if (Refresh & REFRESH_QUEUE)
    {
        for (int i = 0; i < queue.size(); i++)
        {
            if (!items.contains(queue.at(i)))
                queue.removeAt(i--);
            else
                queue.at(i)->setText(1, QString::number(i + 1));
        }
        queue.size() ? header()->showSection(1) : header()->hideSection(1);
    }
    if (Refresh & REFRESH_GROUPS_TIME)
    {
        const QList<QTreeWidgetItem *> groups = getChildren(ONLY_GROUPS);
        for (int i = groups.size() - 1; i >= 0; i--)
        {
            double length = 0.0;
            for (QTreeWidgetItem *tWI : getChildren(ALL_CHILDREN, groups.at(i)))
            {
                if (tWI->parent() != groups.at(i))
                    continue;
                const double l = tWI->data(2, Qt::UserRole).toDouble();
                if (l > 0.0)
                    length += l;
            }
            const bool hasLength = !qFuzzyIsNull(length);
            groups.at(i)->setText(2, hasLength ? Functions::timeToStr(length) : QString());
            groups.at(i)->setData(2, Qt::UserRole, hasLength ? length : QVariant());
        }
    }
    if ((Refresh & REFRESH_CURRPLAYING) && !items.contains(currentPlaying))
        clearCurrentPlaying(false);
}

void PlaylistWidget::processItems(QList<QTreeWidgetItem *> *itemsToShow, bool hideGroups)
{
    int count = 0;
    hasHiddenItems = false;
    for (QTreeWidgetItem *tWI : getChildren(PlaylistWidget::ONLY_NON_GROUPS))
    {
        if (itemsToShow)
        {
            const int idx = itemsToShow->indexOf(tWI);
            tWI->setHidden(idx < 0);
            if (idx > -1)
                itemsToShow->removeAt(idx);
        }
        if (tWI->isHidden())
            hasHiddenItems = true;
        else
            count++;
    }
    emit visibleItemsCount(count);

    if (!itemsToShow)
        return;

    // Hide empty groups which doesn't exist in "itemsToShow" list
    const QList<QTreeWidgetItem *> groups = getChildren(ONLY_GROUPS);
    for (int i = groups.size() - 1; i >= 0; i--)
    {
        QTreeWidgetItem *group = groups.at(i);
        if (hideGroups && !itemsToShow->contains(group))
        {
            bool hasVisibleItems = false;
            for (QTreeWidgetItem *tWI : getChildren(ALL_CHILDREN, group))
            {
                if (!tWI->isHidden())
                {
                    hasVisibleItems = true;
                    break;
                }
            }
            group->setHidden(!hasVisibleItems);
        }
        else
        {
            group->setHidden(false);
        }
    }
}

bool PlaylistWidget::isAlwaysSynced(QTreeWidgetItem *tWI, bool parentOnly)
{
    if (QTreeWidgetItem *item = ((parentOnly && tWI) ? tWI->parent() : tWI))
    {
        do
        {
            if (PlaylistWidget::getFlags(item) & Playlist::Entry::AlwaysSync)
                return true;
        } while ((item = item->parent()));
    }
    return false;
}

void PlaylistWidget::setEntryFont(QTreeWidgetItem *tWI, const int flags)
{
    QFont font = tWI->font(0);
    font.setBold(flags & Playlist::Entry::Locked);
    font.setStrikeOut(flags & Playlist::Entry::Skip);
    font.setItalic(flags & Playlist::Entry::StopAfter);
    tWI->setFont(0, font);
}

QTreeWidgetItem *PlaylistWidget::newGroup(const QString &name, const QString &url, QTreeWidgetItem *parent, int insertChildAt, QStringList *existingEntries)
{
    QTreeWidgetItem *tWI = new PlaylistItem;

    tWI->setFlags(tWI->flags() | Qt::ItemIsEditable);
    QMPlay2GUI.setTreeWidgetItemIcon(tWI, url.isEmpty() ? *QMPlay2GUI.groupIcon : *QMPlay2GUI.folderIcon, 0, this);
    tWI->setText(0, name);
    tWI->setData(0, Qt::UserRole, url);

    if (existingEntries)
        entryCreated(url, insertChildAt, *existingEntries);

    QMetaObject::invokeMethod(this, "insertItem", Q_ARG(QTreeWidgetItem *, tWI), Q_ARG(QTreeWidgetItem *, parent), Q_ARG(int, insertChildAt));
    return tWI;
}
QTreeWidgetItem *PlaylistWidget::newEntry(const Playlist::Entry &entry, QTreeWidgetItem *parent, const Functions::DemuxersInfo &demuxersInfo, int insertChildAt, QStringList *existingEntries)
{
    QTreeWidgetItem *tWI = new PlaylistItem;

    QIcon icon;
    Functions::getDataIfHasPluginPrefix(entry.url, nullptr, nullptr, &icon, nullptr, demuxersInfo);
    setEntryIcon(icon, tWI);

    tWI->setFlags(tWI->flags() &~ Qt::ItemIsDropEnabled);
    tWI->setText(0, entry.name);
    tWI->setData(0, Qt::UserRole, entry.url);
    tWI->setText(2, Functions::timeToStr(entry.length));
    tWI->setData(2, Qt::UserRole, entry.length);

    if (existingEntries)
        entryCreated(entry.url, insertChildAt, *existingEntries);

    QMetaObject::invokeMethod(this, "insertItem", Q_ARG(QTreeWidgetItem *, tWI), Q_ARG(QTreeWidgetItem *, parent), Q_ARG(int, insertChildAt));
    return tWI;
}

void PlaylistWidget::setEntryIcon(const QIcon &icon, QTreeWidgetItem *tWI)
{
    if (icon.isNull())
    {
        if (tWI == currentPlaying)
            currentPlayingItemIcon = *QMPlay2GUI.mediaIcon;
        else
            QMPlay2GUI.setTreeWidgetItemIcon(tWI, *QMPlay2GUI.mediaIcon, 0, this);
    }
    else
    {
        QMetaObject::invokeMethod(this, "setItemIcon", Q_ARG(QTreeWidgetItem *, (tWI == currentPlaying) ? nullptr : tWI), Q_ARG(QIcon, icon));
    }
}

void PlaylistWidget::quickSyncScanDirs(const QString &pth, QTreeWidgetItem *par, bool &mustRefresh, bool recursive, QTreeWidgetItem *&itemToNull)
{
    QStringList dirEntries = getDirEntries(pth);
    QStringList existingEntries;

    for (int i = par->childCount() - 1; i >= 0; --i)
    {
        QTreeWidgetItem *item = par->child(i);

        const QString itemFileName = Functions::fileName(item->data(0, Qt::UserRole).toString());
        const bool isGroup = PlaylistWidget::isGroup(item);
        const int urlIdx = dirEntries.indexOf(itemFileName);
        QString fullPth = urlIdx > -1 ? pth + dirEntries.at(urlIdx) : QString();

        if (urlIdx > -1 && isGroup == QFileInfo(fullPth).isDir())
        {
            existingEntries.prepend(itemFileName);
            dirEntries.removeAt(urlIdx);
            if (isGroup && recursive)
            {
                if (!fullPth.endsWith('/'))
                    fullPth.append('/');
                quickSyncScanDirs(fullPth, item, mustRefresh, recursive, itemToNull);
            }
        }
        else
        {
            mustRefresh = true;
            if (itemToNull == item)
                itemToNull = nullptr;
            delete item;
        }
    }

    if (!dirEntries.isEmpty())
    {
        prependPath(dirEntries, pth);
        add(dirEntries, par, existingEntries, false, true);
        mustRefresh = false;
    }
}

void PlaylistWidget::createExtensionsMenu()
{
    QTreeWidgetItem *currItem = currentItem();
    const QString entryUrl = getUrl();
    if (!currItem || entryUrl.isEmpty())
        return;

    QMenu *extensions = playlistMenu()->extensions;
    extensions->clear();

    const QString entryName = currItem->text(0);
    const double entryLength = currItem->data(2, Qt::UserRole).toDouble();

    QString addressPrefixName, url, param;
    const bool splitFlag = Functions::splitPrefixAndUrlIfHasPluginPrefix(entryUrl, &addressPrefixName, &url, &param);
    for (QMPlay2Extensions *QMPlay2Ext : QMPlay2Extensions::QMPlay2ExtensionsList())
    {
        QVector<QAction *> actions;
        if (splitFlag)
            actions = QMPlay2Ext->getActions(entryName, entryLength, url, addressPrefixName, param);
        else
            actions = QMPlay2Ext->getActions(entryName, entryLength, entryUrl);
        for (QAction *act : asConst(actions))
        {
            act->setParent(extensions);
            extensions->addAction(act);
        }
    }

    extensions->setEnabled(!extensions->isEmpty());
}

void PlaylistWidget::mouseMoveEvent(QMouseEvent *e)
{
    const bool modifier = (e->modifiers() == Qt::MetaModifier) || (e->modifiers() == Qt::AltModifier);
    if ((e->buttons() & Qt::MidButton) || ((e->buttons() & Qt::LeftButton) && modifier))
    {
        const QList<QUrl> urls = getUrls();
        if (!urls.isEmpty())
        {
            QMimeData *mimeData = new QMimeData;
            mimeData->setUrls(urls);

            QDrag *drag = new QDrag(this);
            drag->setMimeData(mimeData);

            QPixmap pix;
            QTreeWidgetItem *currI = currentItem();
            if (currI && currI != currentPlaying)
                pix = Functions::getPixmapFromIcon(currI->icon(0), iconSize(), this);
            if (pix.isNull())
                pix = Functions::getPixmapFromIcon(*QMPlay2GUI.mediaIcon, iconSize(), this);
            drag->setPixmap(pix);

            drag->exec(Qt::CopyAction | Qt::MoveAction | Qt::LinkAction, Qt::CopyAction);
        }
    }
    else if (canModify(false) && !hasHiddenItems)
    {
        internalDrag = false;
        QTreeWidget::mouseMoveEvent(e);
        if (internalDrag)
            refresh();
    }
}
void PlaylistWidget::dragEnterEvent(QDragEnterEvent *e)
{
    if (addThr.isRunning() || !e)
        return;
    if (Functions::chkMimeData(e->mimeData()))
        e->accept();
    else
    {
        QTreeWidget::dragEnterEvent(e);
        internalDrag = true;
    }
}
void PlaylistWidget::dragMoveEvent(QDragMoveEvent *e)
{
    if (!e)
        return;
    if (e->source() == this)
        QTreeWidget::dragMoveEvent(e);
    else
        setCurrentItem(itemAt(e->pos()));
}
void PlaylistWidget::dropEvent(QDropEvent *e)
{
    if (!e)
        return;
    if (e->source() == this)
    {
        QTreeWidgetItem *cI = currentItem();
        setItemsResizeToContents(false);
        QTreeWidget::dropEvent(e);
        setItemsResizeToContents(true);
        setCurrentItem(cI);
    }
    else if (e->mimeData())
    {
        selectAfterAdd = true;
        add(Functions::getUrlsFromMimeData(e->mimeData()), itemAt(e->pos()));
        e->accept();
    }
}
void PlaylistWidget::paintEvent(QPaintEvent *e)
{
    QTreeWidget::paintEvent(e);
    if (!animationTimer.isActive())
        return;

    QPainter p(viewport());
    p.setRenderHint(QPainter::Antialiasing);

    QRect arcRect = getArcRect(48);
    p.drawArc(arcRect, rotation * 16, 120 * 16);
    p.drawArc(arcRect, (rotation + 180) * 16, 120 * 16);
}
void PlaylistWidget::scrollContentsBy(int dx, int dy)
{
    if (dx || dy)
        repaintAll = true;
    QAbstractScrollArea::scrollContentsBy(dx, dy);
}

QRect PlaylistWidget::getArcRect(int size)
{
    return QRect(QPoint(width() / 2 - size / 2, height() / 2 - size / 2), QSize(size, size));
}

void PlaylistWidget::insertItem(QTreeWidgetItem *tWI, QTreeWidgetItem *parent, int insertChildAt)
{
    QTreeWidgetItem *childItem = parent;
    if (parent && !isGroup(parent))
        parent = parent->parent();
    if (insertChildAt < 0 && childItem && childItem->parent() == parent)
    {
        if (parent)
            parent->insertChild(parent->indexOfChild(childItem) + 1, tWI);
        else
            insertTopLevelItem(indexOfTopLevelItem(childItem) + 1, tWI);
    }
    else if (parent)
    {
        if (insertChildAt < 0)
            parent->addChild(tWI);
        else
            parent->insertChild(insertChildAt, tWI);
    }
    else
    {
        addTopLevelItem(tWI);
    }
}
void PlaylistWidget::popupContextMenu(const QPoint &p)
{
    playlistMenu()->popup(mapToGlobal(p));
}
void PlaylistWidget::setItemIcon(QTreeWidgetItem *tWI, const QIcon &icon)
{
    if (tWI)
        QMPlay2GUI.setTreeWidgetItemIcon(tWI, icon, 0, this);
    else
        currentPlayingItemIcon = icon;
}
void PlaylistWidget::animationUpdate()
{
    rotation -= 6;
    if (!repaintAll)
        viewport()->update(getArcRect(50));
    else
    {
        viewport()->update();
        repaintAll = false;
    }
}
void PlaylistWidget::addTimerElapsed()
{
    if (canModify() && !enqueuedAddData.isEmpty())
    {
        const AddData addData = enqueuedAddData.dequeue();
        addThr.setData(addData.urls, addData.existingEntries, addData.par, addData.loadList);
    }
    if (enqueuedAddData.isEmpty())
        addTimer.stop();
}

void PlaylistWidget::modifyMenu()
{
    const QString entryUrl = getUrl();

    QTreeWidgetItem *currItem = currentItem();

    const bool isLocked = (getFlags(currItem) & Playlist::Entry::Locked);
    const bool isItemGroup = isGroup(currItem);
    const bool syncVisible = (isItemGroup && !entryUrl.isEmpty());

    playlistMenu()->saveGroup->setVisible(isItemGroup);
    playlistMenu()->lock->setText(isLocked ? tr("Un&lock") : tr("&Lock"));
    playlistMenu()->lock->setVisible(currItem);
    playlistMenu()->alwaysSync->setChecked(isItemGroup && isAlwaysSynced(currItem));
    playlistMenu()->alwaysSync->setVisible(isItemGroup);
    playlistMenu()->alwaysSync->setEnabled(isItemGroup && !isAlwaysSynced(currItem, true));
    playlistMenu()->sync->setVisible(syncVisible);
    playlistMenu()->quickSync->setVisible(syncVisible && QFileInfo(QString(entryUrl).remove("file://")).isDir());
    playlistMenu()->renameGroup->setVisible(isItemGroup);
    playlistMenu()->entryProperties->setVisible(currItem);
    playlistMenu()->queue->setVisible(currItem && !isItemGroup);
    playlistMenu()->skip->setVisible(currItem && !isItemGroup);
    playlistMenu()->stopAfter->setVisible(currItem && !isItemGroup);
    playlistMenu()->goToPlayback->setVisible(currentPlaying);
    playlistMenu()->copy->setVisible(selectedItems().count());
}

{'repo_name': 'zaps166/QMPlay2', 'stars': '218', 'repo_language': 'C++', 'file_name': 'CMakeLists.txt', 'mime_type': 'text/plain', 'hash': -1556218311814566360, 'source_dataset': 'data'}


module github.com/tj/triage

go 1.13

require (
	github.com/AstromechZA/terminfo v0.0.0-20170409122644-e59d11a175fb
	github.com/aybabtme/rgbterm v0.0.0-20170906152045-cc83f3b3ce59
	github.com/dustin/go-humanize v1.0.0
	github.com/google/go-github/v28 v28.1.1
	github.com/kr/text v0.1.0
	github.com/kyokomi/emoji v2.1.0+incompatible
	github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4
	github.com/tj/go-config v1.3.0
	github.com/tj/go-css v0.0.0-20191108133013-220a796d1705
	github.com/tj/go-tea v0.2.0
	github.com/tj/go-termd v0.0.1
	github.com/tj/go-terminput v1.0.0
	golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be
)

{'repo_name': 'tj/triage', 'stars': '381', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': 5753591318836718202, 'source_dataset': 'data'}


# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-27 02:29
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('topics', '0035_auto_20170327_0205'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='curriculumarea',
            name='parent',
        ),
        migrations.AddField(
            model_name='curriculumarea',
            name='prerequisite_lessons',
            field=models.ManyToManyField(related_name='_curriculumarea_prerequisite_lessons_+', to='topics.CurriculumArea'),
        ),
    ]

{'repo_name': 'uccser/cs-unplugged', 'stars': '146', 'repo_language': 'Python', 'file_name': 'django-debug-toolbar.txt', 'mime_type': 'text/plain', 'hash': 8538117392911164377, 'source_dataset': 'data'}


/*
 * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package java.util.stream;

import java.util.DoubleSummaryStatistics;
import java.util.Objects;
import java.util.OptionalDouble;
import java.util.PrimitiveIterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.DoubleBinaryOperator;
import java.util.function.DoubleConsumer;
import java.util.function.DoubleFunction;
import java.util.function.DoublePredicate;
import java.util.function.DoubleToIntFunction;
import java.util.function.DoubleToLongFunction;
import java.util.function.DoubleUnaryOperator;
import java.util.function.IntFunction;
import java.util.function.ObjDoubleConsumer;
import java.util.function.Supplier;

/**
 * Abstract base class for an intermediate pipeline stage or pipeline source
 * stage implementing whose elements are of type {@code double}.
 *
 * @param <E_IN> type of elements in the upstream source
 *
 * @since 1.8
 */
abstract class DoublePipeline<E_IN>
        extends AbstractPipeline<E_IN, Double, DoubleStream>
        implements DoubleStream {

    /**
     * Constructor for the head of a stream pipeline.
     *
     * @param source {@code Supplier<Spliterator>} describing the stream source
     * @param sourceFlags the source flags for the stream source, described in
     * {@link StreamOpFlag}
     */
    DoublePipeline(Supplier<? extends Spliterator<Double>> source,
                   int sourceFlags, boolean parallel) {
        super(source, sourceFlags, parallel);
    }

    /**
     * Constructor for the head of a stream pipeline.
     *
     * @param source {@code Spliterator} describing the stream source
     * @param sourceFlags the source flags for the stream source, described in
     * {@link StreamOpFlag}
     */
    DoublePipeline(Spliterator<Double> source,
                   int sourceFlags, boolean parallel) {
        super(source, sourceFlags, parallel);
    }

    /**
     * Constructor for appending an intermediate operation onto an existing
     * pipeline.
     *
     * @param upstream the upstream element source.
     * @param opFlags the operation flags
     */
    DoublePipeline(AbstractPipeline<?, E_IN, ?> upstream, int opFlags) {
        super(upstream, opFlags);
    }

    /**
     * Adapt a {@code Sink<Double> to a {@code DoubleConsumer}, ideally simply
     * by casting.
     */
    private static DoubleConsumer adapt(Sink<Double> sink) {
        if (sink instanceof DoubleConsumer) {
            return (DoubleConsumer) sink;
        } else {
            if (Tripwire.ENABLED)
                Tripwire.trip(AbstractPipeline.class,
                              "using DoubleStream.adapt(Sink<Double> s)");
            return sink::accept;
        }
    }

    /**
     * Adapt a {@code Spliterator<Double>} to a {@code Spliterator.OfDouble}.
     *
     * @implNote
     * The implementation attempts to cast to a Spliterator.OfDouble, and throws
     * an exception if this cast is not possible.
     */
    private static Spliterator.OfDouble adapt(Spliterator<Double> s) {
        if (s instanceof Spliterator.OfDouble) {
            return (Spliterator.OfDouble) s;
        } else {
            if (Tripwire.ENABLED)
                Tripwire.trip(AbstractPipeline.class,
                              "using DoubleStream.adapt(Spliterator<Double> s)");
            throw new UnsupportedOperationException("DoubleStream.adapt(Spliterator<Double> s)");
        }
    }

    // Shape-specific methods

    @Override
    final StreamShape getOutputShape() {
        return StreamShape.DOUBLE_VALUE;
    }

    @Override
    final <P_IN> Node<Double> evaluateToNode(PipelineHelper<Double> helper,
                                             Spliterator<P_IN> spliterator,
                                             boolean flattenTree,
                                             IntFunction<Double[]> generator) {
        return Nodes.collectDouble(helper, spliterator, flattenTree);
    }

    @Override
    final <P_IN> Spliterator<Double> wrap(PipelineHelper<Double> ph,
                                          Supplier<Spliterator<P_IN>> supplier,
                                          boolean isParallel) {
        return new StreamSpliterators.DoubleWrappingSpliterator<>(ph, supplier, isParallel);
    }

    @Override
    @SuppressWarnings("unchecked")
    final Spliterator.OfDouble lazySpliterator(Supplier<? extends Spliterator<Double>> supplier) {
        return new StreamSpliterators.DelegatingSpliterator.OfDouble((Supplier<Spliterator.OfDouble>) supplier);
    }

    @Override
    final void forEachWithCancel(Spliterator<Double> spliterator, Sink<Double> sink) {
        Spliterator.OfDouble spl = adapt(spliterator);
        DoubleConsumer adaptedSink = adapt(sink);
        do { } while (!sink.cancellationRequested() && spl.tryAdvance(adaptedSink));
    }

    @Override
    final  Node.Builder<Double> makeNodeBuilder(long exactSizeIfKnown, IntFunction<Double[]> generator) {
        return Nodes.doubleBuilder(exactSizeIfKnown);
    }

    // DoubleStream

    @Override
    public final PrimitiveIterator.OfDouble iterator() {
        return Spliterators.iterator(spliterator());
    }

    @Override
    public final Spliterator.OfDouble spliterator() {
        return adapt(super.spliterator());
    }

    // Stateless intermediate ops from DoubleStream

    @Override
    public final Stream<Double> boxed() {
        return mapToObj(Double::valueOf);
    }

    @Override
    public final DoubleStream map(DoubleUnaryOperator mapper) {
        Objects.requireNonNull(mapper);
        return new StatelessOp<Double>(this, StreamShape.DOUBLE_VALUE,
                                       StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
            @Override
            Sink<Double> opWrapSink(int flags, Sink<Double> sink) {
                return new Sink.ChainedDouble<Double>(sink) {
                    @Override
                    public void accept(double t) {
                        downstream.accept(mapper.applyAsDouble(t));
                    }
                };
            }
        };
    }

    @Override
    public final  Stream mapToObj(DoubleFunction<? extends U> mapper) {
        Objects.requireNonNull(mapper);
        return new ReferencePipeline.StatelessOp<Double, U>(this, StreamShape.DOUBLE_VALUE,
                                                            StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
            @Override
            Sink<Double> opWrapSink(int flags, Sink sink) {
                return new Sink.ChainedDouble(sink) {
                    @Override
                    public void accept(double t) {
                        downstream.accept(mapper.apply(t));
                    }
                };
            }
        };
    }

    @Override
    public final IntStream mapToInt(DoubleToIntFunction mapper) {
        Objects.requireNonNull(mapper);
        return new IntPipeline.StatelessOp<Double>(this, StreamShape.DOUBLE_VALUE,
                                                   StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
            @Override
            Sink<Double> opWrapSink(int flags, Sink<Integer> sink) {
                return new Sink.ChainedDouble<Integer>(sink) {
                    @Override
                    public void accept(double t) {
                        downstream.accept(mapper.applyAsInt(t));
                    }
                };
            }
        };
    }

    @Override
    public final LongStream mapToLong(DoubleToLongFunction mapper) {
        Objects.requireNonNull(mapper);
        return new LongPipeline.StatelessOp<Double>(this, StreamShape.DOUBLE_VALUE,
                                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
            @Override
            Sink<Double> opWrapSink(int flags, Sink<Long> sink) {
                return new Sink.ChainedDouble<Long>(sink) {
                    @Override
                    public void accept(double t) {
                        downstream.accept(mapper.applyAsLong(t));
                    }
                };
            }
        };
    }

    @Override
    public final DoubleStream flatMap(DoubleFunction<? extends DoubleStream> mapper) {
        Objects.requireNonNull(mapper);
        return new StatelessOp<Double>(this, StreamShape.DOUBLE_VALUE,
                                        StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
            @Override
            Sink<Double> opWrapSink(int flags, Sink<Double> sink) {
                return new Sink.ChainedDouble<Double>(sink) {
                    // true if cancellationRequested() has been called
                    boolean cancellationRequestedCalled;

                    // cache the consumer to avoid creation on every accepted element
                    DoubleConsumer downstreamAsDouble = downstream::accept;

                    @Override
                    public void begin(long size) {
                        downstream.begin(-1);
                    }

                    @Override
                    public void accept(double t) {
                        try (DoubleStream result = mapper.apply(t)) {
                            if (result != null) {
                                if (!cancellationRequestedCalled) {
                                    result.sequential().forEach(downstreamAsDouble);
                                }
                                else {
                                    Spliterator.OfDouble s = result.sequential().spliterator();
                                    do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsDouble));
                                }
                            }
                        }
                    }

                    @Override
                    public boolean cancellationRequested() {
                        // If this method is called then an operation within the stream
                        // pipeline is short-circuiting (see AbstractPipeline.copyInto).
                        // Note that we cannot differentiate between an upstream or
                        // downstream operation
                        cancellationRequestedCalled = true;
                        return downstream.cancellationRequested();
                    }
                };
            }
        };
    }

    @Override
    public DoubleStream unordered() {
        if (!isOrdered())
            return this;
        return new StatelessOp<Double>(this, StreamShape.DOUBLE_VALUE, StreamOpFlag.NOT_ORDERED) {
            @Override
            Sink<Double> opWrapSink(int flags, Sink<Double> sink) {
                return sink;
            }
        };
    }

    @Override
    public final DoubleStream filter(DoublePredicate predicate) {
        Objects.requireNonNull(predicate);
        return new StatelessOp<Double>(this, StreamShape.DOUBLE_VALUE,
                                       StreamOpFlag.NOT_SIZED) {
            @Override
            Sink<Double> opWrapSink(int flags, Sink<Double> sink) {
                return new Sink.ChainedDouble<Double>(sink) {
                    @Override
                    public void begin(long size) {
                        downstream.begin(-1);
                    }

                    @Override
                    public void accept(double t) {
                        if (predicate.test(t))
                            downstream.accept(t);
                    }
                };
            }
        };
    }

    @Override
    public final DoubleStream peek(DoubleConsumer action) {
        Objects.requireNonNull(action);
        return new StatelessOp<Double>(this, StreamShape.DOUBLE_VALUE,
                                       0) {
            @Override
            Sink<Double> opWrapSink(int flags, Sink<Double> sink) {
                return new Sink.ChainedDouble<Double>(sink) {
                    @Override
                    public void accept(double t) {
                        action.accept(t);
                        downstream.accept(t);
                    }
                };
            }
        };
    }

    // Stateful intermediate ops from DoubleStream

    @Override
    public final DoubleStream limit(long maxSize) {
        if (maxSize < 0)
            throw new IllegalArgumentException(Long.toString(maxSize));
        return SliceOps.makeDouble(this, (long) 0, maxSize);
    }

    @Override
    public final DoubleStream skip(long n) {
        if (n < 0)
            throw new IllegalArgumentException(Long.toString(n));
        if (n == 0)
            return this;
        else {
            long limit = -1;
            return SliceOps.makeDouble(this, n, limit);
        }
    }

    @Override
    public final DoubleStream sorted() {
        return SortedOps.makeDouble(this);
    }

    @Override
    public final DoubleStream distinct() {
        // While functional and quick to implement, this approach is not very efficient.
        // An efficient version requires a double-specific map/set implementation.
        return boxed().distinct().mapToDouble(i -> (double) i);
    }

    // Terminal ops from DoubleStream

    @Override
    public void forEach(DoubleConsumer consumer) {
        evaluate(ForEachOps.makeDouble(consumer, false));
    }

    @Override
    public void forEachOrdered(DoubleConsumer consumer) {
        evaluate(ForEachOps.makeDouble(consumer, true));
    }

    @Override
    public final double sum() {
        /*
         * In the arrays allocated for the collect operation, index 0
         * holds the high-order bits of the running sum, index 1 holds
         * the low-order bits of the sum computed via compensated
         * summation, and index 2 holds the simple sum used to compute
         * the proper result if the stream contains infinite values of
         * the same sign.
         */
        double[] summation = collect(() -> new double[3],
                               (ll, d) -> {
                                   Collectors.sumWithCompensation(ll, d);
                                   ll[2] += d;
                               },
                               (ll, rr) -> {
                                   Collectors.sumWithCompensation(ll, rr[0]);
                                   Collectors.sumWithCompensation(ll, rr[1]);
                                   ll[2] += rr[2];
                               });

        return Collectors.computeFinalSum(summation);
    }

    @Override
    public final OptionalDouble min() {
        return reduce(Math::min);
    }

    @Override
    public final OptionalDouble max() {
        return reduce(Math::max);
    }

    /**
     * {@inheritDoc}
     *
     * @implNote The {@code double} format can represent all
     * consecutive integers in the range -253 to
     * 253. If the pipeline has more than 253
     * values, the divisor in the average computation will saturate at
     * 253, leading to additional numerical errors.
     */
    @Override
    public final OptionalDouble average() {
        /*
         * In the arrays allocated for the collect operation, index 0
         * holds the high-order bits of the running sum, index 1 holds
         * the low-order bits of the sum computed via compensated
         * summation, index 2 holds the number of values seen, index 3
         * holds the simple sum.
         */
        double[] avg = collect(() -> new double[4],
                               (ll, d) -> {
                                   ll[2]++;
                                   Collectors.sumWithCompensation(ll, d);
                                   ll[3] += d;
                               },
                               (ll, rr) -> {
                                   Collectors.sumWithCompensation(ll, rr[0]);
                                   Collectors.sumWithCompensation(ll, rr[1]);
                                   ll[2] += rr[2];
                                   ll[3] += rr[3];
                               });
        return avg[2] > 0
            ? OptionalDouble.of(Collectors.computeFinalSum(avg) / avg[2])
            : OptionalDouble.empty();
    }

    @Override
    public final long count() {
        return mapToLong(e -> 1L).sum();
    }

    @Override
    public final DoubleSummaryStatistics summaryStatistics() {
        return collect(DoubleSummaryStatistics::new, DoubleSummaryStatistics::accept,
                       DoubleSummaryStatistics::combine);
    }

    @Override
    public final double reduce(double identity, DoubleBinaryOperator op) {
        return evaluate(ReduceOps.makeDouble(identity, op));
    }

    @Override
    public final OptionalDouble reduce(DoubleBinaryOperator op) {
        return evaluate(ReduceOps.makeDouble(op));
    }

    @Override
    public final <R> R collect(Supplier<R> supplier,
                               ObjDoubleConsumer<R> accumulator,
                               BiConsumer<R, R> combiner) {
        Objects.requireNonNull(combiner);
        BinaryOperator<R> operator = (left, right) -> {
            combiner.accept(left, right);
            return left;
        };
        return evaluate(ReduceOps.makeDouble(supplier, accumulator, operator));
    }

    @Override
    public final boolean anyMatch(DoublePredicate predicate) {
        return evaluate(MatchOps.makeDouble(predicate, MatchOps.MatchKind.ANY));
    }

    @Override
    public final boolean allMatch(DoublePredicate predicate) {
        return evaluate(MatchOps.makeDouble(predicate, MatchOps.MatchKind.ALL));
    }

    @Override
    public final boolean noneMatch(DoublePredicate predicate) {
        return evaluate(MatchOps.makeDouble(predicate, MatchOps.MatchKind.NONE));
    }

    @Override
    public final OptionalDouble findFirst() {
        return evaluate(FindOps.makeDouble(true));
    }

    @Override
    public final OptionalDouble findAny() {
        return evaluate(FindOps.makeDouble(false));
    }

    @Override
    public final double[] toArray() {
        return Nodes.flattenDouble((Node.OfDouble) evaluateToArrayNode(Double[]::new))
                        .asPrimitiveArray();
    }

    //

    /**
     * Source stage of a DoubleStream
     *
     * @param <E_IN> type of elements in the upstream source
     */
    static class Head<E_IN> extends DoublePipeline<E_IN> {
        /**
         * Constructor for the source stage of a DoubleStream.
         *
         * @param source {@code Supplier<Spliterator>} describing the stream
         *               source
         * @param sourceFlags the source flags for the stream source, described
         *                    in {@link StreamOpFlag}
         * @param parallel {@code true} if the pipeline is parallel
         */
        Head(Supplier<? extends Spliterator<Double>> source,
             int sourceFlags, boolean parallel) {
            super(source, sourceFlags, parallel);
        }

        /**
         * Constructor for the source stage of a DoubleStream.
         *
         * @param source {@code Spliterator} describing the stream source
         * @param sourceFlags the source flags for the stream source, described
         *                    in {@link StreamOpFlag}
         * @param parallel {@code true} if the pipeline is parallel
         */
        Head(Spliterator<Double> source,
             int sourceFlags, boolean parallel) {
            super(source, sourceFlags, parallel);
        }

        @Override
        final boolean opIsStateful() {
            throw new UnsupportedOperationException();
        }

        @Override
        final Sink<E_IN> opWrapSink(int flags, Sink<Double> sink) {
            throw new UnsupportedOperationException();
        }

        // Optimized sequential terminal operations for the head of the pipeline

        @Override
        public void forEach(DoubleConsumer consumer) {
            if (!isParallel()) {
                adapt(sourceStageSpliterator()).forEachRemaining(consumer);
            }
            else {
                super.forEach(consumer);
            }
        }

        @Override
        public void forEachOrdered(DoubleConsumer consumer) {
            if (!isParallel()) {
                adapt(sourceStageSpliterator()).forEachRemaining(consumer);
            }
            else {
                super.forEachOrdered(consumer);
            }
        }

    }

    /**
     * Base class for a stateless intermediate stage of a DoubleStream.
     *
     * @param <E_IN> type of elements in the upstream source
     * @since 1.8
     */
    abstract static class StatelessOp<E_IN> extends DoublePipeline<E_IN> {
        /**
         * Construct a new DoubleStream by appending a stateless intermediate
         * operation to an existing stream.
         *
         * @param upstream the upstream pipeline stage
         * @param inputShape the stream shape for the upstream pipeline stage
         * @param opFlags operation flags for the new stage
         */
        StatelessOp(AbstractPipeline<?, E_IN, ?> upstream,
                    StreamShape inputShape,
                    int opFlags) {
            super(upstream, opFlags);
            assert upstream.getOutputShape() == inputShape;
        }

        @Override
        final boolean opIsStateful() {
            return false;
        }
    }

    /**
     * Base class for a stateful intermediate stage of a DoubleStream.
     *
     * @param <E_IN> type of elements in the upstream source
     * @since 1.8
     */
    abstract static class StatefulOp<E_IN> extends DoublePipeline<E_IN> {
        /**
         * Construct a new DoubleStream by appending a stateful intermediate
         * operation to an existing stream.
         *
         * @param upstream the upstream pipeline stage
         * @param inputShape the stream shape for the upstream pipeline stage
         * @param opFlags operation flags for the new stage
         */
        StatefulOp(AbstractPipeline<?, E_IN, ?> upstream,
                   StreamShape inputShape,
                   int opFlags) {
            super(upstream, opFlags);
            assert upstream.getOutputShape() == inputShape;
        }

        @Override
        final boolean opIsStateful() {
            return true;
        }

        @Override
        abstract <P_IN> Node<Double> opEvaluateParallel(PipelineHelper<Double> helper,
                                                        Spliterator<P_IN> spliterator,
                                                        IntFunction<Double[]> generator);
    }
}

{'repo_name': 'corretto/corretto-8', 'stars': '1803', 'repo_language': 'Java', 'file_name': 'FtpLoginException.java', 'mime_type': 'text/x-java', 'hash': 184183787134671986, 'source_dataset': 'data'}


//  (C) Copyright Gennadiy Rozental 2001.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
/// @file
/// @brief defines testing result reporter interfaces
///
/// This file defines interfaces that are responsible for results reporting. Interface is presented in a form of
/// free standing function implemented in namespace result_reporter
// ***************************************************************************

#ifndef BOOST_TEST_RESULTS_REPORTER_HPP_021205GER
#define BOOST_TEST_RESULTS_REPORTER_HPP_021205GER

// Boost.Test
#include <boost/test/detail/global_typedef.hpp>
#include <boost/test/detail/fwd_decl.hpp>

// STL
#include <iosfwd>   // for std::ostream&

#include <boost/test/detail/suppress_warnings.hpp>

//____________________________________________________________________________//

namespace boost {
namespace unit_test {

/// Namespace for results reporter interfaces
namespace results_reporter {

// ************************************************************************** //
/// @brief Results report formatter interface
///
/// This is abstract interface for the report formatter used by results reporter routines.
/// You can define a custom formatter by implementing this interface and setting the formatter using set_format function.
/// This is usually done during test module initialization
// ************************************************************************** //

class BOOST_TEST_DECL format {
public:
    // Destructor
    virtual ~format() {}

    virtual void    results_report_start( std::ostream& ostr ) = 0;
    virtual void    results_report_finish( std::ostream& ostr ) = 0;

    virtual void    test_unit_report_start( test_unit const&, std::ostream& ostr ) = 0;
    virtual void    test_unit_report_finish( test_unit const&, std::ostream& ostr ) = 0;

    virtual void    do_confirmation_report( test_unit const&, std::ostream& ostr ) = 0;
};

// ************************************************************************** //
/// @name report configuration
// ************************************************************************** //

/// Sets reporting level

/// There are only four possible levels for results report:
/// - confirmation report (boost::unit_test::CONFIRMATION_REPORT). This report level only produces short confirmation
///   message about test module pass/fail status
/// - short report (boost::unit_test::SHORT_REPORT). This report level produces short summary report for failed/passed
///   assertions and test units.
/// - detailed report (boost::unit_test::DETAILED_REPORT). This report level produces detailed report per test unit for
///   passed/failed assertions and uncaught exceptions
/// - no report (boost::unit_test::NO_REPORT). This report level produces no results report. This is used for test modules
///   running as part of some kind of continues integration framework
/// @param[in] l report level
BOOST_TEST_DECL void    set_level( report_level l );

/// Sets output stream for results reporting

/// By default std::cerr is used. Use this function to set a different stream. The framework
/// refers to the stream by reference, so you need to make sure the stream object lifetime exceeds the testing main scope.
BOOST_TEST_DECL void    set_stream( std::ostream& );

/// Sets one of the predefined formats

/// The framework implements two results report formats:
/// - plain human readable format (boost::unit_test::OF_CLF)
/// - XML format (boost::unit_test::OF_XML)
/// @param[in] of one of the presefined enumeration values for output formats
BOOST_TEST_DECL void    set_format( output_format of );

/// Sets custom report formatter

/// The framework takes ownership of the pointer passed as an argument. So this should be a pointer to
/// a heap allocated object
/// @param[in] f pointer to heap allocated instance of custom report formatter class
BOOST_TEST_DECL void    set_format( results_reporter::format* f );

/// @brief Access to configured results reporter stream
///
/// Use this stream to report additional information abut test module execution
BOOST_TEST_DECL std::ostream& get_stream();

/// @}

// ************************************************************************** //
// **************               report initiation              ************** //
// ************************************************************************** //

BOOST_TEST_DECL void    make_report( report_level l = INV_REPORT_LEVEL, test_unit_id = INV_TEST_UNIT_ID );
inline void             confirmation_report( test_unit_id id = INV_TEST_UNIT_ID )
{ make_report( CONFIRMATION_REPORT, id ); }
inline void             short_report( test_unit_id id = INV_TEST_UNIT_ID )
{ make_report( SHORT_REPORT, id ); }
inline void             detailed_report( test_unit_id id = INV_TEST_UNIT_ID )
{ make_report( DETAILED_REPORT, id ); }

} // namespace results_reporter
} // namespace unit_test
} // namespace boost

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_RESULTS_REPORTER_HPP_021205GER

{'repo_name': 'supercollider/supercollider', 'stars': '3239', 'repo_language': 'C++', 'file_name': 'UIUGens.cpp', 'mime_type': 'text/x-c', 'hash': -5680518707166910845, 'source_dataset': 'data'}


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout android:orientation="horizontal" android:id="@id/bl_" android:background="@drawable/dl" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="13.0dip" android:layout_marginRight="13.0dip" android:minHeight="@dimen/j7">
        <ImageView android:layout_gravity="center_vertical" android:id="@id/l4" android:layout_width="@dimen/dk" android:layout_height="@dimen/dk" android:layout_marginRight="8.0dip" />
        <LinearLayout android:gravity="center_vertical" android:layout_gravity="center_vertical" android:orientation="vertical" android:paddingLeft="@dimen/j_" android:layout_width="0.0dip" android:layout_height="fill_parent" android:layout_weight="1.0">
            <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content">
                <TextView android:id="@id/i1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="{title}" android:singleLine="true" style="@style/MMFontTitleInList" />
                <TextView android:id="@id/fr" android:visibility="gone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5.0dip" android:text="{tip}" style="@style/MMFontTitleInList" />
            </LinearLayout>
            <TextView android:textSize="@dimen/jc" android:textColor="#ff555555" android:id="@id/i3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="{desc}" android:singleLine="true" style="@style/MMFontTipInList" />
        </LinearLayout>
        <CheckBox android:layout_gravity="center_vertical" android:id="@id/l6" android:background="@drawable/iv" android:focusable="false" android:focusableInTouchMode="false" android:visibility="gone" android:clickable="false" android:layout_width="20.0dip" android:layout_height="20.0dip" android:layout_marginLeft="@dimen/j8" android:layout_marginRight="@dimen/he" />
    </LinearLayout>
</RelativeLayout>

{'repo_name': 'reverseengineeringer/com.tencent.mm', 'stars': '201', 'repo_language': 'Smali', 'file_name': 'LibCardRecog.smali', 'mime_type': 'text/plain', 'hash': 4032642420523122911, 'source_dataset': 'data'}


<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE toc
  PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp TOC Version 2.0//EN"
         "http://java.sun.com/products/javahelp/toc_2_0.dtd">

<toc version="2.0">
	<tocitem text="ZAP User Guide" tocid="toplevelitem">
		<tocitem text="Accessoires" tocid="addons">
			<tocitem text="Reveal" image="addon.reveal.images.enabled" target="addon.reveal.concepts"/>
		</tocitem>
	</tocitem>
</toc>

{'repo_name': 'zaproxy/zap-extensions', 'stars': '429', 'repo_language': 'Java', 'file_name': 'PassiveScanTestHelper.java', 'mime_type': 'text/x-java', 'hash': -1789188887354700150, 'source_dataset': 'data'}


package cn.tzy.Jblog.service;

import org.apache.commons.lang.CharUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by tuzhenyu on 17-7-21.
 * @author tuzhenyu
 */
@Service
public class SensitiveService implements InitializingBean{

    private class TrieNode{
        private boolean end = false;
        private Map<Character,TrieNode> subNodes = new HashMap<>();

        public void addSubNode(Character key,TrieNode node){
            subNodes.put(key,node);
        }

        public TrieNode getSubNode(Character key){
            return subNodes.get(key);
        }

        public boolean isEnd(){
            return end;
        }

        public void setNodeEnd(boolean end){
            this.end = end;
        }
    }

    private TrieNode root = new TrieNode();

    @Override
    public void afterPropertiesSet() throws Exception {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("SensitiveWords.txt");
        InputStreamReader reader = new InputStreamReader(is);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String lineTxt;
        while ((lineTxt=bufferedReader.readLine())!=null){
            addWord(lineTxt.trim());
        }
        reader.close();
        is.close();
    }

    public boolean isSymbol(char c){
        int ic = (int)c;
        return !CharUtils.isAsciiAlphanumeric(c)&& (ic<0x2E80 || ic>0x9FFF);
    }

    private void addWord(String lineTxt){
        TrieNode currentNode = root;
        for (int i=0;i<lineTxt.length();i++){
            Character c = lineTxt.charAt(i);
            if (isSymbol(c))
                continue;
            TrieNode node = currentNode.getSubNode(c);
            if (node==null){
                node = new TrieNode();
                currentNode.addSubNode(c,node);
            }
            currentNode = node;
            if (i==lineTxt.length()-1)
                currentNode.setNodeEnd(true);
        }
    }

    public String filter(String text){
        if (StringUtils.isBlank(text)){
            return text;
        }

        StringBuilder result = new StringBuilder();
        String replacement = "***";
        TrieNode tmpNode = root;
        int begin = 0;
        int position = 0;

        while (position<text.length()){
            Character c = text.charAt(position);
            if (isSymbol(c)){
                if (tmpNode==root){
                    result.append(c);
                    begin++;
                }
                position++;
                continue;
            }

            tmpNode = tmpNode.getSubNode(c);
            if (tmpNode == null){
                if (position!=begin)
                    result.append(text.substring(begin,position));
                else
                    result.append(c);
                position = begin+1;
                begin = position;
                tmpNode = root;
            }else if (tmpNode.isEnd()){
                result.append(replacement);
                position++;
                begin = position;
                tmpNode = root;
            }else {
                position++;
            }
        }
        result.append(text.substring(begin));
        return result.toString();
    }

}

{'repo_name': 'zhenyutu/Jblog', 'stars': '103', 'repo_language': 'CSS', 'file_name': 'create.sql', 'mime_type': 'text/plain', 'hash': -2335399742799373425, 'source_dataset': 'data'}


import RewritingStream from 'parse5-html-rewriting-stream'
import * as htmlRules from './html-rules'
import stream from 'stream'
import { DeferSourceMapRewriteFn } from './js'

// the HTML rewriter passes inline JS to the JS rewriter, hence
// the lack of basic `rewriteHtml` or `HtmlRewriter` exports here

export function HtmlJsRewriter (url: string, deferSourceMapRewrite?: DeferSourceMapRewriteFn): stream.Transform {
  const rewriter = new RewritingStream()

  htmlRules.install(url, rewriter, deferSourceMapRewrite)

  return rewriter
}

export function rewriteHtmlJs (url: string, html: string, deferSourceMapRewrite?: DeferSourceMapRewriteFn): Promise<string> {
  let out = ''
  const rewriter = HtmlJsRewriter(url, deferSourceMapRewrite)

  rewriter.on('data', (chunk) => {
    out += chunk
  })

  rewriter.end(html)

  return new Promise<string>((resolve) => {
    rewriter.on('end', () => {
      resolve(out)
    })
  })
}

{'repo_name': 'cypress-io/cypress', 'stars': '21861', 'repo_language': 'JavaScript', 'file_name': 'settings.json', 'mime_type': 'text/plain', 'hash': 1971248053974911927, 'source_dataset': 'data'}


Instruction: This is a sheet for Abstract Dungeon. The base is set up for French but it can easily be tweak to any language. There are two main tabs : the player character'sheet and the non-player character's sheet (access in the upper right corner). Don't hesitate to use NPC_card as a macro (like @{selected|NPC_card}), it will display a NPC card in the chat with all relative informations without opening the character sheet. The config can be accessed via the gear icon.

Change le nom du jeu pour correspondre à votre style

Change les caractéristiques pour correspondre à votre type de jeu

Change les compétences pour correspondre à votre type de jeu

Trancher, Endurer, Briser, Sauter, Grimper, Plier, Nager, Souffler, Courir, Broyer, Pousser, Tirer, Soulever, Porter, Encaisser, Arracher, Lancer

Change les descriptions pour correspondre à votre type de jeu

Esquiver, Parer, Equilibrer, Basculer, Rouler, Viser, Danser, Attraper, Ramasser, Désarmer, Nouer, S'échapper, Dévier, Transpercer, Se retourner

Communier, Sentir, Motiver, Exhorter, Sympathiser, Persuader, Intimider, Pressentir, Ordonner, Commander, Provoquer, Embrouiller, Canaliser

Convaincre, Se souvenir, Déduire, Raisonner, Déchiffrer, Inventer, Chercher, Débattre, Supposer, Etudier, Résoudre, Mystifier, Incanter, Méditer

{'repo_name': 'Roll20/roll20-character-sheets', 'stars': '790', 'repo_language': 'HTML', 'file_name': 'sheet.css', 'mime_type': 'text/plain', 'hash': -4693539780249539448, 'source_dataset': 'data'}


/*
 * Copyright (C) STMicroelectronics SA 2014
 * Author: Benjamin Gaignard <benjamin.gaignard@st.com> for STMicroelectronics.
 * License terms:  GNU General Public License (GPL), version 2
 */

#include <linux/clk.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>

#include <drm/drmP.h>

/* registers offset */
#define VTAC_CONFIG                     0x00
#define VTAC_RX_FIFO_CONFIG             0x04
#define VTAC_FIFO_CONFIG_VAL            0x04

#define VTAC_SYS_CFG8521                0x824
#define VTAC_SYS_CFG8522                0x828

/* Number of phyts per pixel */
#define VTAC_2_5_PPP                    0x0005
#define VTAC_3_PPP                      0x0006
#define VTAC_4_PPP                      0x0008
#define VTAC_5_PPP                      0x000A
#define VTAC_6_PPP                      0x000C
#define VTAC_13_PPP                     0x001A
#define VTAC_14_PPP                     0x001C
#define VTAC_15_PPP                     0x001E
#define VTAC_16_PPP                     0x0020
#define VTAC_17_PPP                     0x0022
#define VTAC_18_PPP                     0x0024

/* enable bits */
#define VTAC_ENABLE                     0x3003

#define VTAC_TX_PHY_ENABLE_CLK_PHY      BIT(0)
#define VTAC_TX_PHY_ENABLE_CLK_DLL      BIT(1)
#define VTAC_TX_PHY_PLL_NOT_OSC_MODE    BIT(3)
#define VTAC_TX_PHY_RST_N_DLL_SWITCH    BIT(4)
#define VTAC_TX_PHY_PROG_N3             BIT(9)

/**
 * VTAC mode structure
 *
 * @vid_in_width: Video Data Resolution
 * @phyts_width: Width of phyt buses(phyt low and phyt high).
 * @phyts_per_pixel: Number of phyts sent per pixel
 */
struct sti_vtac_mode {
	u32 vid_in_width;
	u32 phyts_width;
	u32 phyts_per_pixel;
};

static const struct sti_vtac_mode vtac_mode_main = {
	.vid_in_width = 0x2,
	.phyts_width = 0x2,
	.phyts_per_pixel = VTAC_5_PPP,
};
static const struct sti_vtac_mode vtac_mode_aux = {
	.vid_in_width = 0x1,
	.phyts_width = 0x0,
	.phyts_per_pixel = VTAC_17_PPP,
};

/**
 * VTAC structure
 *
 * @dev: pointer to device structure
 * @regs: ioremapped registers for RX and TX devices
 * @phy_regs: phy registers for TX device
 * @clk: clock
 * @mode: main or auxillary configuration mode
 */
struct sti_vtac {
	struct device *dev;
	void __iomem *regs;
	void __iomem *phy_regs;
	struct clk *clk;
	const struct sti_vtac_mode *mode;
};

static void sti_vtac_rx_set_config(struct sti_vtac *vtac)
{
	u32 config;

	/* Enable VTAC clock */
	if (clk_prepare_enable(vtac->clk))
		DRM_ERROR("Failed to prepare/enable vtac_rx clock.\n");

	writel(VTAC_FIFO_CONFIG_VAL, vtac->regs + VTAC_RX_FIFO_CONFIG);

	config = VTAC_ENABLE;
	config |= vtac->mode->vid_in_width << 4;
	config |= vtac->mode->phyts_width << 16;
	config |= vtac->mode->phyts_per_pixel << 23;
	writel(config, vtac->regs + VTAC_CONFIG);
}

static void sti_vtac_tx_set_config(struct sti_vtac *vtac)
{
	u32 phy_config;
	u32 config;

	/* Enable VTAC clock */
	if (clk_prepare_enable(vtac->clk))
		DRM_ERROR("Failed to prepare/enable vtac_tx clock.\n");

	/* Configure vtac phy */
	phy_config = 0x00000000;
	writel(phy_config, vtac->phy_regs + VTAC_SYS_CFG8522);
	phy_config = VTAC_TX_PHY_ENABLE_CLK_PHY;
	writel(phy_config, vtac->phy_regs + VTAC_SYS_CFG8521);
	phy_config = readl(vtac->phy_regs + VTAC_SYS_CFG8521);
	phy_config |= VTAC_TX_PHY_PROG_N3;
	writel(phy_config, vtac->phy_regs + VTAC_SYS_CFG8521);
	phy_config = readl(vtac->phy_regs + VTAC_SYS_CFG8521);
	phy_config |= VTAC_TX_PHY_ENABLE_CLK_DLL;
	writel(phy_config, vtac->phy_regs + VTAC_SYS_CFG8521);
	phy_config = readl(vtac->phy_regs + VTAC_SYS_CFG8521);
	phy_config |= VTAC_TX_PHY_RST_N_DLL_SWITCH;
	writel(phy_config, vtac->phy_regs + VTAC_SYS_CFG8521);
	phy_config = readl(vtac->phy_regs + VTAC_SYS_CFG8521);
	phy_config |= VTAC_TX_PHY_PLL_NOT_OSC_MODE;
	writel(phy_config, vtac->phy_regs + VTAC_SYS_CFG8521);

	/* Configure vtac tx */
	config = VTAC_ENABLE;
	config |= vtac->mode->vid_in_width << 4;
	config |= vtac->mode->phyts_width << 16;
	config |= vtac->mode->phyts_per_pixel << 23;
	writel(config, vtac->regs + VTAC_CONFIG);
}

static const struct of_device_id vtac_of_match[] = {
	{
		.compatible = "st,vtac-main",
		.data = &vtac_mode_main,
	}, {
		.compatible = "st,vtac-aux",
		.data = &vtac_mode_aux,
	}, {
		/* end node */
	}
};
MODULE_DEVICE_TABLE(of, vtac_of_match);

static int sti_vtac_probe(struct platform_device *pdev)
{
	struct device *dev = &pdev->dev;
	struct device_node *np = dev->of_node;
	const struct of_device_id *id;
	struct sti_vtac *vtac;
	struct resource *res;

	vtac = devm_kzalloc(dev, sizeof(*vtac), GFP_KERNEL);
	if (!vtac)
		return -ENOMEM;

	vtac->dev = dev;

	id = of_match_node(vtac_of_match, np);
	if (!id)
		return -ENOMEM;

	vtac->mode = id->data;

	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if (!res) {
		DRM_ERROR("Invalid resource\n");
		return -ENOMEM;
	}
	vtac->regs = devm_ioremap_resource(dev, res);
	if (IS_ERR(vtac->regs))
		return PTR_ERR(vtac->regs);

	vtac->clk = devm_clk_get(dev, "vtac");
	if (IS_ERR(vtac->clk)) {
		DRM_ERROR("Cannot get vtac clock\n");
		return PTR_ERR(vtac->clk);
	}

	res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
	if (res) {
		vtac->phy_regs = devm_ioremap_nocache(dev, res->start,
						 resource_size(res));
		sti_vtac_tx_set_config(vtac);
	} else {

		sti_vtac_rx_set_config(vtac);
	}

	platform_set_drvdata(pdev, vtac);
	DRM_INFO("%s %s\n", __func__, dev_name(vtac->dev));

	return 0;
}

static int sti_vtac_remove(struct platform_device *pdev)
{
	return 0;
}

struct platform_driver sti_vtac_driver = {
	.driver = {
		.name = "sti-vtac",
		.owner = THIS_MODULE,
		.of_match_table = vtac_of_match,
	},
	.probe = sti_vtac_probe,
	.remove = sti_vtac_remove,
};

module_platform_driver(sti_vtac_driver);

MODULE_AUTHOR("Benjamin Gaignard <benjamin.gaignard@st.com>");
MODULE_DESCRIPTION("STMicroelectronics SoC DRM driver");
MODULE_LICENSE("GPL");

{'repo_name': 'ljrcore/linuxmooc', 'stars': '217', 'repo_language': 'C', 'file_name': 'ecc.c', 'mime_type': 'text/x-c', 'hash': 8876484989974976438, 'source_dataset': 'data'}


---------------------------------------------------------------------------------------
-- Title          : Wishbone slave core for Simple Wishbone UART
---------------------------------------------------------------------------------------
-- File           : simple_uart_pkg.vhd
-- Author         : auto-generated by wbgen2 from simple_uart_wb.wb
-- Created        : Tue Aug 15 10:16:30 2017
-- Standard       : VHDL'87
---------------------------------------------------------------------------------------
-- THIS FILE WAS GENERATED BY wbgen2 FROM SOURCE FILE simple_uart_wb.wb
-- DO NOT HAND-EDIT UNLESS IT'S ABSOLUTELY NECESSARY!
---------------------------------------------------------------------------------------

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

package uart_wbgen2_pkg is

  -- Input registers (user design -> WB slave)

  type t_uart_in_registers is record
    sr_tx_busy_i                             : std_logic;
    sr_rx_rdy_i                              : std_logic;
    rdr_rx_data_i                            : std_logic_vector(7 downto 0);
    host_tdr_rdy_i                           : std_logic;
    host_rdr_data_i                          : std_logic_vector(7 downto 0);
    host_rdr_rdy_i                           : std_logic;
    host_rdr_count_i                         : std_logic_vector(15 downto 0);
    end record;

  constant c_uart_in_registers_init_value: t_uart_in_registers := (
    sr_tx_busy_i => '0',
    sr_rx_rdy_i => '0',
    rdr_rx_data_i => (others => '0'),
    host_tdr_rdy_i => '0',
    host_rdr_data_i => (others => '0'),
    host_rdr_rdy_i => '0',
    host_rdr_count_i => (others => '0')
    );

    -- Output registers (WB slave -> user design)

    type t_uart_out_registers is record
      bcr_o                                    : std_logic_vector(31 downto 0);
      bcr_wr_o                                 : std_logic;
      tdr_tx_data_o                            : std_logic_vector(7 downto 0);
      tdr_tx_data_wr_o                         : std_logic;
      host_tdr_data_o                          : std_logic_vector(7 downto 0);
      host_tdr_data_wr_o                       : std_logic;
      end record;

    constant c_uart_out_registers_init_value: t_uart_out_registers := (
      bcr_o => (others => '0'),
      bcr_wr_o => '0',
      tdr_tx_data_o => (others => '0'),
      tdr_tx_data_wr_o => '0',
      host_tdr_data_o => (others => '0'),
      host_tdr_data_wr_o => '0'
      );
    function "or" (left, right: t_uart_in_registers) return t_uart_in_registers;
    function f_x_to_zero (x:std_logic) return std_logic;
    function f_x_to_zero (x:std_logic_vector) return std_logic_vector;
end package;

package body uart_wbgen2_pkg is
function f_x_to_zero (x:std_logic) return std_logic is
begin
if x = '1' then
return '1';
else
return '0';
end if;
end function;
function f_x_to_zero (x:std_logic_vector) return std_logic_vector is
variable tmp: std_logic_vector(x'length-1 downto 0);
begin
for i in 0 to x'length-1 loop
if x(i) = '1' then
tmp(i):= '1';
else
tmp(i):= '0';
end if;
end loop;
return tmp;
end function;
function "or" (left, right: t_uart_in_registers) return t_uart_in_registers is
variable tmp: t_uart_in_registers;
begin
tmp.sr_tx_busy_i := f_x_to_zero(left.sr_tx_busy_i) or f_x_to_zero(right.sr_tx_busy_i);
tmp.sr_rx_rdy_i := f_x_to_zero(left.sr_rx_rdy_i) or f_x_to_zero(right.sr_rx_rdy_i);
tmp.rdr_rx_data_i := f_x_to_zero(left.rdr_rx_data_i) or f_x_to_zero(right.rdr_rx_data_i);
tmp.host_tdr_rdy_i := f_x_to_zero(left.host_tdr_rdy_i) or f_x_to_zero(right.host_tdr_rdy_i);
tmp.host_rdr_data_i := f_x_to_zero(left.host_rdr_data_i) or f_x_to_zero(right.host_rdr_data_i);
tmp.host_rdr_rdy_i := f_x_to_zero(left.host_rdr_rdy_i) or f_x_to_zero(right.host_rdr_rdy_i);
tmp.host_rdr_count_i := f_x_to_zero(left.host_rdr_count_i) or f_x_to_zero(right.host_rdr_count_i);
return tmp;
end function;
end package body;

{'repo_name': 'EttusResearch/uhd', 'stars': '477', 'repo_language': 'Verilog', 'file_name': 'i2c_master_defines.v', 'mime_type': 'text/plain', 'hash': -6766855573893181395, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8"?>
<!--
 /**
  * Copyright © Magento, Inc. All rights reserved.
  * See COPYING.txt for license details.
  */
-->

<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd">
    <section name="CheckoutCartMessageSection">
        <element name="successMessage" type="text" selector=".message.message-success.success>div" />
        <element name="errorMessage" type="text" selector=".message-error.error.message>div" />
        <element name="emptyCartMessage" type="text" selector=".cart-empty>p"/>
        <element name="errorMessageText" type="text" selector="//div[contains(@class, 'message-error')]/div[text()='{{var}}']" parameterized="true"/>
    </section>
</sections>

{'repo_name': 'magento/magento2', 'stars': '8767', 'repo_language': 'PHP', 'file_name': 'report.phtml', 'mime_type': 'text/x-php', 'hash': 2978639321315888341, 'source_dataset': 'data'}


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateHomeworksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('homeworks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('file_path');
            $table->text('description');
            $table->integer('teacher_id')->unsigned();
            $table->integer('section_id')->unsigned();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('homeworks');
    }
}

{'repo_name': 'changeweb/Unifiedtransform', 'stars': '1846', 'repo_language': 'PHP', 'file_name': 'application.js', 'mime_type': 'text/plain', 'hash': -5565317175287299084, 'source_dataset': 'data'}


# SPDX-License-Identifier: Apache-2.0

add_definitions(-D__ZEPHYR_SUPERVISOR__)

include_directories(
  ${ZEPHYR_BASE}/kernel/include
  ${ARCH_DIR}/${ARCH}/include
  )

add_subdirectory(common)
add_subdirectory(${ARCH_DIR}/${ARCH} arch/${ARCH})

{'repo_name': 'zephyrproject-rtos/zephyr', 'stars': '3443', 'repo_language': 'C', 'file_name': 'CMakeLists.txt', 'mime_type': 'text/plain', 'hash': 3485114501158289327, 'source_dataset': 'data'}