text:
#include "linksbagmanager.h"

#include <QDir>
#include <QSettings>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QFile>
#include <QByteArray>
#include <QImage>
#include <QTimer>
#include <QThread>
#include <QThreadPool>

#include "settings/applicationsettings.h"
#include "application.h"
#include "bookmarksmodel.h"
#include "downloadedcontenthandler.h"
#include "downloadedimagehandler.h"
#include "enumsproxy.h"
#include "filterproxymodel.h"
#include "getpocketapi.h"
#include "offlinedownloader.h"

namespace LinksBag
{
LinksBagManager::LinksBagManager(QObject *parent)
: QObject(parent)
, m_Api(new GetPocketApi(this))
, m_IsBusy(false)
, m_IsLogged(false)
, m_BookmarksModel(new BookmarksModel(this))
, m_FilterProxyModel(new FilterProxyModel(m_BookmarksModel, this))
, m_CoverModel(new FilterProxyModel(m_BookmarksModel, this))
, m_ThumbnailDownloader(new QNetworkAccessManager(this))
, m_SyncTimer(new QTimer(this))
, m_OfflineDownloader(new OfflineDownloader())
, m_OfflineDownloaderThread(new QThread())
{
    MakeConnections();

    QDir dir;
    dir.mkpath(Application::GetPath(Application::ThumbnailCacheDirectory));
    dir.mkpath(Application::GetPath(Application::ArticleCacheDirectory));
    dir.mkpath(Application::GetPath(Application::CoverCacheDirectory));

    m_FilterProxyModel->setSourceModel(m_BookmarksModel);
    m_CoverModel->setSourceModel(m_BookmarksModel);

    m_FilterProxyModel->filterBookmarks(ApplicationSettings::Instance(this)->value("statusFilter").toInt(),
            ApplicationSettings::Instance(this)->value("contentTypeFilter").toInt());
    m_CoverModel->filterBookmarks(ApplicationSettings::Instance(this)->value("statusFilter").toInt(),
            ContentTypeAll);

    connect(m_ThumbnailDownloader, &QNetworkAccessManager::finished,
            this, &LinksBagManager::thumbnailReceived);

    m_OfflineDownloader->moveToThread(m_OfflineDownloaderThread);
    connect(m_OfflineDownloader, &OfflineDownloader::queueNeedsRefresh,
            this, &LinksBagManager::updateOfflineDownloaderQueue, Qt::QueuedConnection);
    connect(m_OfflineDownloader, &OfflineDownloader::updateBookmarkCount,
            this, &LinksBagManager::handleUpdateBookmarkCount, Qt::QueuedConnection);
    connect(m_OfflineDownloader, &OfflineDownloader::updateArticleContent,
            this, &LinksBagManager::handleUpdateArticleContent, Qt::QueuedConnection);
    connect(m_OfflineDownloader, &OfflineDownloader::updateImageContent,
            this, &LinksBagManager::handleUpdateImageContent, Qt::QueuedConnection);
    connect(m_OfflineDownloaderThread, &QThread::started,
            m_OfflineDownloader, &OfflineDownloader::start);
    connect(m_OfflineDownloaderThread, &QThread::finished,
            m_OfflineDownloaderThread, &QThread::deleteLater);
    connect(this, &LinksBagManager::offlineDownloaderEnabled,
            m_OfflineDownloader, &OfflineDownloader::handleOfflineDownloaderEnabled,
            Qt::QueuedConnection);
    connect(this, &LinksBagManager::wifiOnlyDownloaderEnabled,
            m_OfflineDownloader, &OfflineDownloader::handleWifiOnlyDownloaderEnabled,
            Qt::QueuedConnection);
    connect(this, &LinksBagManager::unreadOnlyDownloaderEnabled,
            m_OfflineDownloader, &OfflineDownloader::handleUnreadOnlyDownloaderEnabled,
            Qt::QueuedConnection);

    connect(m_SyncTimer, &QTimer::timeout, this, &LinksBagManager::refreshBookmarks);

    SetLogged(!ApplicationSettings::Instance(this)->value("accessToken").isNull() &&
              !ApplicationSettings::Instance(this)->value("userName").isNull());

    m_OfflineDownloaderThread->start();

    if (m_IsLogged)
    {
        loadBookmarksFromCache();
        updateOfflineDownloaderQueue();
    }

    restartSyncTimer();
}

LinksBagManager* LinksBagManager::Instance(QObject *parent)
{
    static LinksBagManager *linksBagManager = nullptr;
    if (!linksBagManager)
    {
        linksBagManager = new LinksBagManager(parent);
    }
    return linksBagManager;
}

bool LinksBagManager::GetBusy() const
{
    return m_IsBusy;
}

bool LinksBagManager::GetLogged() const
{
    return m_IsLogged;
}

BookmarksModel* LinksBagManager::GetBookmarksModel() const
{
    return m_BookmarksModel;
}

FilterProxyModel* LinksBagManager::GetFilterModel() const
{
    return m_FilterProxyModel;
}

FilterProxyModel *LinksBagManager::GetCoverModel() const
{
    return m_CoverModel;
}

int LinksBagManager::GetDownloaderQueueSize() const
{
    return m_OfflineDownloaderQueueSize;
}

int LinksBagManager::GetDownloadedBookmarksCount() const
{
    auto bookmarks = m_BookmarksModel->GetBookmarks();
    const int count = std::count_if(bookmarks.begin(), bookmarks.end(),
            [](decltype(bookmarks.front()) bkm) { return bkm->HasContent(); });
    return count;
}

void LinksBagManager::Stop()
{
    m_OfflineDownloader->stop();
    m_OfflineDownloader->deleteLater();
    m_OfflineDownloaderThread->quit();
    m_OfflineDownloaderThread->wait();
}

void LinksBagManager::MakeConnections()
{
    connect(this, &LinksBagManager::articlesCacheReset,
            m_BookmarksModel, &BookmarksModel::handleArticlesCacheReset);

    connect(m_Api.get(),
            &GetPocketApi::requestFinished,
            this,
            [=](bool success, const QString& errorMsg)
            {
                SetBusy(false);
                if (!success && !errorMsg.isEmpty())
                {
                    emit error(errorMsg, ETGeneral);
                }
            });
    connect(m_Api.get(),
            &GetPocketApi::error,
            this,
            [=](const QString& msg, int code, ErrorType type)
            {
                SetBusy(false);
                const QString errorMessage = (type == ETGetPocket?
                        (tr("GetPocket error (%1): ").arg(code) + msg) :
                        msg);
                emit error(errorMessage, type);
            });

    connect(m_Api.get(),
            &GetPocketApi::requestTokenChanged,
            this,
            &LinksBagManager::requestTokenChanged);

    connect(m_Api.get(),
            &GetPocketApi::logged,
            this,
            [=](bool logged, const QString& accessToken, const QString& userName)
            {
                ApplicationSettings::Instance(this)->
                        setValue("accessToken", accessToken);
                ApplicationSettings::Instance(this)->
                        setValue("userName", userName);
                SetLogged(logged);
            });

    connect(m_Api.get(),
            &GetPocketApi::gotBookmarks,
            this,
            [this](const Bookmarks_t& bookmarks, quint64 since)
            {
                m_BookmarksModel->AddBookmarks(bookmarks);
                saveBookmarks();
                const auto& savedBookmarks = m_BookmarksModel->GetBookmarks();
                for (int i=savedBookmarks.size()-1; i>=0; --i) {
                    auto b = savedBookmarks.at(i);
                    QString path = Application::GetPath(Application::ThumbnailCacheDirectory) +
                            b->GetID() + ".jpg";
                    if (QFile(path).exists())
                        continue;

                    const QUrl url = b->GetImageUrl();
                    if (!url.isEmpty())
                    {
                        m_ThumbnailUrls[url] = b->GetID();
                        m_ThumbnailDownloader->get(QNetworkRequest(url));
                    }
                }
                m_FilterProxyModel->invalidate();
                m_FilterProxyModel->sort(0, Qt::DescendingOrder);
                ApplicationSettings::Instance(this)->setValue("lastUpdate", since);
                updateOfflineDownloaderQueue();
            });

    connect(m_Api.get(),
            &GetPocketApi::bookmarksRemoved,
            this,
            [this](const QStringList& ids)
            {
                m_BookmarksModel->RemoveBookmarks(ids);
                updateOfflineDownloaderQueue();
            });

    connect(m_Api.get(),
            &GetPocketApi::bookmarksMarkedAsFavorite,
            [this](const QStringList& ids, bool favorite)
            {
                m_BookmarksModel->MarkBookmarksAsFavorite(ids, favorite);
            });

    connect(m_Api.get(),
            &GetPocketApi::bookmarksMarkedAsRead,
            [this](const QStringList& ids, bool read)
            {
                m_BookmarksModel->MarkBookmarksAsRead(ids, read);
            });

    connect(m_Api.get(),
            &GetPocketApi::tagsUpdated,
            [this](const QString& id, const QString& tags)
            {
                m_BookmarksModel->UpdateTags(id, tags);
            });
}

void LinksBagManager::SetBusy(const bool busy)
{
    m_IsBusy = busy;
    emit busyChanged();
}

void LinksBagManager::SetLogged(const bool logged)
{
    m_IsLogged = logged;
    emit loggedChanged();
}

void LinksBagManager::thumbnailReceived(QNetworkReply *pReply)
{
    if (!pReply)
    {
        return;
    }

    if (pReply->error() == QNetworkReply::NoError)
    {
        QString bookmarkId = m_ThumbnailUrls.value(pReply->url(), "");
        QThreadPool::globalInstance()->start(new DownloadedImageHandler(pReply,
                bookmarkId, m_BookmarksModel));
    }
    m_ThumbnailUrls.remove(pReply->url());
}

void LinksBagManager::handleUpdateBookmarkCount()
{
    m_OfflineDownloaderQueueSize = m_OfflineDownloader->GetBookmarkCount();
    emit downloaderQueueSizeChanged();
}

void LinksBagManager::handleUpdateArticleContent(const QString& id, const QString& pubDate,
        const QString& content)
{
    updatePublishDate(id, pubDate);
    updateContent(id, content);
    emit downloadedBookmarksCountChanged();
}

void LinksBagManager::handleUpdateImageContent(const QString& id, const QImage& imageContent)
{
    updateContent(id, imageContent);
    emit downloadedBookmarksCountChanged();
}

void LinksBagManager::obtainRequestToken()
{
    SetBusy(true);
    m_Api->ObtainRequestToken();
}

void LinksBagManager::requestAccessToken()
{
    SetBusy(true);
    m_Api->RequestAccessToken();
}

void LinksBagManager::filterBookmarks(const QString &text)
{
    m_FilterProxyModel->setFilterRegExp(text);
}

void LinksBagManager::loadBookmarksFromCache()
{
    QSettings settings(Application::GetPath(Application::CacheDirectory) +
            "/linksbag_cache", QSettings::IniFormat);
    const int size = settings.beginReadArray("Bookmarks");
    Bookmarks_t bookmarks;
    for (int i = 0; i < size; ++i)
    {
        settings.setArrayIndex(i);
        QByteArray data = settings.value("SerializedData").toByteArray();
        auto bm = Bookmark::Deserialize(data);
        if (!bm->IsValid())
        {
            qWarning() << Q_FUNC_INFO
                    << "unserializable entry"
                    << i;
            continue;
        }
        bookmarks << bm;
    }
    settings.endArray();

    m_BookmarksModel->SetBookmarks(bookmarks);
    m_FilterProxyModel->sort(0, Qt::DescendingOrder);
}

void LinksBagManager::saveBookmarks()
{
    const auto& bookmarks = m_BookmarksModel->GetBookmarks();
    if (bookmarks.isEmpty())
        return;

    QSettings settings(Application::GetPath(Application::CacheDirectory) +
            "/linksbag_cache", QSettings::IniFormat);
    settings.beginWriteArray("Bookmarks");
    for (int i = 0, size = bookmarks.size(); i < size; ++i)
    {
        settings.setArrayIndex(i);
        settings.setValue("SerializedData", bookmarks.at(i)->Serialize());
    }
    settings.endArray();
    settings.sync();
}

void LinksBagManager::refreshBookmarks()
{
    SetBusy(true);
    m_Api->LoadBookmarks(ApplicationSettings::Instance(this)->
            value("lastUpdate", 0).toLongLong());
}

void LinksBagManager::updateOfflineDownloaderQueue()
{
    QMetaObject::invokeMethod(m_OfflineDownloader, "SetBookmarks", Qt::QueuedConnection,
            Q_ARG(Bookmarks_t, m_BookmarksModel->GetBookmarks()));
}

void LinksBagManager::removeBookmark(const QString& id)
{
    SetBusy(true);
    m_Api->RemoveBookmarks({ id });
}

void LinksBagManager::removeBookmarks(const QStringList& ids)
{
    SetBusy(true);
    m_Api->RemoveBookmarks(ids);
}

void LinksBagManager::markAsFavorite(const QString& id, bool favorite)
{
    SetBusy(true);
    m_Api->MarkBookmarksAsFavorite({ id }, favorite);
}

void LinksBagManager::markAsRead(const QString& id, bool read)
{
    SetBusy(true);
    m_Api->MarkBookmarksAsRead({ id }, read);
}

void LinksBagManager::markAsFavorite(const QStringList& ids, bool favorite)
{
    SetBusy(true);
    m_Api->MarkBookmarksAsFavorite(ids, favorite);
}

void LinksBagManager::markAsRead(const QStringList& ids, bool read)
{
    SetBusy(true);
    m_Api->MarkBookmarksAsRead(ids, read);
}

void LinksBagManager::updateTags(const QString& id, const QString& tags)
{
    SetBusy(true);
    m_Api->UpdateTags(id, tags);
}

void LinksBagManager::updateContent(const QString& id, const QString& content)
{
    QThreadPool::globalInstance()->start(new DownloadedContentHandler(id,
            content, m_BookmarksModel));
}

void LinksBagManager::updateContent(const QString& id, const QImage& imageContent)
{
    QThreadPool::globalInstance()->start(new DownloadedContentHandler(id,
            imageContent, m_BookmarksModel));
}

void LinksBagManager::updatePublishDate(const QString& id, const QString& date)
{
    m_BookmarksModel->UpdatePublishDate(id, date);
}

QString LinksBagManager::getContent(const QString& id) {

    QString filePath(Application::GetPath(Application::ArticleCacheDirectory) + id + ".html");
    if (!QFile::exists(filePath))
    {
        filePath = Application::GetPath(Application::ArticleCacheDirectory) + id;
        if (!QFile::exists(filePath))
        {
            filePath = "";
        }
    }

    if (filePath.isEmpty())
    {
        return "";
    }

    QFile file(filePath);
    if(!file.open(QIODevice::ReadOnly))
    {
        return "";
    }

    QTextStream in(&file);
    QString content;

    while(!in.atEnd())
    {
        content += in.readLine();
    }
    file.close();
    return content;
}

QUrl LinksBagManager::getContentUri(const QString& id)
{
    return Application::GetPath(Application::ArticleCacheDirectory) + id;
}

void LinksBagManager::resetAccount()
{
    ApplicationSettings::Instance(this)->remove("syncOnStartup");
    ApplicationSettings::Instance(this)->remove("lastUpdate");
    ApplicationSettings::Instance(this)->remove("bookmarksViewItemSize");
    ApplicationSettings::Instance(this)->remove("parser");
    ApplicationSettings::Instance(this)->remove("showSearchField");
    ApplicationSettings::Instance(this)->remove("userName");
    ApplicationSettings::Instance(this)->remove("accessToken");
    ApplicationSettings::Instance(this)->remove("useBestView");
    ApplicationSettings::Instance(this)->remove("showContentType");
    ApplicationSettings::Instance(this)->remove("mobileBrowser");
    ApplicationSettings::Instance(this)->remove("backgroundSyncPeriod");
    ApplicationSettings::Instance(this)->remove("showBackgroundImage");
    ApplicationSettings::Instance(this)->remove("statusFilter");
    ApplicationSettings::Instance(this)->remove("contentTypeFilter");

    m_Api->ResetAccount();

    QSettings settings(Application::GetPath(Application::CacheDirectory) +
            "/linksbag_cache", QSettings::IniFormat);
    settings.remove("Bookmarks");
    settings.sync();
    resetArticleCache();
    resetThumbnailCache();

    // fix logout
    QDir webkitCache(Application::GetPath(Application::CacheDirectory) + "/.QtWebKit");
    webkitCache.removeRecursively();
    webkitCache = QDir(Application::GetPath(Application::AppDataDirectory) + "/.QtWebKit");
    webkitCache.removeRecursively();

    m_BookmarksModel->Clear();

    SetLogged(false);
}

void LinksBagManager::resetArticleCache()
{
    // remove directory
    QDir article(Application::GetPath(Application::ArticleCacheDirectory));
    article.removeRecursively();

    // recreate directory
    article.mkpath(Application::GetPath(Application::ArticleCacheDirectory));

    emit articlesCacheReset();
    emit downloadedBookmarksCountChanged();
}

void LinksBagManager::resetThumbnailCache()
{
    // remove directories
    QDir cache(Application::GetPath(Application::ThumbnailCacheDirectory));
    cache.removeRecursively();
    cache = QDir(Application::GetPath(Application::CoverCacheDirectory));
    cache.removeRecursively();

    // recreate directories
    cache.mkpath(Application::GetPath(Application::ThumbnailCacheDirectory));
    cache.mkpath(Application::GetPath(Application::CoverCacheDirectory));
}

void LinksBagManager::handleGotAuthAnswer(const QString& data)
{
    if (data.contains("/linksbag_authorization"))
    {
        m_Api->RequestAccessToken();
    }
}

void LinksBagManager::restartSyncTimer()
{
    const int period = ApplicationSettings::Instance(this)->value("backgroundSyncPeriod", "-1").toInt();

    if (period == -1)
    {
        m_SyncTimer->stop();
        return;
    }

    const qint64 lastSync = ApplicationSettings::Instance(this)->value("lastUpdate", 0).toLongLong();
    if (QDateTime::currentDateTime().toTime_t() - lastSync > period)
    {
        refreshBookmarks();
    }

    m_SyncTimer->start(period * 1000);
}

void LinksBagManager::handleUnreadOnlyDownloaderChanged(bool unreadOnly)
{
    emit unreadOnlyDownloaderEnabled(unreadOnly);
}

void LinksBagManager::handleWifiOnlyDownloaderChanged(bool wifiOnly)
{
    emit wifiOnlyDownloaderEnabled(wifiOnly);
}

void LinksBagManager::handleOfflineyDownloaderChanged(bool offlineDownloader)
{
    emit offlineDownloaderEnabled(offlineDownloader);
}
} // namespace LinskBag


text:
"""
Default experiment for clean smp

Should be self-contained requiring now external packages or processes.

Robot: Point mass
World: open linear (1D) space
 Task: go to a goal position and stay there
Brain: taxis
 Loss: mean squared error / goal distance
"""

import time
from smq.utils  import make_column_names_numbered, make_expr_id, make_robot_name
from smq.worlds import RobotWorld
from smq.robots import SimpleRandomRobot, PointmassRobot
from smq.plot   import PlotTimeseries
from smq.tasks  import NullTask, SetpointTask, GoalTask, GoalTaskTaxis
from smq.brains import NullBrain, TaxisBrain

# local variables for re-use
numsteps = 1000
motors   = 1
name = "taxis_1d"
expr_id = make_expr_id(name)

# using dict convention seemed to be the best over yaml and friends
conf = {
    # first level corresponds to experiment
    "numsteps": numsteps,
    "id": "%s-%s" % (name, time.strftime("%Y%m%d-%H%M%S")),
    # these are arrays of dicts specifying components
    "robots": [
        {
            "class": PointmassRobot, # SimpleRandomRobot,
            "type": "explauto",
            "name": make_robot_name(expr_id, "pm", 0),
            # dimensions of different subparts of sm vector
            # make that more compact / automatically inferred
            # actually: make that lists of names whose length is the dim
            "dim_s_proprio": make_column_names_numbered("acc", motors),
            "dim_s_extero": make_column_names_numbered("vel", motors),
            "dim_s_intero": make_column_names_numbered("vel_", motors) + make_column_names_numbered("pos_", motors) + make_column_names_numbered("vel_goal", motors) + make_column_names_numbered("vel_error", motors),
            "dim_s_reward": make_column_names_numbered("dist_goal", 1),
            "dim_s_pred": make_column_names_numbered("acc_pred", motors),
            "dim_s_motor": make_column_names_numbered("m", motors),
            # above is not enough, need either full dict / access variable by column name
            #                   OR dict mapping variable name to numerical index (HACK?)

            "numsteps": numsteps,
            "control": "force",
            "ros": False,
            "brains": [
                {
                    "class": TaxisBrain,
                    "name": "taxisbrain",
                    "dim_s_motor": motors,
                    "variant": "binary_threshold", # "continuous_linear"
                    "continuous_gain": 1.5,
                    "binary_threshold": 0.2,
                    "binary_high_range": 1.0,
                    "binary_low_range": 0.01,
                    # tasks be of length either one or same as len(robots)
                    "tasks": [
                        {
                            "class": GoalTaskTaxis,
                            "name": "goaltasktaxis",
                            "goalspace": "s_extero",
                            "goaldim": motors,
                            "goalinteroindex": 2,
                            "loss": "mse",
                        }
                    ],
                },
            ],
        }
    ],
    "worlds": [
        {"class": RobotWorld,
         "dt": 0.1,
         "map": "open_planar_isotropic",
         "dim": 0,
         "numsteps": numsteps,
        }
    ],
    "loss": "mse",
    "analyses": [
        {
            "class": PlotTimeseries,
            "name": "plottimeseries",
            "type": "seaborn" # "pyplot"
        },
    ],
    }

redpajama_set_name: RedPajamaGithub


text:
package com.siyeh.ig.imports;

import javax.annotation.Nonnull;

import com.intellij.psi.*;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;

public class OnDemandImportInspection extends BaseInspection {

  @Nonnull
  public String getDisplayName() {
    return InspectionGadgetsBundle.message("import.display.name");
  }

  @Nonnull
  public String buildErrorString(Object... infos) {
    return InspectionGadgetsBundle.message("import.problem.descriptor");
  }

  public BaseInspectionVisitor buildVisitor() {
    return new PackageImportVisitor();
  }

  private static class PackageImportVisitor extends BaseInspectionVisitor {

    @Override
    public void visitClass(@Nonnull PsiClass aClass) {
      // no call to super, so it doesn't drill down
      final PsiElement parent = aClass.getParent();
      if (!(parent instanceof PsiJavaFile)) {
        return;
      }
      final PsiJavaFile file = (PsiJavaFile)parent;
     /* if (JspPsiUtil.isInJspFile(aClass.getContainingFile())) {
        return;
      }  */
      if (!file.getClasses()[0].equals(aClass)) {
        return;
      }
      final PsiImportList importList = file.getImportList();
      if (importList != null) {
        final PsiImportStatement[] importStatements =
          importList.getImportStatements();
        for (PsiImportStatement importStatement : importStatements) {
          if (importStatement.isOnDemand()) {
            registerError(importStatement);
          }
        }
      }
    }
  }
}


text:
layout: post
title:  "Salinas Lapas"
date:   2015-10-24 15:39:40
preview: /Propiedades/venta/Salinas/1.jpg
---

$165,000

Se liquida, 50 cuerdas de terreno ideal para desarrollo (antes contaba con permisología de uso) Tiene una casa pequeña de 2 habitaciones - 1 baño con 400pies cuadrados. Acceso directo a la #1 y a pasos de PR-52. Llama HOY!! Edgar Acosta 787 645 2084


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />

    <title>7.7. motor system</title>

  <link href="../../_static/styles/theme.css?digest=1999514e3f237ded88cf" rel="stylesheet">
<link href="../../_static/styles/pydata-sphinx-theme.css?digest=1999514e3f237ded88cf" rel="stylesheet">

  <link rel="stylesheet"
    href="../../_static/vendor/fontawesome/5.13.0/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">

    <link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
    <link rel="stylesheet" href="../../_static/styles/sphinx-book-theme.css?digest=62ba249389abaaa9ffc34bf36a076bdc1d65ee18" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../../_static/togglebutton.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/copybutton.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/mystnb.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/sphinx-thebe.css" />
    <link rel="stylesheet" type="text/css" href="../../_static/design-style.b7bb847fb20b106c3d81b95245e65545.min.css" />

  <link rel="preload" as="script" href="../../_static/scripts/pydata-sphinx-theme.js?digest=1999514e3f237ded88cf">

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="7.8. development" href="development.html" />
    <link rel="prev" title="7.6. memory" href="memory.html" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="docsearch:language" content="None">

<input type="checkbox" class="sidebar-toggle" name="__navigation" id="__navigation" aria-label="Toggle navigation sidebar">

Toggle navigation sidebar

<input type="checkbox" class="sidebar-toggle" name="__page-toc" id="__page-toc" aria-label="Toggle in-page Table of Contents">

Toggle in-page Table of Contents

<form class="bd-search d-flex align-items-center" action="../../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form>

                    overview 👋

   1. research_ovws

  <input class="toctree-checkbox" id="toctree-checkbox-1" name="toctree-checkbox-1" type="checkbox"/>

     1.1. comp neuro

     1.2. transfer learning

     1.3. disentanglement

     1.4. omics

     1.5. complexity

     1.6. interesting science

     1.7. dl theory

     1.8. scattering transform

     1.9. ml in medicine

     1.10. transformers

     1.11. causal inference

     1.12. dl for neuro

     1.13. uncertainty

     1.14. interpretability

     1.15. generalization

   2. cs

  <input class="toctree-checkbox" id="toctree-checkbox-2" name="toctree-checkbox-2" type="checkbox"/>

     2.1. info retrieval

     2.2. data structures

     2.3. languages

     2.4. software engineering

     2.5. quantum

     2.6. algorithms

     2.7. graphs

     2.8. os

     2.9. architecture

     2.10. reproducibility

     2.11. cs theory

   3. math

  <input class="toctree-checkbox" id="toctree-checkbox-3" name="toctree-checkbox-3" type="checkbox"/>

     3.1. differential equations

     3.2. proofs

     3.3. real analysis

     3.4. linear algebra

     3.5. signals

     3.6. optimization

     3.7. calculus

     3.8. chaos

     3.9. math basics

   4. stat

  <input class="toctree-checkbox" id="toctree-checkbox-4" name="toctree-checkbox-4" type="checkbox"/>

     4.1. graphical models

     4.2. data analysis

     4.3. testing

     4.4. causal inference

     4.5. info theory

     4.6. linear models

     4.7. time series

     4.8. game theory

   5. ml

  <input class="toctree-checkbox" id="toctree-checkbox-5" name="toctree-checkbox-5" type="checkbox"/>

     5.1. kernels

     5.2. nlp

     5.3. computer vision

     5.4. structure learning

     5.5. classification

     5.6. unsupervised

     5.7. deep learning

     5.8. feature selection

     5.9. learning theory

     5.10. evaluation

   6. ai

  <input class="toctree-checkbox" id="toctree-checkbox-6" name="toctree-checkbox-6" type="checkbox"/>

     6.1. search

     6.2. decisions, rl

     6.3. fairness, sts

     6.4. cogsci

     6.5. ai futures

     6.6. logic

     6.7. philosophy

     6.8. psychology

     6.9. representations

   7. neuro

  <input checked="" class="toctree-checkbox" id="toctree-checkbox-7" name="toctree-checkbox-7" type="checkbox"/>

     7.1. disease

     7.2. brain basics

     7.3. vision

     7.4. comp neuro

     7.5. sensory input

     7.6. memory

     7.7. motor system

     7.8. development

            Powered by Jupyter Book

<button onclick="toggleFullScreen()"
  class="headerbtn"
  data-toggle="tooltip"
data-placement="bottom"
title="Fullscreen mode"
>

</button>

  <button class="headerbtn menu-dropdown__trigger"
      aria-label="Download this page">

  </button>

.md

<button onclick="printPdf(this)"
  class="headerbtn"
  data-toggle="tooltip"
data-placement="left"
title="Print to PDF"
>

.pdf
</button>

         Contents

   7.7.1. 16 lower

   7.7.2. 17 upper

   7.7.3. 18 basal ganglia (choose what you want to do)

   7.7.4. 19 cerebellum (fine tuning all your motion)

   7.7.5. 20 eye movements/integration

   7.7.6. 21 visceral (how you control organs, stress levels, etc.)

motor system

 Contents

   7.7.1. 16 lower

   7.7.2. 17 upper

   7.7.3. 18 basal ganglia (choose what you want to do)

   7.7.4. 19 cerebellum (fine tuning all your motion)

   7.7.5. 20 eye movements/integration

   7.7.6. 21 visceral (how you control organs, stress levels, etc.)

7.7. motor system#

notes from Neuroscience, 5th edition + Intro to neurobiology course at UVA

7.7.1. 16 lower#

sensory in dorsal spinal cord, motor in ventral

farther out neurons control farther out body parts (medial=trunk, lateral=arms,legs)

one motor neuron (MN) innervates multiple fibers

the more fibers/neuron, the less precise

MN pool - group of MNs=motor units

muscle tone = all your muscles are a little on, kind of like turning on the car engine and when you want to, you can move forward

more firing = more contraction

MN types

fast fatiguable - white muscle

fast fatigue-resistant

slow - red muscles, make atp

muscles are innervated by a proportion of these MNs

reflex

whenever you get positive signal on one side, also get negative on other

flexor - curl in (bicep)

extensor - extend (tricep)

proprioceptors (+) - measure length - more you stretch, more firing of alpha MN to contract

intrafusal muscle=spindle - stretches the proprioceptor so that it can measure even when muscle is already stretched

\(\gamma\) motor neuron - adjusts intrafusal muscles until they are just right

keeps muscles tight so you know how much muscle is streteched

if alpha fires a lot, gamma will increase as well

high gamma allows for fast responsiveness - brainstem modulators (serotonin) also do this

opposes muscle stretch to keep it fixed

spindle -> activates muscles -> contracts -> turns off

sensory neurons / gamma MNs innervate muscle spindle

homonymous MNs go into same muscle, antagonistic muscle pushes other way

golgi tendon (-) measures pressure not stretch

safety switch

inhibits homonymous neuron so you don't rip muscle off

ALS = Lou Gehrig's disease

MNs are degenerating - reflexes don't work

progressive loss of \(\alpha\) MNs

last neuron to go is superior rectus muscle -> people use eyes to talk with tracker

CPG = central pattern generator

ex. step on pin, lift up leg

walking works even if you cut cat's spinal cord

collection of interneurons

7.7.2. 17 upper#

cAMP is used by GPCR

lift and hold circuit

ctx->lateral white matter->lateral ventral horn->limb muscles

lateral white matter - most sensitive to injury

brainstem->medial white matter->medial horn->trunk

medial white matter -> goes into trunk

bulbarspinal tracts

lateral and medial vestibulospinal tracts - feedback

automated system - not much thinking

posture - reflex

too slow for learning surfing

reticular - feedforward = anticipate things before they happen

command / control system for trunk muscles (posture)

feedforward - not a reflex, lean back before opening drawer

caudal pontine - feeds into spinal cord

colliculospinal tract

has superior colliculus - eye muscles, neck-looking

see ch. 20 - reflex

corticular bulbar tract (premotor->primary motor->brainstem)

motor cortexes - this info is descending

can override reticular reflexes in reticular formation

premotor cortex (P2) - contains all actions you can do

has mirror neurons that fire ahead of primary neurons

fire if you think about it or if you do it

primary motor cortex (P1)

layer 1 ascending

layer 4 input

layer 5 - Betz cells - behave like 6 (output)

layer 6 - descending output

has map like S1 does

Jacksonian march get seizure that goes from feet to face (usually one side)

epileptic seizure - neurons fire too much and fire neurons near them

insular - flashes of moods

pyriform - flashes of smells

Betz cells - if they fire, you will do something

dictate a goal, not single neuron to fire

axons to ventral horn of spinal cord

lesions

upper

spasticity - unorganized leg motions

increased tone - tight muscles

hyperactive deep reflexes

ex. babinski's sign

curl foot down a lot because you don't know how much to curl

curling foot down = normal plantar

more serotonin can cause this

lower

hypoactive deep reflexes

decreased tone

severe muscle atrophy

pathways

Betz cell

90% cross midline in brainstem - control limbs

10% don't cross - trunk muscles

7.7.3. 18 basal ganglia (choose what you want to do)#

"who you are"

outputs

brainstem

motor cortex

4 loops (last 2 aren't really covered)

motor loops

body movement loop

SnC -> S (CP) -> (-) Gp -> (-) VA/VL -> motor cortex

oculomotor loop

cortex -> caudate -> substantia nigra pars reticulata -> superior colliculus

non-motor loops
3. prefrontal loop - daydreaming (higher-order function)

spiny neurons corresponding to a silly idea (alien coming after you) filtered out because not fired enough

schizophrenia - can't filter that out

limbic loop - mood

has nucleus accumbens

can make mood better with dopamine

substantia nigra

pars compacta - dopaminergic neurons (input to striatum)

more dopamine = more strength between cortical pyramidal neurons and spiny neurons (turns up the gain)

dopamine helps activate a spiny neuron

may be the ones that learn (positive outcome is saved, will result in more dopamine later)

Parkinson's - specific loss of dopaminergic neurons

dopaminergic neurons form melanin = dark color

when you get down to 20% what you were born with

know what they need to do - don't have enough dopamine to act

treat with L Dopa -> something like dopamine -> take out globus pallidus

cocaine, amphetamine - too much dopamine

Huntington's - death of specific class of spiny neurons

have uncontrolled actions

Tourette's - too much dopamine

also alcohol

MPPP (synthetic heroin)

MPTP looks like dopamine but turns into MPP and kills dopaminergic neurons

treated with L Dopa to reactivate spiny neurons

pars reticulata

doesn't have dopamine (output from striatum)

striatum contains spiny neurons

caudate (for vision) - output to globus pallidus and substantia nigra (pars reticulata)

putamen - output only to globus pallidus

each spiny neuron gets input from ~1000 cortical pyramidal cells

globus pallidus

each spiny neuron connects to one globus pallidus neuron

deja vu - spiny neuron you haven't fired in a while

VA/VL (thalamus)

all motor actions must go through here before cortex

has series of commands of all actions you can do

has parallel set of betz cells that will illicit those actions

VA/VL is always firing, globus pallidus inhibits it (tonic connection)

7.7.4. 19 cerebellum (fine tuning all your motion)#

redundant system - cortex could do all of this, but would be slow

repeated circuit - interesting for neuroscientists

all info comes in, gets processed and goes back out

cerebellum gets motor efferant copy

all structures on your brain that do processing send out efferent

cerebellum sends efferant copy back to itself with time delay (through inferior olive)

cerebrocerebellum

deals with premotor cortex (mostly motor cortex)

spinocerebellum = clarke's nucleus, knows stretch of every muscle, many proprioceptors go straight into here

motor cortex

has a map of muscles

vestibular cerebellum - vestibular->cerebellum->vestibular

vestibular system leans you back but if wind blows, have to adjust to that

input

pontine nuclei (from cortex)

vestibular nuclei (balance)

cuneate nucleus (somatosensory from spinal upper body)

clarke (proprio from spinal lower body)

processing

cerebellar deep nuclei

output

deep cerebellar nuclei

go to superior colliculus, reticular formation

VA/VL (thalamus) - back to cortex

red nucleus

circuit 1 - fine-tuning

circuit 2 - detects differences, adjusts

cerebellum -> red nucleus (is an efferant copy) -> inferior olive -> cerebellum

compare new copy to old copy

cells

purkinje cells - huge number of dendrite branches		- dead planar allows good imaging

GABAergic

(input) mossy fibers -(+)> granule cells (send parallel fibers) -(+)> purkinje cell -(-)> deep cerebellar nuclei (output)

mossy->granule->parallel fibers connect to ~100,000 parallel fibers

climbing fiber - comes from inferior olive and goes back to purkinje cell (this is the efferent copy) = training signal

loops

deep excitatory loop (climbing/mossy) -(+)-> deep cerebellar nuclei

cortical inhibitory loop (climbing/granule) -(+)-> purkinje

the negative is from purkinje to deep cerebellar nuclei

alcohol

can create gaps = folia

long-term use causes degeneration = ataxia (lack of coordination)

7.7.5. 20 eye movements/integration#

Broca's view - look at people with problems

Ramon y Cajal - look at circuits

5 kinds of eye movements

saccades

use cortex, superior colliculus (visual info -> LGN -> cortex, 10% goes to brainstem)

constantly moving eyes around (fovea)

~scan at 30 Hz

5 Hz=200 ms for cortex to process so pause eyes (get 5-6 images)

there is a little bit of drift

can't control this

humans are better than other animals at seeing things that aren't moving

VOR - vestibular ocular reflex - keeps eyes still

use vestibular system, occurs in comatose

fast

works better if you move your head fast

optokinetic system - tracks with eyes

ex. stick head out window of car and track objects as they go by

slower than VOR (takes 200 ms)

works better if slower

reflex

in cortex (textbooks) but probs brainstem (new)

smooth pursuit - can track things moving very fast

suppress saccades and track smoothly

only in higher apes

area MT is highest area of motion coding and goes up and comes down multiple ways

high speed processing isn't understood

could be retina processing

vergence - crossing your eyes

suppresses conjugate eye movements

we can control this

only humans - bring objects up very close

reading uses this

eye muscles

rectus

vertical

superior

inferior

use complicated vertical gaze center

last to degenerate in ALS

locked-in syndrome - can only move eyes vertically

controls oculomotor nucleus

lateral

medial

lateral (controlled by abducens)

use horizontal gaze center=PPRF which talk to abducens
-MLF connects abducents to opposite medial lateral rectus muscle

oblique - more circular motions

superior (controlled by trochlear nucleus)

inferior

everything else controlled by oculomotor nucleus

superior colliculus has visual map

controls saccades, connects to gaze centers

takes input from basal ganglia (oculomotor loop)

also gets audio input from inferior colliculus (hear someone behind you and turn)

gets strokes

redundant with frontal eye field in secondary motor cortex

connects to superior colliculus, gaze center, and comes back

if you lose one of these, the other will replace it

if you lose both, can't saccade to that side

7.7.6. 21 visceral (how you control organs, stress levels, etc.)#

parasympathetic works against sympathetic

divisions

sympathetic - fight-or-flight (adrenaline)

functions

neurons to smooth muscle

pupils dilate

increases heart rate

turn off digestive system

2 things with no parasympathetic counterpart

increase BP

sweat glands

location

neurons in spinal cord lateral horn

send out neurons to sympathetic trunk (along the spinal cord)

all outgoing connections are adrenergic

beta-adrenergic drugs block adrenaline

beta agonist - activates adrenaline receptors (do this before EKG)

parasympathetic - relaxing (ACh)

location

brainstem

edinger westphal nucleus - pupil-constriction

salivatory nucleus

vagus nucleus - digestive system, sexual function

nucleus ambiguous - heart

nucleus of the solitary tract
- all input/output goes through this
1. rostral part (front) - taste neurons
2. caudal part (back) contains all sensory information of viscera (ex. BP, heart rate, sexual

sacral spinal cord (bottom) - gut/bladder/genitals

not parallel to sympathetic – poor design - may cause stress-associated diseases

hard to make drugs with ACh

enteric nervous system - in your gut

takes input through vagus nerve from vagus nucleus

also has sensory neurons and sends afferents back to brainstem

pathway

insular cortex - what you care about

amygdala - contains emotional memories

hypothalamus - controls a lot

mostly peptinergin neurons

aging, digestion, mood, straight to bloodstream & CNS

releases hormones

ex. leptin - stops you eating when you eat calories

reticular formation - feedforward, prepares digestion before we eat

three examples

heart rate

starts at nucleus ambiguous

also takes input from chemoreceptors (ex. pH)

SA node at heart generates heartbeat - balances Ach and adrenaline

sympathetic sends info from thoracic spinal cord

heart sends back baroreceptor afferents

bladder function

parasympathetic in sacral lateral horn make you pee (contracts bladder)

turn off sympathetic NS

open sphincter muscle (voluntary)

can also control this via skeletal nervous system

circuit

amygdala (can't pee when nervous)

pontine micturation center -> parasympathetic preganglionic neurons -> parasympathetic ganglionic neurons

inhibitory local circuit neurons -> somatic MNs

sexual function

Viagra turns on parasympathetic NS

also gives temporal color blindness

sympathetic involved in ejaculation

temporal correlation ("Point and Shoot")

previous

7.6. memory

next

7.8. development

    By Chandan Singh

      © Copyright None.

Many of these images are taken from resources on the web.


text:
package org.ddpush.im.v1.node;

import org.ddpush.im.v1.node.udpconnector.UdpConnector;

import java.util.ArrayList;

public class Messenger implements Runnable {

    private UdpConnector connector;

    //this is very large and dynamic
    private NodeStatus nodeStat;
    private Thread hostThread;

    boolean started = false;
    boolean stoped = false;

    public Messenger(UdpConnector connector, NodeStatus nodeStat) {
        this.connector = connector;
        this.nodeStat = nodeStat;
    }

    @Override
    public void run() {
        this.started = true;

        while (stoped == false) {
            try {
                procMessage();
            } catch (Exception e) {
                e.printStackTrace();
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }

    }

    public void stop() {
        this.stoped = true;
    }

    private void procMessage() throws Exception {
        ClientMessage m = this.obtainMessage();
        if (m == null) {
            try {
                Thread.sleep(5);
            } catch (Exception e) {
            }
            return;
        }

        this.deliverMessage(m);

    }

    private void deliverMessage(ClientMessage m) throws Exception {
        //System.out.println(this.hostThread.getName()+" receive:"+StringUtil.convert(m.getData()));
        //System.out.println(m.getSocketAddress().getClass().getName());
        String uuid = m.getUuidHexString();
        //ClientStatMachine csm = NodeStatus.getInstance().getClientStat(uuid);
        ClientStatMachine csm = nodeStat.getClientStat(uuid);
        if (csm == null) {
            csm = ClientStatMachine.newByClientTick(m);
            if (csm == null) {
                return;
            }
            nodeStat.putClientStat(uuid, csm);
        }
        ArrayList<ServerMessage> smList = csm.onClientMessage(m);
        if (smList == null) {
            return;
        }
        for (int i = 0; i < smList.size(); i++) {
            ServerMessage sm = smList.get(i);
            if (sm.getSocketAddress() == null) continue;
            this.connector.send(sm);
        }

    }

    private ClientMessage obtainMessage() throws Exception {
        return connector.receive();
    }

    public void setHostThread(Thread t) {
        this.hostThread = t;
    }

    public Thread getHostThread() {
        return this.hostThread;
    }

}


text:
package com.os.comment.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.*;
import java.io.File;

/**
 * 图片处理工具类
 * @author Administrator
 * 2015-5-18
 */
public class ImageUtils {

	public static void main(String[] args) {
		//放大缩小图片
		scaler("e:/1.jpg","e:/2.jpg",2,false,"jpg");//true放大  false缩小
		//裁剪图片
		cut("e:/1.jpg","e:/3.jpg",100,100,500,500,"jpg");
		//格式转换
		convert("e:/1.jpg", "gif", "e:/4.jpg");
		//转换成黑白图片
		gray("e:/1.jpg","e:/5.jpg","jpg");
		//添加水印文字
		pressText("我是水印文字","e:/1.jpg","e:/1.jpg","宋体",Font.BOLD,Color.white,50, 100, 100, 0.5f,"jpg");
		//添加水印图片
		pressImage("e:/添加水印.jpg", "e:/1.jpg","e:/7.jpg", 0, 0, 0.5f,"jpg");
		//固定图片宽高
		fixed("e:/添加水印.jpg","e:/添加水印.jpg",100,100,"jpg");
	}

	/**
	 * 图片放大缩小
	 * @param oldPath 源图片路径
	 * @param newPath 处理后图片的路径
	 * @param scale 倍数
	 * @param flag true放大  false缩小
	 */
	public static void scaler(String oldPath,String newPath,int scale,boolean flag,String imgType){
		try {
			BufferedImage img=ImageIO.read(new File(oldPath));
			int width=img.getWidth();
			int height=img.getHeight();
			if(flag==true){//放大
				width=width*scale;
				height=height*scale;
			}else{//缩小
				 width=width/scale;
	             height=height/scale;
			}
			Image image = img.getScaledInstance(width, height,Image.SCALE_SMOOTH);
			BufferedImage outputImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
            Graphics graphics = outputImage.getGraphics();
            graphics.drawImage(image, 0, 0, null);// 绘制处理后的图
            graphics.dispose();
            ImageIO.write(outputImage, imgType, new File(newPath));
            System.out.println("处理成功");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	/**
	 * 图片固定宽高
	 * @param oldPath 源文件
	 * @param newPath 处理后的文件
	 * @param width 宽
	 * @param height 高
	 * @param imgType 图片类型
	 */
	public static void fixed(String oldPath,String newPath,int width,int height,String imgType){
		try {
			BufferedImage img=ImageIO.read(new File(oldPath));
			Image image = img.getScaledInstance(width, height,Image.SCALE_SMOOTH);
			BufferedImage outputImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
            Graphics graphics = outputImage.getGraphics();
            graphics.drawImage(image, 0, 0, null);// 绘制处理后的图
            graphics.dispose();
            ImageIO.write(outputImage, imgType, new File(newPath));
            System.out.println("处理成功");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	/**
	 * 图像裁剪
	 * @param oldPath 源图片路径
	 * @param newPath 处理后图片路径
	 * @param x 切片x坐标起点
	 * @param y 切片y坐标起点
	 * @param width 切片宽度
	 * @param height 切片高度
	 */
	public static void cut(String oldPath, String newPath,int x, int y, int width, int height,String imgType) {
        try {
            // 读取源图像
            BufferedImage bi = ImageIO.read(new File(oldPath));
            int srcWidth = bi.getHeight(); // 源图宽度
            int srcHeight = bi.getWidth(); // 源图高度
            if (srcWidth > 0 && srcHeight > 0) {
                Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_SMOOTH);
                // 四个参数分别为图像起点坐标和宽高
                // 即: CropImageFilter(int x,int y,int width,int height)
                ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
                Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(),cropFilter));
                BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图
                g.dispose();
                // 输出为文件
                ImageIO.write(tag,imgType, new File(newPath));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	/**
	 * 添加水印
	 * @param pressText 水印文字
	 * @param oldPath 源图片路径
	 * @param newPath 处理后的图片路径
	 * @param fontName 水印的字体名称
	 * @param fontStyle 水印的字体样式
	 * @param color 水印的字体颜色
	 * @param fontSize 水印的字体大小
	 * @param x 修正值
	 * @param y 修正值
	 * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
	 */
	public static void pressText(String pressText,String oldPath, String newPath, String fontName,int fontStyle, Color color,
		int fontSize,int x,int y, float alpha,String imgType) {
		try {
			File img = new File(oldPath);
			Image src = ImageIO.read(img);
			int width = src.getWidth(null);
			int height = src.getHeight(null);
			BufferedImage image = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D g = image.createGraphics();
			g.drawImage(src, 0, 0, width, height, null);
			g.setColor(color);
			g.setFont(new Font(fontName, fontStyle, fontSize));
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha));
			// 在指定坐标绘制水印文字
			g.drawString(pressText, (width - (getLength(pressText) * fontSize))
					/ 2 + x, (height - fontSize) / 2 + y);
			g.dispose();
			ImageIO.write((BufferedImage) image, imgType, new File(newPath));// 输出到文件流
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	 /**
     * 计算text的长度(一个中文算两个字符)
     * @param text
     * @return
     */
    public static int getLength(String text) {
        int length = 0;
        for (int i = 0; i < text.length(); i++) {
            if (new String(text.charAt(i) + "").getBytes().length > 1) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length / 2;
    }

    /**
     * 给图片添加图片水印
     * @param pressImg 水印图片
     * @param oldPath 源图像地址
     * @param newPath 目标图像地址
     * @param x 修正值。 默认在中间
     * @param y 修正值。 默认在中间
     * @param alpha 透明度:alpha 必须是范围 [0.0, 1.0] 之内(包含边界值)的一个浮点数字
     */
    public static void pressImage(String pressImg, String oldPath,String newPath,int x, int y, float alpha,String imgType) {
        try {
            File img = new File(oldPath);
            Image src = ImageIO.read(img);
            int wideth = src.getWidth(null);
            int height = src.getHeight(null);
            BufferedImage image = new BufferedImage(wideth, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();
            g.drawImage(src, 0, 0, wideth, height, null);
            // 水印文件
            Image src_biao = ImageIO.read(new File(pressImg));
            int wideth_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));
            g.drawImage(src_biao, (wideth - wideth_biao) / 2,
                    (height - height_biao) / 2, wideth_biao, height_biao, null);
            // 水印文件结束
            g.dispose();
            ImageIO.write((BufferedImage) image,  imgType, new File(newPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	/**
	 * 图像类型转换
	 * @param oldPath 源图片路径
	 * @param formatName 要转换的格式
	 * @param newPath 处理后的图片路径
	 */
	public static void convert(String oldPath, String formatName, String newPath) {
        try {
            File f = new File(oldPath);
            f.canRead();
            f.canWrite();
            BufferedImage src = ImageIO.read(f);
            ImageIO.write(src, formatName, new File(newPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	/**
	 * 图片转换成黑白
	 * @param oldPath
	 * @param newPath
	 */
	public static void gray(String oldPath, String newPath,String imgType) {
		try {
			BufferedImage src = ImageIO.read(new File(oldPath));
			ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
			ColorConvertOp op = new ColorConvertOp(cs, null);
			src = op.filter(src, null);
			ImageIO.write(src, imgType, new File(newPath));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title></title>
  <link rel="stylesheet" media="screen" type="text/css" href="./style.css" />
  <link rel="stylesheet" media="screen" type="text/css" href="./design.css" />
  <link rel="stylesheet" media="print" type="text/css" href="./print.css" />

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

start

Mozilla and Java properties files

The Translate Toolkit can manage Java .properties files with the prop2po and po2prop tool. As part of the Mozilla localisation process, the moz2po tool handles the properties files along with the other files.

Features

 Fully manage Java escaping (Mozilla non-escaped form is also handled)

 Preserves the layout of the original source file in the translated version

Not implemented

 Does not fold access keys together as done in the Mozilla DTD format.

Examples

editmenu.label = "Edit"
saveas.label = "Save As"

References

 Java Properties Class load method describes the properties format.

 http://java.sun.com/dtd/properties.dtd - alternate <acronym title="Extensible Markup Language">XML</acronym> based property representation


text:
layout: post
title: Home alone
---

We've been in the new flat a little while now, and Hannah has started her job which means I spend the vast majority of my time alone. I'm job hunting and doing some housework, but that can only occupy so much of my time.

Being unemployed sucks

It's funny, you'd think I'd be able to embrace this time to do loads of stuff that I want to do, like more writing, software development projects and exercise but I feel like I can't 'waste' time doing things like that when I don't have a job. It's crippling in so many ways; I worry that if I don't get a job soon I'll wind up hating Didcot with the same passion that I hate Coventry, and for many the same reasons. There's not much to do, and I don't know anyone here. Not having anyone to talk to for most of the day has a shockingly large adverse effect, surprisingly quickly.


text:
#include <UnitTest++.h>
#include "texture_pool.h"

namespace
{
	struct Fixture
	{
		Fixture()
		{
			m_simpleInputs.push_back( std::make_pair( "a.png", 10.0 ) );
			m_simpleInputs.push_back( std::make_pair( "b.png", 15.0 ) );
			m_simpleInputs.push_back( std::make_pair( "c.png", 20.0 ) );
		}

		std::vector< Lxt::PathDate >	m_simpleInputs;
		std::vector< Lxt::PathDate >	m_emptyInputs;
		Lxt::TexturePool				m_tp;
	};
}

namespace Lxt
{
	// Skip these tests, this class is poo and should be removed ASAP.

	/*
	TEST_FIXTURE( Fixture, TexturePool_Empty )
	{
		bool updated = TexturePool::Link( m_emptyInputs, 0, false, m_tp );

		CHECK_EQUAL( false, updated );
		CHECK_EQUAL( 0, m_tp.GetTextures().size() );
	}

	TEST_FIXTURE( Fixture, TexturePool_Simple )
	{
		// Add three new items to empty pool
		bool updated = TexturePool::Link( m_simpleInputs, 0, false, m_tp );

		CHECK_EQUAL( true, updated );
		CHECK_EQUAL( 3, m_tp.GetTextures().size() );
	}

	TEST_FIXTURE( Fixture, TexturePool_AddEmpty )
	{
		// Add three new items to empty pool
		TexturePool::Link( m_simpleInputs, 0, false, m_tp );

		// Add empty pool, should remove entries
		bool updated = TexturePool::Link( m_emptyInputs, 0, false, m_tp );

		CHECK_EQUAL( updated,	true );
		CHECK_EQUAL( 0,			m_tp.GetTextures().size() );
	}

	TEST_FIXTURE( Fixture, TexturePool_AddSame )
	{
		// Add three new items to empty pool
		TexturePool::Link( m_simpleInputs, 0, false, m_tp );

		// Add same items with pool at a new date, should be no change
		bool updated = TexturePool::Link( m_simpleInputs, 30, false, m_tp );

		CHECK_EQUAL( updated,	false );
		CHECK_EQUAL( 3,			m_tp.GetTextures().size() );
	}

	TEST_FIXTURE( Fixture, TexturePool_AddSameButOneNewer )
	{
		// Add three new items to empty pool
		TexturePool::Link( m_simpleInputs, 0, false, m_tp );

		m_simpleInputs.erase( m_simpleInputs.begin() );
		m_simpleInputs.push_back( std::make_pair( "a.png", 30 ) );

		// Add newer
		bool updated = TexturePool::Link( m_simpleInputs, 20, false, m_tp );
		CHECK_EQUAL( updated,	true );
		CHECK_EQUAL( 3,			m_tp.GetTextures().size() );
	}

	TEST_FIXTURE( Fixture, TexturePool_Append )
	{
		// Add three new items to empty pool
		TexturePool::Link( m_simpleInputs, 0, false, m_tp );

		std::vector< Lxt::PathDate > appendage;
		appendage.push_back( std::make_pair( "d.png", 30 ) );

		// Add newer
		bool updated = TexturePool::Link( appendage, 20, true, m_tp );
		CHECK_EQUAL( updated,	true );
		CHECK_EQUAL( 4,			m_tp.GetTextures().size() );
	}
	*/
}


text:
package imports

import (
	. "reflect"
	"sync/atomic"
)

// reflection: allow interpreted code to import "sync/atomic"
func init() {
	Packages["sync/atomic"] = Package{
	Binds: map[string]Value{
		"AddInt32":	ValueOf(atomic.AddInt32),
		"AddInt64":	ValueOf(atomic.AddInt64),
		"AddUint32":	ValueOf(atomic.AddUint32),
		"AddUint64":	ValueOf(atomic.AddUint64),
		"AddUintptr":	ValueOf(atomic.AddUintptr),
		"CompareAndSwapInt32":	ValueOf(atomic.CompareAndSwapInt32),
		"CompareAndSwapInt64":	ValueOf(atomic.CompareAndSwapInt64),
		"CompareAndSwapPointer":	ValueOf(atomic.CompareAndSwapPointer),
		"CompareAndSwapUint32":	ValueOf(atomic.CompareAndSwapUint32),
		"CompareAndSwapUint64":	ValueOf(atomic.CompareAndSwapUint64),
		"CompareAndSwapUintptr":	ValueOf(atomic.CompareAndSwapUintptr),
		"LoadInt32":	ValueOf(atomic.LoadInt32),
		"LoadInt64":	ValueOf(atomic.LoadInt64),
		"LoadPointer":	ValueOf(atomic.LoadPointer),
		"LoadUint32":	ValueOf(atomic.LoadUint32),
		"LoadUint64":	ValueOf(atomic.LoadUint64),
		"LoadUintptr":	ValueOf(atomic.LoadUintptr),
		"StoreInt32":	ValueOf(atomic.StoreInt32),
		"StoreInt64":	ValueOf(atomic.StoreInt64),
		"StorePointer":	ValueOf(atomic.StorePointer),
		"StoreUint32":	ValueOf(atomic.StoreUint32),
		"StoreUint64":	ValueOf(atomic.StoreUint64),
		"StoreUintptr":	ValueOf(atomic.StoreUintptr),
		"SwapInt32":	ValueOf(atomic.SwapInt32),
		"SwapInt64":	ValueOf(atomic.SwapInt64),
		"SwapPointer":	ValueOf(atomic.SwapPointer),
		"SwapUint32":	ValueOf(atomic.SwapUint32),
		"SwapUint64":	ValueOf(atomic.SwapUint64),
		"SwapUintptr":	ValueOf(atomic.SwapUintptr),
	}, Types: map[string]Type{
		"Value":	TypeOf((*atomic.Value)(nil)).Elem(),
	},
	}
}


text:
import { styled as styledWithoutDefault } from '@material-ui/styles';
import defaultTheme from './defaultTheme';

const styled = (Component) => {
  const componentCreator = styledWithoutDefault(Component);

  return (style, options) =>
    componentCreator(style, {
      defaultTheme,
      ...options,
    });
};

export default styled;


text:
from __future__ import unicode_literals

import unittest

from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from django.test import TestCase, override_settings

@override_settings(DEBUG=True)
@unittest.skipUnless(connection.vendor == 'mysql', 'MySQL specific test.')
class MySQLTests(TestCase):

    @staticmethod
    def get_isolation_level(connection):
        with connection.cursor() as cursor:
            cursor.execute("SELECT @@session.tx_isolation")
            return cursor.fetchone()[0]

    def test_auto_is_null_auto_config(self):
        query = 'set sql_auto_is_null = 0'
        connection.init_connection_state()
        last_query = connection.queries[-1]['sql'].lower()
        if connection.features.is_sql_auto_is_null_enabled:
            self.assertIn(query, last_query)
        else:
            self.assertNotIn(query, last_query)

    def test_connect_isolation_level(self):
        read_committed = 'read committed'
        repeatable_read = 'repeatable read'
        isolation_values = {
            level: level.replace(' ', '-').upper()
            for level in (read_committed, repeatable_read)
        }
        configured_level = connection.isolation_level or isolation_values[repeatable_read]
        configured_level = configured_level.upper()
        other_level = read_committed if configured_level != isolation_values[read_committed] else repeatable_read

        self.assertEqual(self.get_isolation_level(connection), configured_level)

        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS']['isolation_level'] = other_level
        try:
            self.assertEqual(self.get_isolation_level(new_connection), isolation_values[other_level])
        finally:
            new_connection.close()

        # Upper case values are also accepted in 'isolation_level'.
        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS']['isolation_level'] = other_level.upper()
        try:
            self.assertEqual(self.get_isolation_level(new_connection), isolation_values[other_level])
        finally:
            new_connection.close()

    def test_isolation_level_validation(self):
        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS']['isolation_level'] = 'xxx'
        msg = (
            "Invalid transaction isolation level 'xxx' specified.\n"
            "Use one of 'read committed', 'read uncommitted', "
            "'repeatable read', 'serializable', or None."
        )
        with self.assertRaisesMessage(ImproperlyConfigured, msg):
            new_connection.cursor()


text:
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <lemon:Lexicon rdf:about="example:Lexicon__nl" xmlns:lemon="http://www.monnet-project.eu/lemon#">
    <lemon:language>nl</lemon:language>
    <lemon:entry>
      <lemon:LexicalEntry rdf:about="example:haveValidDriversLicenseEntry__nl">
        <lemon:sense>
          <lemon:LexicalSense>
            <lemon:reference rdf:resource="example:haveValidDriversLicense"/>
          </lemon:LexicalSense>
        </lemon:sense>
        <lemon:canonicalForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">hebben een geldig rijbewijs</lemon:writtenRep>
          </lemon:Form>
        </lemon:canonicalForm>
        <lexinfo:head rdf:resource="example:hebben__nl" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
        <lexinfo:lexicalComplement rdf:resource="example:gr__nl" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
        <lemon:synBehavior>
          <lemon:Frame>
            <lemon:synArg>
              <lemon:Argument/>
            </lemon:synArg>
          </lemon:Frame>
        </lemon:synBehavior>
        <lemon:otherForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">een geldig rijbewijs hebben</lemon:writtenRep>
            <lexinfo:mood rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#infinitive" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
          </lemon:Form>
        </lemon:otherForm>
        <lemon:otherForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">heeft een geldig rijbewijs</lemon:writtenRep>
            <lexinfo:number rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#singular" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
            <lexinfo:mood rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#indicative" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
            <lexinfo:tense rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#present" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
            <lexinfo:person rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#thirdPerson" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
          </lemon:Form>
        </lemon:otherForm>
      </lemon:LexicalEntry>
    </lemon:entry>
    <lemon:entry>
      <lemon:LexicalEntry rdf:about="example:workAsEntry__nl">
        <lemon:sense>
          <lemon:LexicalSense>
            <lemon:reference rdf:resource="example:workAs"/>
          </lemon:LexicalSense>
        </lemon:sense>
        <lemon:canonicalForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">werken</lemon:writtenRep>
          </lemon:Form>
        </lemon:canonicalForm>
        <lemon:synBehavior>
          <lemon:Frame>
            <lexinfo:subject xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#">
              <lemon:Argument/>
            </lexinfo:subject>
            <rdf:type rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#IntransitivePPFrame"/>
            <lexinfo:prepositionalAdjunct xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#">
              <lemon:Argument>
                <lemon:marker rdf:resource="example:als__nl"/>
              </lemon:Argument>
            </lexinfo:prepositionalAdjunct>
          </lemon:Frame>
        </lemon:synBehavior>
        <lemon:otherForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="de">werkt</lemon:writtenRep>
            <lexinfo:number rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#singular" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
            <lexinfo:mood rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#indicative" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
            <lexinfo:tense rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#present" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
            <lexinfo:person rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#thirdPerson" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
          </lemon:Form>
        </lemon:otherForm>
        <lemon:otherForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="de">werken</lemon:writtenRep>
            <lexinfo:mood rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#infinitive" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
          </lemon:Form>
        </lemon:otherForm>
      </lemon:LexicalEntry>
    </lemon:entry>
    <lemon:entry>
      <lemon:LexicalEntry rdf:about="example:over18Entry__nl">
        <lemon:sense>
          <lemon:LexicalSense>
            <lemon:reference rdf:resource="example:over18"/>
          </lemon:LexicalSense>
        </lemon:sense>
        <lemon:canonicalForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">ouder dan 18 jaar</lemon:writtenRep>
          </lemon:Form>
        </lemon:canonicalForm>
        <lemon:synBehavior>
          <lemon:Frame>
            <rdf:type rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#AdjectivePredicativeFrame"/>
            <lemon:synArg>
              <lemon:Argument/>
            </lemon:synArg>
          </lemon:Frame>
        </lemon:synBehavior>
      </lemon:LexicalEntry>
    </lemon:entry>
    <lemon:entry>
      <lemon:LexicalEntry rdf:about="example:inHollandEntry__nl">
        <lemon:canonicalForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">in nederland</lemon:writtenRep>
          </lemon:Form>
        </lemon:canonicalForm>
      </lemon:LexicalEntry>
    </lemon:entry>
    <lemon:entry>
      <lemon:LexicalEntry rdf:about="example:wonenEntry__nl">
        <lemon:canonicalForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">wonen</lemon:writtenRep>
          </lemon:Form>
        </lemon:canonicalForm>
      </lemon:LexicalEntry>
    </lemon:entry>
    <lemon:entry>
      <lemon:LexicalEntry rdf:about="example:gr__nl">
        <lemon:canonicalForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">een geldig rijbewijs</lemon:writtenRep>
          </lemon:Form>
        </lemon:canonicalForm>
      </lemon:LexicalEntry>
    </lemon:entry>
    <lemon:entry>
      <lemon:LexicalEntry rdf:about="example:hebben__nl">
        <lemon:canonicalForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">hebben</lemon:writtenRep>
          </lemon:Form>
        </lemon:canonicalForm>
      </lemon:LexicalEntry>
    </lemon:entry>
    <lemon:entry>
      <lemon:LexicalEntry rdf:about="example:truckDriverEntry__nl">
        <lemon:sense>
          <lemon:LexicalSense>
            <lemon:reference rdf:resource="example:truckDriver"/>
          </lemon:LexicalSense>
        </lemon:sense>
        <lemon:canonicalForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">vrachtwagenchauffeur</lemon:writtenRep>
          </lemon:Form>
        </lemon:canonicalForm>
        <lexinfo:gender rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#masculine" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
      </lemon:LexicalEntry>
    </lemon:entry>
    <lemon:entry>
      <lemon:LexicalEntry rdf:about="example:liveInHollandEntry__nl">
        <lemon:sense>
          <lemon:LexicalSense>
            <lemon:reference rdf:resource="example:liveInHolland"/>
          </lemon:LexicalSense>
        </lemon:sense>
        <lemon:canonicalForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">wonen in nederland</lemon:writtenRep>
          </lemon:Form>
        </lemon:canonicalForm>
        <lexinfo:head rdf:resource="example:wonenEntry__nl" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
        <lexinfo:lexicalComplement rdf:resource="example:inHollandEntry" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
        <lemon:synBehavior>
          <lemon:Frame>
            <lemon:synArg>
              <lemon:Argument/>
            </lemon:synArg>
          </lemon:Frame>
        </lemon:synBehavior>
        <lemon:otherForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">in nederland wonen</lemon:writtenRep>
            <lexinfo:mood rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#infinitive" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
          </lemon:Form>
        </lemon:otherForm>
        <lemon:otherForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">woont in nederland</lemon:writtenRep>
            <lexinfo:number rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#singular" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
            <lexinfo:mood rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#indicative" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
            <lexinfo:tense rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#present" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
            <lexinfo:person rdf:resource="http://www.lexinfo.net/ontology/2.0/lexinfo#thirdPerson" xmlns:lexinfo="http://www.lexinfo.net/ontology/2.0/lexinfo#"/>
          </lemon:Form>
        </lemon:otherForm>
      </lemon:LexicalEntry>
    </lemon:entry>
    <lemon:entry>
      <lemon:LexicalEntry rdf:about="example:als__nl">
        <lemon:canonicalForm>
          <lemon:Form>
            <lemon:writtenRep xml:lang="nl">als</lemon:writtenRep>
          </lemon:Form>
        </lemon:canonicalForm>
      </lemon:LexicalEntry>
    </lemon:entry>
  </lemon:Lexicon>
</rdf:RDF>


text:
<vector android:height="48dp" android:viewportHeight="24.0"
    android:viewportWidth="24.0" android:width="48dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#FFFFFF" android:pathData="M6,19h4V5H6v14zm8,-14v14h4V5h-4z"/>
</vector>


text:
require 'bertha'

describe "Bertha Integration" do

  it "call's Bertha to retrieve version number" do
    Bertha.open '/dev/cu.usbmodemfa131', 9600 do |bertha|
      bertha.version.should == 'v1.0.0'
    end
  end

end


text:
using System.IO;
using System.Reflection;

namespace NOps.Instance.Tests
{
    public static class TestHelpers
    {
        public static string GetAppDir()
        {
            var appPath = Assembly.GetEntryAssembly().Location;
            return Path.GetDirectoryName(appPath);
        }
    }
}


text:
alter table distribution_pref rename column grouping to dist_grouping;

/*
 * Update database version
 */

update application_config set value='208' where name='tmtbl.db.version';

commit;


text:
package org.apache.hadoop.examples;

import java.io.*;
import java.util.*;

import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

/**
 * This is an example Hadoop Map/Reduce application.
 * Map reads the text input files, breaks each line into 3 consecutive words
 * and emits <word1|word2|word3|file ,1> indicating the count of word appearing in each file
 * Reduce takes map output and emits <word1|word2|word3|file,n>.
 *
 * To run: bin/hadoop jar build/hadoop-examples.jar multiwordcount
 *            [-m maps] [-r reduces] in-dir out-dir
 *
 * @author Faraz Ahmad
 */

@SuppressWarnings("deprecation")
public class SequenceCount extends Configured implements Tool{

  private enum Counter { WORDS, VALUES }

  public static final Log LOG = LogFactory.getLog("org.apache.hadoop.examples.SequenceCount");

  public static class MapClass extends Mapper<LongWritable, Text, Text, IntWritable> {

    private final static IntWritable one = new IntWritable(1);
    private String path;

    public void map(LongWritable key, Text value,
                   Context context) throws IOException,InterruptedException {

      Text word = new Text();
      String line = new String("");
      String wordStringP1 = new String("");
      String wordStringP2 = new String("");
      String wordStringP3 = new String("");
      String docName = new String("");

      StringTokenizer tokens = new StringTokenizer(path, "/");
      while(tokens.hasMoreTokens()){
        docName = tokens.nextToken();
      }
      line = ((Text)value).toString();
      StringTokenizer itr = new StringTokenizer(line);
      while (itr.hasMoreTokens()) {
        wordStringP1 = wordStringP2;
        wordStringP2 = wordStringP3;
        wordStringP3 = itr.nextToken();
        // for one word, do no emit ..
        if(wordStringP1.equals(""));
        else {
          // using "|" as a separator
          word = new Text(wordStringP1 + "|" + wordStringP2 + "|" + wordStringP3 + "|" + docName);
          context.write(word, one);
          context.getCounter(Counter.WORDS).increment(1);;
        }
      }
    }
  }

  public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {

    public void reduce(Text key, Iterator<IntWritable> values,
                      Context context) throws IOException, InterruptedException {

      int sum = 0;
      while (values.hasNext()) {
        sum += ((IntWritable) values.next()).get();
        context.getCounter(Counter.VALUES).increment(1);
      }
      context.write(key, new IntWritable(sum));
    }
  }

  static void printUsage() {
    System.out.println("sequencecount [-m <maps>] [-r <reduces>] <input> <output>");
    System.exit(1);
  }

  /**
   * The main driver for word count map/reduce program.
   * Invoke this method to submit the map/reduce job.
   * @throws IOException When there is communication problems with the
   *                     job tracker.
   */

  public int run(String[] args) throws Exception {

    Configuration conf = new Configuration();
    Job job = Job.getInstance(conf, "sequenceCount");;
    job.setJobName("sequencecount");
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    job.setMapperClass(MapClass.class);
    job.setCombinerClass(Reduce.class);
    job.setReducerClass(Reduce.class);

    List<String> other_args = new ArrayList<String>();
    for(int i=0; i < args.length; ++i) {
      try {
        if ("-m".equals(args[i])) {

        } else if ("-r".equals(args[i])) {
          job.setNumReduceTasks(Integer.parseInt(args[++i]));
        } else {
          other_args.add(args[i]);
        }
      } catch (NumberFormatException except) {
        System.out.println("ERROR: Integer expected instead of " + args[i]);
        printUsage();
      } catch (ArrayIndexOutOfBoundsException except) {
        System.out.println("ERROR: Required parameter missing from " +
            args[i-1]);
        printUsage(); // exits
      }
    }
    // Make sure there are exactly 2 parameters left.
    if (other_args.size() != 2) {
      System.out.println("ERROR: Wrong number of parameters: " +
          other_args.size() + " instead of 2.");
      printUsage();
    }

    FileInputFormat.addInputPath(job, new Path(other_args.get(0)));
    String outPath = new String(other_args.get(1));
    FileOutputFormat.setOutputPath(job, new Path(outPath));

    Date startTime = new Date();
    System.out.println("Job started: " + startTime);

    Boolean waitforCompletion = job.waitForCompletion(true) ;

    Date end_time = new Date();
    System.out.println("Job ended: " + end_time);
    System.out.println("The job took " +
        (end_time.getTime() - startTime.getTime()) /1000 + " seconds.");
    return 0;
  }
  public static void main(String[] args) throws Exception {
    int ret = ToolRunner.run(new SequenceCount(), args);
    System.exit(ret);
  }
}


text:
import logging

from haystack import indexes
from haystack.utils import get_identifier

from django.db.models import signals

from apn_search.query import SearchQuerySet
from apn_search.results import SearchResult
from apn_search.signals import search_index_signal_handler, make_related_signal_handler, related_signal_handler_uid
from apn_search.utils.encoders import BasicEncoder

class CommonSearchIndex(indexes.SearchIndex):

    def _manage_signal_handler(self, signal_method):
        """
        Manage all signal handlers for this index through this method. Provide
        the signal_method (e.g. post_save.connect) and it will do the rest.

        """

        indexed_model = self.get_model()

        # Connect the basic signal handler for this index.
        signal_method(search_index_signal_handler, sender=indexed_model)

        # For any related models, create and connect signal handlers that will
        # update an indexable object when a related object is changed.
        for related_model, field_name in self.get_related_models():

            # Creating the function isn't necessary when disconnecting
            # signals, but for simplicity's sake (and since we never
            # disconnect) just do it anyway.
            related_handler = make_related_signal_handler(field_name)

            unique_id = related_signal_handler_uid(related_model, indexed_model)
            signal_method(
                receiver=related_handler,
                sender=related_model,
                weak=False,
                dispatch_uid=unique_id,
            )

    def _setup_save(self):
        self._manage_signal_handler(signals.post_save.connect)

    def _setup_delete(self):
        self._manage_signal_handler(signals.post_delete.connect)

    def _teardown_save(self):
        self._manage_signal_handler(signals.post_save.disconnect)

    def _teardown_delete(self):
        self._manage_signal_handler(signals.post_delete.disconnect)

    def full_prepare(self, obj):
        super(CommonSearchIndex, self).full_prepare(obj)
        self.prepared_data = BasicEncoder(self.prepared_data).encode()
        return self.prepared_data

    def get_index_name(self, using=None):
        base_index_name = self._get_backend(using).index_name
        model = self.get_model()
        version = self.get_index_version()
        parts = (
            base_index_name,
            model._meta.app_label,
            model._meta.module_name,
            version,
        )
        return '-'.join(str(part) for part in parts if part)

    def get_index_version(self):
        return None

    def get_related_models(self):
        """
        Return a sequence of tuples of models and their field names which
        returns instances of this indexed model. A signal handler will be set
        up to automatically update this index when changes to instances of the
        related model are made.

        """
        return ()

    def get_result_class(self):
        return SearchResult

    def should_index(self, obj):
        """Should this object be indexed?"""
        return True

    def update_object(self, instance, **kwargs):
        """
        Alter the default indexing behaviour to check "should_index" before
        adding an object to the index. If it returns False, then it will be
        removed instead.

        """

        if self.should_index(instance):
            logging.info('Updating search index %r' % get_identifier(instance))
            super(CommonSearchIndex, self).update_object(instance, **kwargs)
            return True
        else:
            self.remove_object(instance, using=None, **kwargs)
            return False

    def remove_object(self, instance, **kwargs):
        logging.info('Removing from search index %r' % get_identifier(instance))
        super(CommonSearchIndex, self).remove_object(instance, **kwargs)

    @staticmethod
    def filters():
        """
        Return a dictionary of filters for searching on this content type.
        These filters should ensure that only live objects are returned.

        Implement this in each Index class.

        """

        return {}

    @classmethod
    def search(cls):
        """
        Perform a basic, default search for this content type.

        Implement this in each Index class.

        """

        return SearchQuerySet()


text:
//>>built
define("dojox/html/metrics", ["dojo/_base/kernel","dojo/_base/lang", "dojo/_base/sniff", "dojo/ready", "dojo/_base/unload",
		"dojo/_base/window", "dojo/dom-geometry"],
  function(kernel,lang,has,ready,UnloadUtil,Window,DOMGeom){
	var dhm = lang.getObject("dojox.html.metrics",true);
	var dojox = lang.getObject("dojox");

	//	derived from Morris John's emResized measurer
	dhm.getFontMeasurements = function(){
		//	summary
		//	Returns an object that has pixel equivilents of standard font size values.
		var heights = {
			'1em':0, '1ex':0, '100%':0, '12pt':0, '16px':0, 'xx-small':0, 'x-small':0,
			'small':0, 'medium':0, 'large':0, 'x-large':0, 'xx-large':0
		};

		if(has("ie")){
			//	we do a font-size fix if and only if one isn't applied already.
			//	NOTE: If someone set the fontSize on the HTML Element, this will kill it.
			Window.doc.documentElement.style.fontSize="100%";
		}

		//	set up the measuring node.
		var div=Window.doc.createElement("div");
		var ds = div.style;
		ds.position="absolute";
		ds.left="-100px";
		ds.top="0";
		ds.width="30px";
		ds.height="1000em";
		ds.borderWidth="0";
		ds.margin="0";
		ds.padding="0";
		ds.outline="0";
		ds.lineHeight="1";
		ds.overflow="hidden";
		Window.body().appendChild(div);

		//	do the measurements.
		for(var p in heights){
			ds.fontSize = p;
			heights[p] = Math.round(div.offsetHeight * 12/16) * 16/12 / 1000;
		}

		Window.body().removeChild(div);
		div = null;
		return heights; 	//	object
	};

	var fontMeasurements = null;

	dhm.getCachedFontMeasurements = function(recalculate){
		if(recalculate || !fontMeasurements){
			fontMeasurements = dhm.getFontMeasurements();
		}
		return fontMeasurements;
	};

	var measuringNode = null, empty = {};
	dhm.getTextBox = function(/* String */ text, /* Object */ style, /* String? */ className){
		var m, s;
		if(!measuringNode){
			m = measuringNode = Window.doc.createElement("div");
			// Container that we can set contraints on so that it doesn't
			// trigger a scrollbar.
			var c = Window.doc.createElement("div");
			c.appendChild(m);
			s = c.style;
			s.overflow='scroll';
			s.position = "absolute";
			s.left = "0px";
			s.top = "-10000px";
			s.width = "1px";
			s.height = "1px";
			s.visibility = "hidden";
			s.borderWidth = "0";
			s.margin = "0";
			s.padding = "0";
			s.outline = "0";
			Window.body().appendChild(c);
		}else{
			m = measuringNode;
		}
		// reset styles
		m.className = "";
		s = m.style;
		s.borderWidth = "0";
		s.margin = "0";
		s.padding = "0";
		s.outline = "0";
		// set new style
		if(arguments.length > 1 && style){
			for(var i in style){
				if(i in empty){ continue; }
				s[i] = style[i];
			}
		}
		// set classes
		if(arguments.length > 2 && className){
			m.className = className;
		}
		// take a measure
		m.innerHTML = text;
		var box = DOMGeom.position(m);
		// position doesn't report right (reports 1, since parent is 1)
		// So we have to look at the scrollWidth to get the real width
		// Height is right.
		box.w = m.parentNode.scrollWidth;
		return box;
	};

	//	determine the scrollbar sizes on load.
	var scroll={ w:16, h:16 };
	dhm.getScrollbar=function(){ return { w:scroll.w, h:scroll.h }; };

	dhm._fontResizeNode = null;

	dhm.initOnFontResize = function(interval){
		var f = dhm._fontResizeNode = Window.doc.createElement("iframe");
		var fs = f.style;
		fs.position = "absolute";
		fs.width = "5em";
		fs.height = "10em";
		fs.top = "-10000px";
		if(has("ie")){
			f.onreadystatechange = function(){
				if(f.contentWindow.document.readyState == "complete"){
					f.onresize = f.contentWindow.parent[dojox._scopeName].html.metrics._fontresize;
				}
			};
		}else{
			f.onload = function(){
				f.contentWindow.onresize = f.contentWindow.parent[dojox._scopeName].html.metrics._fontresize;
			};
		}
		//The script tag is to work around a known firebug race condition.  See comments in bug #9046
		f.setAttribute("src", "javascript:''");
		Window.body().appendChild(f);
		dhm.initOnFontResize = function(){};
	};

	dhm.onFontResize = function(){};
	dhm._fontresize = function(){
		dhm.onFontResize();
	}

	UnloadUtil.addOnUnload(function(){
		// destroy our font resize iframe if we have one
		var f = dhm._fontResizeNode;
		if(f){
			if(has("ie") && f.onresize){
				f.onresize = null;
			}else if(f.contentWindow && f.contentWindow.onresize){
				f.contentWindow.onresize = null;
			}
			dhm._fontResizeNode = null;
		}
	});

	ready(function(){
		// getScrollbar metrics node
		try{
			var n=Window.doc.createElement("div");
			n.style.cssText = "top:0;left:0;width:100px;height:100px;overflow:scroll;position:absolute;visibility:hidden;";
			Window.body().appendChild(n);
			scroll.w = n.offsetWidth - n.clientWidth;
			scroll.h = n.offsetHeight - n.clientHeight;
			Window.body().removeChild(n);
			//console.log("Scroll bar dimensions: ", scroll);
			delete n;
		}catch(e){}

		// text size poll setup
		if("fontSizeWatch" in kernel.config && !!kernel.config.fontSizeWatch){
			dhm.initOnFontResize();
		}
	});
	return dhm;
});


text:
from distutils.core import setup
from setuptools import find_packages

setup(name='blitzdb',
version='0.2.12',
author='Andreas Dewes - 7scientists',
author_email='andreas@7scientists.com',
license='MIT',
entry_points={
    },
url='https://github.com/adewes/blitzdb',
packages=find_packages(),
zip_safe=False,
description='A document-oriented database written purely in Python.',
long_description="""Blitz is a document-oriented database toolkit for Python that is backend-agnostic.

It comes with a flat-file database for JSON documents and provides MongoDB-like querying capabilities.

Key Features
============

* Document-based, object-oriented interface.
* Powerful and rich querying language.
* Deep document indexes on arbitrary fields.
* Compressed storage of documents.
* Support for multiple backends (e.g. file-based storage, MongoDB).
* Support for database transactions (currently only for the file-based backend).

Documentation
=============

An extensive documentation, including tutorials and installation instructions is available on `ReadTheDocs <http://blitz-db.readthedocs.org/>`_.

Source Code
===========

The source code is available on `GitHub <https://github.com/adewes/blitzdb>`_.

Isssue Tracker
==============

If you should encounter any problems when using BlitzDB, please feel free to `submit an issue <https://github.com/adewes/blitzdb/issues>`_ on Github.

Changelog
=========

* 0.2.12: Added support for proper attribute iteration to `Document`.
* 0.2.11: Allow setting the `collection` parameter through a `Document.Meta` attribute.
* 0.2.10: Bugfix-Release: Fix Python 3 compatibility issue.
* 0.2.9: Bugfix-Release: Fix serialization problem with file backend.
* 0.2.8: Added `get`, `has_key` and `clear` methods to `Document` class
* 0.2.7: Fixed problem with __unicode__ function in Python 3.
* 0.2.6: Bugfix-Release: Fixed an issue with the $exists operator for the file backend.
* 0.2.5: Bugfix-Release
* 0.2.4: Added support for projections and update operations to the MongoDB backend.
* 0.2.3: Bugfix-Release: Fixed bug in transaction data caching in MongoDB backend.
* 0.2.2: Fix for slice operators in MongoDB backend.
* 0.2.1: Better tests.
* 0.2.0: Support for including additional information in DB references. Support for accessing document attributes as dictionary items.
         Added $regex parameter that allows to use regular expressions in queries.
* 0.1.5: MongoDB backend now supports database transactions. Database operations are now read-isolated by default, i.e.
         uncommitted operations will not affect database queries before they are committed.
* 0.1.4: Improved indexing of objects for the file backend, added support for automatic serialization/deserialization
         of object attributes when adding keys to or querying an index.
* 0.1.3: Sorting of query sets is now supported (still experimental)
* 0.1.2: Small bugfixes, BlitzDB version number now contained in DB config dict
* 0.1.1: BlitzDB is now Python3 compatible (thanks to David Koblas)
"""
)


text:
<?php

namespace ZendTest\Http\Header;

use Zend\Http\Header\IfModifiedSince;

class IfModifiedSinceTest extends \PHPUnit_Framework_TestCase
{

    public function testIfModifiedSinceFromStringCreatesValidIfModifiedSinceHeader()
    {
        $ifModifiedSinceHeader = IfModifiedSince::fromString('If-Modified-Since: xxx');
        $this->assertInstanceOf('Zend\Http\Header\HeaderDescription', $ifModifiedSinceHeader);
        $this->assertInstanceOf('Zend\Http\Header\IfModifiedSince', $ifModifiedSinceHeader);
    }

    public function testIfModifiedSinceGetFieldNameReturnsHeaderName()
    {
        $ifModifiedSinceHeader = new IfModifiedSince();
        $this->assertEquals('If-Modified-Since', $ifModifiedSinceHeader->getFieldName());
    }

    public function testIfModifiedSinceGetFieldValueReturnsProperValue()
    {
        $this->markTestIncomplete('IfModifiedSince needs to be completed');

        $ifModifiedSinceHeader = new IfModifiedSince();
        $this->assertEquals('xxx', $ifModifiedSinceHeader->getFieldValue());
    }

    public function testIfModifiedSinceToStringReturnsHeaderFormattedString()
    {
        $this->markTestIncomplete('IfModifiedSince needs to be completed');

        $ifModifiedSinceHeader = new IfModifiedSince();

        // @todo set some values, then test output
        $this->assertEmpty('If-Modified-Since: xxx', $ifModifiedSinceHeader->toString());
    }

    /** Implmentation specific tests here */

}


text:
module HasDroomUser
  extend ActiveSupport::Concern

  included do
    scope :by_user, -> user_or_uid {
      uid = user_or_uid.respond_to?(:uid) ? user_or_uid.uid : user_or_uid
      where(user_uid: uid)
    }
  end

  ## Get
  #
  # Users are associated by uid in the hope of database and device independence. All we do here is go and get the user.
  #
  def user
    begin
      if user_uid?
        @_user ||= User.find(user_uid)
      end
      if respond_to?(:email?) && email?
        @_user ||= User.where(email: email).first
      end
    rescue => e
      Rails.logger.warn "#{self.class} #{self.id} has a user_uid that corresponds to no known data room user. Perhaps someone has been deleted? Ignoring. Error: #{e}"
      nil
    end
    @_user
  end

  def find_or_create_user
    unless user
      if email
        @_user = User.create({
          given_name: given_name,
          family_name: family_name,
          chinese_name: chinese_name,
          email: email
        })
        self.user_uid = @_user.uid
      end
    end
    @_user
  end

  ## Set
  #
  # Users are assigned in two ways: by direct association to an existing user object, or by the inline creation of a new
  # user object during the creation of a local object.
  #
  # ### Assigning an existing user
  #
  # +user=+ will be called in two situations: during a compound save with an existing user object,
  # or immediately upon the creeation of a new user, on the object that it was created with.
  # We only complete the save if nothing else is going on: if this record is new or has other changes,
  # we assume that this is part of a larger save operation.
  #
  def user=(user)
    also_save = self.persisted? && !self.changed?
    self.user_uid = user.uid
    @_user = user
    self.save if also_save
  end

  # Nil or value is meaningful. Empty string means that no value was set.
  def user_uid=(uid="")
    if uid != ""
      write_attribute(:user_uid, uid)
    end
  end

  # ### Nested creation of a new user
  #
  # +user_attributes=+ is only usually called during the nested creation of a new user object but it
  # is also possible for people to update some of their account settings through a remote service.
  #
  def user_attributes=(attributes)
    if attributes.any?
      if user = self.user
        user.update_attributes(attributes.with_indifferent_access)
        user.save
      else
        attributes.reverse_merge!(defer_confirmation: confirmation_usually_deferred?)
        Rails.logger.warn "!!! NEW USER attributes=#{attributes.inspect}"
        user = User.new_with_defaults(attributes)
        user.save
        Rails.logger.warn "!!! CREATED USER with uid #{user.uid}"
        self.user = user
      end
    end
  end

  def confirmation_usually_deferred?
    true
  end

  def user?
    user_uid? && user.present?
  end

  def confirmed?
    !!user.confirmed if user?
  end

  def name
    user.name if user?
  end

  def formal_name
    user.formal_name if user?
  end

  def informal_name
    user.informal_name if user?
  end

  def colloquial_name
    user.colloquial_name if user?
  end

  def title_if_it_matters
    user.title_if_it_matters if user?
  end

  def icon
    user.icon if user?
  end

  def email
    read_attribute(:email) || user_email
  end

  def user_email
    user.email if user?
  end

end


text:
package com.tle.core.cluster.exception;

public class MessagingException extends RuntimeException {
  public MessagingException(String error) {
    super(error);
  }

  public MessagingException(String msg, Throwable t) {
    super(msg, t);
  }
}


text:
<?php

namespace SMW\Tests\Integration;

use SMW\MediaWiki\Hooks\BaseTemplateToolbox;
use SMW\ApplicationFactory;

use Title;

/**
 * @covers \SMW\MediaWiki\Hooks\BaseTemplateToolbox
 * @covers \SMWInfolink
 *
 * @group SMW
 * @group SMWExtension
 *
 * @group semantic-mediawiki-integration
 * @group mediawiki-databaseless
 *
 * @license GNU GPL v2+
 * @since 1.9
 *
 * @author mwjames
 */
class EncodingIntegrationTest extends \PHPUnit_Framework_TestCase {

	/**
	 * @dataProvider baseTemplateToolboxDataProvider
	 */
	public function testBaseTemplateToolboxURLEncoding( $setup, $expected ) {

		$toolbox  = '';

		foreach ( $setup['settings'] as $key => $value) {
			ApplicationFactory::getInstance()->getSettings()->set( $key, $value );
		}

		$instance = new BaseTemplateToolbox( $setup['skinTemplate'], $toolbox );

		$instance->process();

		$this->assertContains(
			$expected,
			$toolbox['smw-browse']['href']
		);

		ApplicationFactory::clear();
	}

	public function baseTemplateToolboxDataProvider() {

		$specialName = str_replace( '%3A', ':',
			\SMW\UrlEncoder::encode( \SpecialPage::getTitleFor( 'Browse' )->getPrefixedText() )
		);

		$provider = array();

		$provider[] = array( $this->newBaseTemplateToolboxSetup( '2013/11/05' ), "$specialName/2013-2F11-2F05" );
		$provider[] = array( $this->newBaseTemplateToolboxSetup( '2013-06-30' ), "$specialName/2013-2D06-2D30" );
		$provider[] = array( $this->newBaseTemplateToolboxSetup( '2013$06&30' ), "$specialName/2013-2406-2630" );
		$provider[] = array( $this->newBaseTemplateToolboxSetup( '2013\Foo' ),   "$specialName/2013-5CFoo" );

		return $provider;
	}

	private function newBaseTemplateToolboxSetup( $text ) {

		$settings = array(
			'smwgNamespacesWithSemanticLinks' => array( NS_MAIN => true ),
			'smwgToolboxBrowseLink'           => true
		);

		$message = $this->getMockBuilder( '\Message' )
			->disableOriginalConstructor()
			->getMock();

		$skin = $this->getMockBuilder( '\Skin' )
			->disableOriginalConstructor()
			->getMock();

		$skin->expects( $this->atLeastOnce() )
			->method( 'getTitle' )
			->will( $this->returnValue( Title::newFromText( $text, NS_MAIN ) ) );

		$skin->expects( $this->atLeastOnce() )
			->method( 'msg' )
			->will( $this->returnValue( $message ) );

		$skinTemplate = $this->getMockBuilder( '\SkinTemplate' )
			->disableOriginalConstructor()
			->getMock();

		$skinTemplate->expects( $this->atLeastOnce() )
			->method( 'getSkin' )
			->will( $this->returnValue( $skin ) );

		$skinTemplate->data['isarticle'] = true;

		return array( 'settings' => $settings, 'skinTemplate' => $skinTemplate );
	}

}