text:
package herddb.core;

import static org.junit.Assert.assertTrue;
import herddb.model.ColumnTypes;
import herddb.model.ConstValueRecordFunction;
import herddb.model.GetResult;
import herddb.model.Record;
import herddb.model.StatementEvaluationContext;
import herddb.model.Table;
import herddb.model.TransactionContext;
import herddb.model.TransactionResult;
import herddb.model.commands.BeginTransactionStatement;
import herddb.model.commands.CommitTransactionStatement;
import herddb.model.commands.CreateTableSpaceStatement;
import herddb.model.commands.CreateTableStatement;
import herddb.model.commands.DeleteStatement;
import herddb.model.commands.GetStatement;
import herddb.model.commands.InsertStatement;
import herddb.model.commands.UpdateStatement;
import herddb.utils.Bytes;
import java.nio.file.Path;
import java.util.Collections;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

/**
 * Recovery from file
 *
 * @author enrico.olivelli
 */
public abstract class RestartPendingTransactionBase {

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    protected abstract DBManager buildDBManager(
            String nodeId,
            Path metadataPath,
            Path dataPath,
            Path logsPath,
            Path tmoDir) throws Exception;

    @Test
    public void recoverUpdateInTransaction() throws Exception {

        Path dataPath = folder.newFolder("data").toPath();
        Path logsPath = folder.newFolder("logs").toPath();
        Path metadataPath = folder.newFolder("metadata").toPath();
        Path tmoDir = folder.newFolder("tmoDir").toPath();
        Bytes key1 = Bytes.from_string("k1");
        Bytes key2 = Bytes.from_string("k2");
        Bytes key3 = Bytes.from_string("k3");
        String nodeId = "localhost";
        try (DBManager manager = buildDBManager(nodeId,
                metadataPath,
                dataPath,
                logsPath,
                tmoDir)) {
            manager.start();

            CreateTableSpaceStatement st1 = new CreateTableSpaceStatement("tblspace1", Collections.singleton(nodeId),
                    nodeId, 1, 0, 0);
            manager.executeStatement(st1, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(),
                    TransactionContext.NO_TRANSACTION);
            manager.waitForTablespace("tblspace1", 10000);

            Table table = Table
                    .builder()
                    .tablespace("tblspace1")
                    .name("t1")
                    .column("id", ColumnTypes.STRING)
                    .column("name", ColumnTypes.STRING)
                    .primaryKey("id")
                    .build();
            manager.executeStatement(new CreateTableStatement(table), StatementEvaluationContext.
                    DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key1, key1)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key2, key2)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key3, key3)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.checkpoint();

            long tx = ((TransactionResult) manager.executeStatement(new BeginTransactionStatement("tblspace1"),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION)).
                    getTransactionId();
            manager.executeStatement(new UpdateStatement("tblspace1", table.name, new ConstValueRecordFunction(key2),
                    new ConstValueRecordFunction(key3), null), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(),
                    new TransactionContext(tx));
            manager.executeStatement(new CommitTransactionStatement("tblspace1", tx), StatementEvaluationContext.
                    DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            // transaction which contains the update will be replayed at reboot
        }

        try (DBManager manager = buildDBManager(nodeId,
                metadataPath,
                dataPath,
                logsPath,
                tmoDir)) {
            manager.start();

            manager.waitForTablespace("tblspace1", 10000);

            GetResult result = manager.get(new GetStatement("tblspace1", "t1", key1, null, false),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            assertTrue(result.found());
        }

    }

    @Test
    public void recoverDeleteInTransaction() throws Exception {

        Path dataPath = folder.newFolder("data").toPath();
        Path logsPath = folder.newFolder("logs").toPath();
        Path metadataPath = folder.newFolder("metadata").toPath();
        Path tmoDir = folder.newFolder("tmoDir").toPath();
        Bytes key1 = Bytes.from_string("k1");
        Bytes key2 = Bytes.from_string("k2");
        Bytes key3 = Bytes.from_string("k3");
        String nodeId = "localhost";
        try (DBManager manager = buildDBManager(nodeId,
                metadataPath,
                dataPath,
                logsPath,
                tmoDir)) {
            manager.start();

            CreateTableSpaceStatement st1 = new CreateTableSpaceStatement("tblspace1", Collections.singleton(nodeId),
                    nodeId, 1, 0, 0);
            manager.executeStatement(st1, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(),
                    TransactionContext.NO_TRANSACTION);
            manager.waitForTablespace("tblspace1", 10000);

            Table table = Table
                    .builder()
                    .tablespace("tblspace1")
                    .name("t1")
                    .column("id", ColumnTypes.STRING)
                    .column("name", ColumnTypes.STRING)
                    .primaryKey("id")
                    .build();
            manager.executeStatement(new CreateTableStatement(table), StatementEvaluationContext.
                    DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key1, key1)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key2, key2)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key3, key3)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.checkpoint();

            long tx = ((TransactionResult) manager.executeStatement(new BeginTransactionStatement("tblspace1"),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION)).
                    getTransactionId();
            manager.executeStatement(new DeleteStatement("tblspace1", table.name, key2, null),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), new TransactionContext(tx));
            manager.executeStatement(new CommitTransactionStatement("tblspace1", tx), StatementEvaluationContext.
                    DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            // transaction which contains the update will be replayed at reboot
        }

        try (DBManager manager = buildDBManager(nodeId,
                metadataPath,
                dataPath,
                logsPath,
                tmoDir)) {
            manager.start();

            manager.waitForTablespace("tblspace1", 10000);

            GetResult result = manager.get(new GetStatement("tblspace1", "t1", key1, null, false),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            assertTrue(result.found());
        }

    }

    @Test
    public void recoverUpdate() throws Exception {

        Path dataPath = folder.newFolder("data").toPath();
        Path logsPath = folder.newFolder("logs").toPath();
        Path metadataPath = folder.newFolder("metadata").toPath();
        Path tmoDir = folder.newFolder("tmoDir").toPath();
        Bytes key1 = Bytes.from_string("k1");
        Bytes key2 = Bytes.from_string("k2");
        Bytes key3 = Bytes.from_string("k3");
        String nodeId = "localhost";
        try (DBManager manager = buildDBManager(nodeId,
                metadataPath,
                dataPath,
                logsPath,
                tmoDir)) {
            manager.start();

            CreateTableSpaceStatement st1 = new CreateTableSpaceStatement("tblspace1", Collections.singleton(nodeId),
                    nodeId, 1, 0, 0);
            manager.executeStatement(st1, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(),
                    TransactionContext.NO_TRANSACTION);
            manager.waitForTablespace("tblspace1", 10000);

            Table table = Table
                    .builder()
                    .tablespace("tblspace1")
                    .name("t1")
                    .column("id", ColumnTypes.STRING)
                    .column("name", ColumnTypes.STRING)
                    .primaryKey("id")
                    .build();
            manager.executeStatement(new CreateTableStatement(table), StatementEvaluationContext.
                    DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key1, key1)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key2, key2)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key3, key3)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.checkpoint();

            manager.executeStatement(new UpdateStatement("tblspace1", table.name, new ConstValueRecordFunction(key2),
                    new ConstValueRecordFunction(key3), null), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(),
                    TransactionContext.NO_TRANSACTION);

            long tx2 = ((TransactionResult) manager.executeStatement(new BeginTransactionStatement("tblspace1"),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION)).
                    getTransactionId();
            manager.executeStatement(new UpdateStatement("tblspace1", table.name, new ConstValueRecordFunction(key2),
                    new ConstValueRecordFunction(key3), null), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(),
                    new TransactionContext(tx2));
            manager.executeStatement(new CommitTransactionStatement("tblspace1", tx2), StatementEvaluationContext.
                    DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            // transactions which contains the update will be replayed at reboot
        }

        try (DBManager manager = buildDBManager(nodeId,
                metadataPath,
                dataPath,
                logsPath,
                tmoDir)) {
            manager.start();

            manager.waitForTablespace("tblspace1", 10000);

            GetResult result = manager.get(new GetStatement("tblspace1", "t1", key1, null, false),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            assertTrue(result.found());
        }

    }

    @Test
    public void recoverDelete() throws Exception {

        Path dataPath = folder.newFolder("data").toPath();
        Path logsPath = folder.newFolder("logs").toPath();
        Path metadataPath = folder.newFolder("metadata").toPath();
        Path tmoDir = folder.newFolder("tmoDir").toPath();
        Bytes key1 = Bytes.from_string("k1");
        Bytes key2 = Bytes.from_string("k2");
        Bytes key3 = Bytes.from_string("k3");
        String nodeId = "localhost";
        try (DBManager manager = buildDBManager(nodeId,
                metadataPath,
                dataPath,
                logsPath,
                tmoDir)) {
            manager.start();

            CreateTableSpaceStatement st1 = new CreateTableSpaceStatement("tblspace1", Collections.singleton(nodeId),
                    nodeId, 1, 0, 0);
            manager.executeStatement(st1, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(),
                    TransactionContext.NO_TRANSACTION);
            manager.waitForTablespace("tblspace1", 10000);

            Table table = Table
                    .builder()
                    .tablespace("tblspace1")
                    .name("t1")
                    .column("id", ColumnTypes.STRING)
                    .column("name", ColumnTypes.STRING)
                    .primaryKey("id")
                    .build();
            manager.executeStatement(new CreateTableStatement(table), StatementEvaluationContext.
                    DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key1, key1)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key2, key2)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key3, key3)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.checkpoint();

            manager.executeStatement(new DeleteStatement("tblspace1", table.name, key2, null),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);

        }

        try (DBManager manager = buildDBManager(nodeId,
                metadataPath,
                dataPath,
                logsPath,
                tmoDir)) {
            manager.start();

            manager.waitForTablespace("tblspace1", 10000);

            GetResult result = manager.get(new GetStatement("tblspace1", "t1", key1, null, false),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            assertTrue(result.found());
        }

    }

    @Test
    public void recoverUpdateInTransaction2() throws Exception {

        Path dataPath = folder.newFolder("data").toPath();
        Path logsPath = folder.newFolder("logs").toPath();
        Path metadataPath = folder.newFolder("metadata").toPath();
        Path tmoDir = folder.newFolder("tmoDir").toPath();
        Bytes key1 = Bytes.from_string("k1");
        Bytes key2 = Bytes.from_string("k2");
        Bytes key3 = Bytes.from_string("k3");
        String nodeId = "localhost";
        try (DBManager manager = buildDBManager(nodeId,
                metadataPath,
                dataPath,
                logsPath,
                tmoDir)) {
            manager.start();

            CreateTableSpaceStatement st1 = new CreateTableSpaceStatement("tblspace1", Collections.singleton(nodeId),
                    nodeId, 1, 0, 0);
            manager.executeStatement(st1, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(),
                    TransactionContext.NO_TRANSACTION);
            manager.waitForTablespace("tblspace1", 10000);

            Table table = Table
                    .builder()
                    .tablespace("tblspace1")
                    .name("t1")
                    .column("id", ColumnTypes.STRING)
                    .column("name", ColumnTypes.STRING)
                    .primaryKey("id")
                    .build();
            manager.executeStatement(new CreateTableStatement(table), StatementEvaluationContext.
                    DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key1, key1)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key2, key2)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key3, key3)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.checkpoint();

            long tx = ((TransactionResult) manager.executeStatement(new BeginTransactionStatement("tblspace1"),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION)).
                    getTransactionId();
            manager.executeStatement(new DeleteStatement("tblspace1", table.name, key2, null),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), new TransactionContext(tx));
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key2, key2)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), new TransactionContext(tx));
            manager.executeStatement(new UpdateStatement("tblspace1", table.name, new ConstValueRecordFunction(key2),
                    new ConstValueRecordFunction(key3), null), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(),
                    new TransactionContext(tx));
            manager.executeStatement(new CommitTransactionStatement("tblspace1", tx), StatementEvaluationContext.
                    DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            // transaction which contains the update will be replayed at reboot
        }

        try (DBManager manager = buildDBManager(nodeId,
                metadataPath,
                dataPath,
                logsPath,
                tmoDir)) {
            manager.start();

            manager.waitForTablespace("tblspace1", 10000);

            GetResult result = manager.get(new GetStatement("tblspace1", "t1", key1, null, false),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            assertTrue(result.found());
        }

    }

    @Test
    public void recoverCommitInTransaction() throws Exception {

        Path dataPath = folder.newFolder("data").toPath();
        Path logsPath = folder.newFolder("logs").toPath();
        Path metadataPath = folder.newFolder("metadata").toPath();
        Path tmoDir = folder.newFolder("tmoDir").toPath();
        Bytes key1 = Bytes.from_string("k1");
        Bytes key2 = Bytes.from_string("k2");
        Bytes key3 = Bytes.from_string("k3");
        String nodeId = "localhost";
        try (DBManager manager = buildDBManager(nodeId,
                metadataPath,
                dataPath,
                logsPath,
                tmoDir)) {
            manager.start();

            CreateTableSpaceStatement st1 = new CreateTableSpaceStatement("tblspace1", Collections.singleton(nodeId),
                    nodeId, 1, 0, 0);
            manager.executeStatement(st1, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(),
                    TransactionContext.NO_TRANSACTION);
            manager.waitForTablespace("tblspace1", 10000);

            Table table = Table
                    .builder()
                    .tablespace("tblspace1")
                    .name("t1")
                    .column("id", ColumnTypes.STRING)
                    .column("name", ColumnTypes.STRING)
                    .primaryKey("id")
                    .build();
            manager.executeStatement(new CreateTableStatement(table), StatementEvaluationContext.
                    DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key1, key1)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key2, key2)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            manager.executeStatement(new InsertStatement("tblspace1", table.name, new Record(key3, key3)),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);

            long tx = ((TransactionResult) manager.executeStatement(new BeginTransactionStatement("tblspace1"),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION)).
                    getTransactionId();

            manager.executeStatement(new UpdateStatement("tblspace1", table.name, new ConstValueRecordFunction(key2),
                    new ConstValueRecordFunction(key3), null), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(),
                    new TransactionContext(tx));

            manager.checkpoint();

            // the commit tx command is to be replayed
            // the behaviour is different from BK and File commit logs
            manager.executeStatement(new CommitTransactionStatement("tblspace1", tx), StatementEvaluationContext.
                    DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);

        }

        try (DBManager manager = buildDBManager(nodeId,
                metadataPath,
                dataPath,
                logsPath,
                tmoDir)) {
            manager.start();

            manager.waitForTablespace("tblspace1", 10000);

            GetResult result = manager.get(new GetStatement("tblspace1", "t1", key2, null, false),
                    StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
            assertTrue(result.found());
        }

    }
}


text:
import copy
import re
import sys
import warnings
from threading import local

from cms.admin.placeholderadmin import PlaceholderAdminMixin
from cms.constants import PUBLISHER_STATE_PENDING
from cms.models import CMSPlugin, StaticPlaceholder
from cms.utils import get_language_from_request
from cms.utils.conf import get_cms_setting
from cms.utils.i18n import (
    force_language, get_language_list, get_language_object, get_language_tuple,
)
from cms.utils.urlutils import admin_reverse
from django.conf.urls import url
from django.contrib import admin, messages
from django.contrib.admin.models import CHANGE, LogEntry
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import router, transaction
from django.http import Http404, HttpResponseForbidden, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.template.defaultfilters import escape
from django.template.loader import get_template
from django.utils.decorators import method_decorator
from django.utils.encoding import force_text
from django.utils.six.moves.urllib.parse import unquote
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.http import require_POST

from ..api import add_content
from ..conf import settings
from ..models import Article, Title
from .forms import ArticleCreateForm, ArticleForm

try:
    from django.contrib.admin.utils import get_deleted_objects
except ImportError:
    from django.contrib.admin.util import get_deleted_objects

require_POST = method_decorator(require_POST)

_thread_locals = local()

class ArticleAdmin(PlaceholderAdminMixin, admin.ModelAdmin):
    change_list_template = 'admin/cms_articles/article_changelist.html'
    search_fields = ('=id', 'title_set__slug', 'title_set__title', 'title_set__description')
    list_display = ('__str__', 'order_date', 'preview_link') + tuple(
        'lang_{}'.format(lang) for lang in get_language_list()
    )
    list_filter = ['tree', 'attributes', 'categories', 'template', 'changed_by']
    date_hierarchy = 'order_date'
    filter_horizontal = ['attributes', 'categories']

    preview_template = 'admin/cms_articles/article/change_list_preview.html'

    def preview_link(self, obj):
        return get_template(self.preview_template).render({
            'article': obj,
            'lang': _thread_locals.language,
            'request': _thread_locals.request,
        })
    preview_link.short_description = _('Show')
    preview_link.allow_tags = True

    lang_template = 'admin/cms_articles/article/change_list_lang.html'

    def __getattr__(self, name):
        if name.startswith('lang_'):
            lang = name[len('lang_'):]

            def lang_dropdown(obj):
                return get_template(self.lang_template).render({
                    'article': obj,
                    'lang': lang,
                    'language': _thread_locals.language,
                    'has_change_permission': obj.has_change_permission(_thread_locals.request),
                    'has_publish_permission': obj.has_publish_permission(_thread_locals.request),
                    'request': _thread_locals.request,
                })

            lang_dropdown.short_description = lang
            lang_dropdown.allow_tags = True
            return lang_dropdown
        raise AttributeError(name)

    def get_fieldsets(self, request, obj=None):
        language_dependent = ['title', 'slug', 'description', 'content', 'page_title',
                              'menu_title', 'meta_description', 'image']
        if obj:
            language_dependent.remove('content')
        return [
            (None, {'fields': ['tree', 'template']}),
            (_('Language dependent settings'), {'fields': language_dependent}),
            (_('Other settings'), {'fields': ['attributes', 'categories', 'publication_date',
                                              'publication_end_date', 'login_required']}),
        ]

    def get_urls(self):
        """Get the admin urls
        """
        info = '%s_%s' % (self.model._meta.app_label, self.model._meta.model_name)

        def pat(regex, fn):
            return url(regex, self.admin_site.admin_view(fn), name='%s_%s' % (info, fn.__name__))

        url_patterns = [
            pat(r'^([0-9]+)/delete-translation/$', self.delete_translation),
            pat(r'^([0-9]+)/([a-z\-]+)/publish/$', self.publish_article),
            pat(r'^([0-9]+)/([a-z\-]+)/unpublish/$', self.unpublish),
            pat(r'^([0-9]+)/([a-z\-]+)/preview/$', self.preview_article),
        ]

        url_patterns += super(ArticleAdmin, self).get_urls()
        return url_patterns

    def get_queryset(self, request):
        return super(ArticleAdmin, self).get_queryset(request).filter(
            tree__node__site_id=settings.SITE_ID,
            publisher_is_draft=True,
        )

    def save_model(self, request, obj, form, change):
        new = obj.id is None
        super(ArticleAdmin, self).save_model(request, obj, form, change)
        Title.objects.set_or_create(request, obj, form, form.cleaned_data['language'])
        if new and form.cleaned_data['content']:
            add_content(
                obj,
                language=form.cleaned_data['language'],
                slot=settings.CMS_ARTICLES_SLOT,
                content=form.cleaned_data['content'],
            )

    SLUG_REGEXP = re.compile(settings.CMS_ARTICLES_SLUG_REGEXP)

    def get_form(self, request, obj=None, **kwargs):
        """
        Get ArticleForm for the Article model and modify its fields depending on
        the request.
        """
        language = get_language_from_request(request)
        form = super(ArticleAdmin, self).get_form(
            request, obj,
            form=(obj and ArticleForm or ArticleCreateForm),
            **kwargs
        )
        # get_form method operates by overriding initial fields value which
        # may persist across invocation. Code below deepcopies fields definition
        # to avoid leaks
        for field in tuple(form.base_fields.keys()):
            form.base_fields[field] = copy.deepcopy(form.base_fields[field])

        if 'language' in form.base_fields:
            form.base_fields['language'].initial = language

        if obj:
            title_obj = obj.get_title_obj(language=language, fallback=False, force_reload=True)

            if hasattr(title_obj, 'id'):
                for name in ('title', 'description', 'page_title', 'menu_title', 'meta_description', 'image'):
                    if name in form.base_fields:
                        form.base_fields[name].initial = getattr(title_obj, name)
                try:
                    slug = self.SLUG_REGEXP.search(title_obj.slug).groups()[settings.CMS_ARTICLES_SLUG_GROUP_INDEX]
                except AttributeError:
                    warnings.warn('Failed to parse slug from CMS_ARTICLES_SLUG_REGEXP. '
                                  'It probably doesn\'t correspond to CMS_ARTICLES_SLUG_FORMAT.')
                    slug = title_obj.slug
                form.base_fields['slug'].initial = slug

        return form

    def get_unihandecode_context(self, language):
        if language[:2] in get_cms_setting('UNIHANDECODE_DECODERS'):
            uhd_lang = language[:2]
        else:
            uhd_lang = get_cms_setting('UNIHANDECODE_DEFAULT_DECODER')
        uhd_host = get_cms_setting('UNIHANDECODE_HOST')
        uhd_version = get_cms_setting('UNIHANDECODE_VERSION')
        if uhd_lang and uhd_host and uhd_version:
            uhd_urls = [
                '%sunihandecode-%s.core.min.js' % (uhd_host, uhd_version),
                '%sunihandecode-%s.%s.min.js' % (uhd_host, uhd_version, uhd_lang),
            ]
        else:
            uhd_urls = []
        return {'unihandecode_lang': uhd_lang, 'unihandecode_urls': uhd_urls}

    def changelist_view(self, request, extra_context=None):
        _thread_locals.request = request
        _thread_locals.language = get_language_from_request(request)
        return super(ArticleAdmin, self).changelist_view(request, extra_context=extra_context)

    def add_view(self, request, form_url='', extra_context=None):
        extra_context = self.update_language_tab_context(request, context=extra_context)
        extra_context.update(self.get_unihandecode_context(extra_context['language']))
        return super(ArticleAdmin, self).add_view(request, form_url, extra_context=extra_context)

    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = self.update_language_tab_context(request, context=extra_context)
        language = extra_context['language']
        extra_context.update(self.get_unihandecode_context(language))
        response = super(ArticleAdmin, self).change_view(request, object_id,
                                                         form_url=form_url, extra_context=extra_context)
        if language and response.status_code == 302 and response._headers['location'][1] == request.path_info:
            location = response._headers['location']
            response._headers['location'] = (location[0], '%s?language=%s' % (location[1], language))
        return response

    def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None):
        # add context variables
        filled_languages = []
        if obj:
            filled_languages = [t[0] for t in obj.title_set.filter(title__isnull=False).values_list('language')]
        allowed_languages = [lang[0] for lang in get_language_tuple()]
        context.update({
            'filled_languages': [lang for lang in filled_languages if lang in allowed_languages],
        })
        return super(ArticleAdmin, self).render_change_form(request, context, add, change, form_url, obj)

    def update_language_tab_context(self, request, context=None):
        if not context:
            context = {}
        language = get_language_from_request(request)
        languages = get_language_tuple()
        context.update({
            'language': language,
            'languages': languages,
            'language_tabs': languages,
            'show_language_tabs': len(list(languages)) > 1,
        })
        return context

    @require_POST
    @transaction.atomic
    def publish_article(self, request, article_id, language):
        try:
            article = Article.objects.get(id=article_id, publisher_is_draft=True)
        except Article.DoesNotExist:
            article = None

        # ensure user has permissions to publish this article
        if article:
            if not self.has_change_permission(request):
                return HttpResponseForbidden(force_text(_('You do not have permission to publish this article')))
            article.publish(language)
        statics = request.GET.get('statics', '')
        if not statics and not article:
            raise Http404('No article or stack found for publishing.')
        all_published = True
        if statics:
            static_ids = statics.split(',')
            for pk in static_ids:
                static_placeholder = StaticPlaceholder.objects.get(pk=pk)
                published = static_placeholder.publish(request, language)
                if not published:
                    all_published = False
        if article:
            if all_published:
                messages.info(request, _('The content was successfully published.'))
                LogEntry.objects.log_action(
                    user_id=request.user.id,
                    content_type_id=ContentType.objects.get_for_model(Article).pk,
                    object_id=article_id,
                    object_repr=article.get_title(language),
                    action_flag=CHANGE,
                )
            else:
                messages.warning(request, _('There was a problem publishing your content'))

        if 'redirect' in request.GET:
            return HttpResponseRedirect(request.GET['redirect'])

        referrer = request.META.get('HTTP_REFERER', '')
        path = admin_reverse('cms_articles_article_changelist')
        if request.GET.get('redirect_language'):
            path = '%s?language=%s&article_id=%s' % (
                path,
                request.GET.get('redirect_language'),
                request.GET.get('redirect_article_id')
            )
        if admin_reverse('index') not in referrer:
            if all_published:
                if article:
                    if article.get_publisher_state(language) == PUBLISHER_STATE_PENDING:
                        path = article.get_absolute_url(language, fallback=True)
                    else:
                        public_article = Article.objects.get(publisher_public=article.pk)
                        path = '%s?%s' % (
                            public_article.get_absolute_url(language, fallback=True),
                            get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF')
                        )
                else:
                    path = '%s?%s' % (referrer, get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF'))
            else:
                path = '/?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF')

        return HttpResponseRedirect(path)

    @require_POST
    @transaction.atomic
    def unpublish(self, request, article_id, language):
        """
        Publish or unpublish a language of a article
        """
        article = get_object_or_404(self.model, pk=article_id)
        if not article.has_publish_permission(request):
            return HttpResponseForbidden(force_text(_('You do not have permission to unpublish this article')))
        if not article.publisher_public_id:
            return HttpResponseForbidden(force_text(_('This article was never published')))
        try:
            article.unpublish(language)
            message = _('The %(language)s article "%(article)s" was successfully unpublished') % {
                'language': get_language_object(language)['name'], 'article': article}
            messages.info(request, message)
            LogEntry.objects.log_action(
                user_id=request.user.id,
                content_type_id=ContentType.objects.get_for_model(Article).pk,
                object_id=article_id,
                object_repr=article.get_title(),
                action_flag=CHANGE,
                change_message=message,
            )
        except RuntimeError:
            exc = sys.exc_info()[1]
            messages.error(request, exc.message)
        except ValidationError:
            exc = sys.exc_info()[1]
            messages.error(request, exc.message)
        path = admin_reverse('cms_articles_article_changelist')
        if request.GET.get('redirect_language'):
            path = '%s?language=%s&article_id=%s' % (
                path,
                request.GET.get('redirect_language'),
                request.GET.get('redirect_article_id')
            )
        return HttpResponseRedirect(path)

    def delete_translation(self, request, object_id, extra_context=None):
        if 'language' in request.GET:
            language = request.GET['language']
        else:
            language = get_language_from_request(request)

        opts = Article._meta
        titleopts = Title._meta
        app_label = titleopts.app_label
        pluginopts = CMSPlugin._meta

        try:
            obj = self.get_queryset(request).get(pk=unquote(object_id))
        except self.model.DoesNotExist:
            # Don't raise Http404 just yet, because we haven't checked
            # permissions yet. We don't want an unauthenticated user to be able
            # to determine whether a given object exists.
            obj = None

        if not self.has_delete_permission(request, obj):
            return HttpResponseForbidden(force_text(_('You do not have permission to change this article')))

        if obj is None:
            raise Http404(
                _('%(name)s object with primary key %(key)r does not exist.') % {
                    'name': force_text(opts.verbose_name),
                    'key': escape(object_id)
                })

        if not len(list(obj.get_languages())) > 1:
            raise Http404(_('There only exists one translation for this article'))

        titleobj = get_object_or_404(Title, article__id=object_id, language=language)
        saved_plugins = CMSPlugin.objects.filter(placeholder__article__id=object_id, language=language)

        using = router.db_for_read(self.model)
        kwargs = {
            'admin_site': self.admin_site,
            'user': request.user,
            'using': using
        }

        deleted_objects, __, perms_needed = get_deleted_objects(
            [titleobj],
            titleopts,
            **kwargs
        )[:3]
        to_delete_plugins, __, perms_needed_plugins = get_deleted_objects(
            saved_plugins,
            pluginopts,
            **kwargs
        )[:3]

        deleted_objects.append(to_delete_plugins)
        perms_needed = set(list(perms_needed) + list(perms_needed_plugins))

        if request.method == 'POST':
            if perms_needed:
                raise PermissionDenied

            message = _('Title and plugins with language %(language)s was deleted') % {
                'language': force_text(get_language_object(language)['name'])
            }
            self.log_change(request, titleobj, message)
            messages.info(request, message)

            titleobj.delete()
            for p in saved_plugins:
                p.delete()

            public = obj.publisher_public
            if public:
                public.save()

            if not self.has_change_permission(request, None):
                return HttpResponseRedirect(admin_reverse('index'))
            return HttpResponseRedirect(admin_reverse('cms_articles_article_changelist'))

        context = {
            'title': _('Are you sure?'),
            'object_name': force_text(titleopts.verbose_name),
            'object': titleobj,
            'deleted_objects': deleted_objects,
            'perms_lacking': perms_needed,
            'opts': opts,
            'root_path': admin_reverse('index'),
            'app_label': app_label,
        }
        context.update(extra_context or {})
        request.current_app = self.admin_site.name
        return render(request, self.delete_confirmation_template or [
            'admin/%s/%s/delete_confirmation.html' % (app_label, titleopts.object_name.lower()),
            'admin/%s/delete_confirmation.html' % app_label,
            'admin/delete_confirmation.html'
        ], context)

    def preview_article(self, request, object_id, language):
        """Redirecting preview function based on draft_id
        """
        article = get_object_or_404(self.model, id=object_id)
        attrs = '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')
        attrs += '&language=' + language
        with force_language(language):
            url = article.get_absolute_url(language) + attrs
        return HttpResponseRedirect(url)

admin.site.register(Article, ArticleAdmin)

redpajama_set_name: RedPajamaGithub


text:
package org.damm.ideaforge.repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.damm.ideaforge.pojo.Event;
import org.damm.ideaforge.pojo.Team;
import org.damm.ideaforge.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

@Repository
public class EventRepository {

	private final static String SELECT_TEAM = "select id,name,user_id,start,end from event";

	@Autowired
	private JdbcTemplate jdbcTemplate;

	public List<Event> findAll() {
		return jdbcTemplate.query(SELECT_TEAM, new EventRowMapper());
	}

	public Event insert(Event event, User currentUser) {
		String sql = "insert into event (name, user_id) values (?,?)";
		KeyHolder keyHolder = new GeneratedKeyHolder();
		jdbcTemplate.update(new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
				PreparedStatement ps = connection.prepareStatement(sql, new String[] { "id" });
				ps.setString(1, event.getName());
				ps.setLong(2, currentUser.getId());
				return ps;
			}
		}, keyHolder);
		event.setId(keyHolder.getKey().longValue());
		return event;
	}

	public int update(Event event) {
		String sql = "update event set name = ? where id = ?";
		return jdbcTemplate.update(sql, event.getName(), event.getId());
	}

	public Event find(Long id) {
		String sql = String.format("%s %s", SELECT_TEAM, "where id = ?");
		return jdbcTemplate.queryForObject(sql, new EventRowMapper(), id);
	}

	public int addTeam(long teamId, long eventId) {
		String sql = "insert into team_event (team_id, event_id) values (?,?)";
		return jdbcTemplate.update(sql, teamId, eventId);
	}

	public List<Team> teams(long eventId) {
		String sql = "select t.id, t.name, t.user_id from team t join team_event te on t.id = te.team_id where te.event_id = ?";
		return jdbcTemplate.query(sql, new TeamRowMapper(), eventId);
	}

	private class EventRowMapper implements RowMapper<Event> {
		@Override
		public Event mapRow(ResultSet rs, int row) throws SQLException {
			Event event = new Event();
			event.setId(rs.getLong("id"));
			event.setName(rs.getString("name"));
			event.setUserId(rs.getLong("user_id"));
			event.setStart(rs.getLong("start"));
			event.setEnd(rs.getLong("end"));
			return event;
		}
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2021 OPS4J.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.ops4j.pax.cdi</groupId>
        <artifactId>pax-cdi-samples</artifactId>
        <version>1.1.5-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <groupId>org.ops4j.pax.cdi.samples</groupId>
    <artifactId>pax-cdi-sample5-client1</artifactId>
    <packaging>bundle</packaging>

    <name>OPS4J Pax CDI Sample5 Client1</name>

    <dependencies>

        <!-- pax-cdi own artifacts -->

        <dependency>
            <groupId>org.ops4j.pax.cdi.samples</groupId>
            <artifactId>pax-cdi-sample5</artifactId>
        </dependency>

        <!-- APIs -->

        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>org.ops4j.pax.cdi.sample5.client1</Bundle-SymbolicName>
                        <Require-Capability>
                            osgi.cdi.extension;
                            filter:="(&(osgi.cdi.extension=pax-cdi-extension)(version>=${version;==;${pax.cdi.osgi.version.clean}})(!(version>=${version;=+;${pax.cdi.osgi.version.clean}})))",
                            osgi.extender; filter:="(osgi.extender=osgi.cdi)"
                        </Require-Capability>
                    </instructions>
                </configuration>
                <executions>
                    <execution>
                        <id>versions</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>cleanVersions</goal>
                        </goals>
                        <configuration>
                            <versions>
                                <pax.cdi.osgi.version.clean>${project.version}</pax.cdi.osgi.version.clean>
                            </versions>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
elemon
======

[![npm](https://img.shields.io/npm/v/elemon.svg?style=flat-square)](https://www.npmjs.com/package/elemon)

`elemon` is a tiny module that tries to provide a simple and yet efficient live-reload tool when developing [Electron](https://github.com/electron/electron) applications. You just need to pass the `app` and `BrowserWindows` and the name of the files that are associated with them as a parameter to the `elemon` function **after** your app is `ready`. Please check out the example below to see how you can easily use it to watch your app and cleanly reload it upon any changes. If the changed
file is the main app file, then it `relaunch` the app and `exit` the current instance. If the changed file is a file that is associated with a browser window, then that window will only be reloaded.

In fact, setting up a clean live-reload tool when developing an electron application is super simple by using the [Electron API](https://github.com/electron/electron/tree/master/docs). The api already comes with whatever you need; just add a watcher (like [chokidar](https://github.com/paulmillr/chokidar) or whatever watcher you like) and you are all set.

Install
-------

  `npm i elemon --save-dev`.

Usage
-----

**elemon(refs)**

`refs` `{Object}` object that takes references to app and browser windows objects and resources
  - `app` `{Object}` main [app](https://github.com/electron/electron/blob/master/docs/api/app.md) object
  - `mainFile` `{String}` main file name
  - `bws` `{Array<Object>}` array of browser window objects and their resources `[{bw:, res: []}]`
    - `bw` `{Object}` [BrowserWindow](https://github.com/electron/electron/blob/master/docs/api/browser-window.md) object
    - `res` `{Array<String>}` array of any file name that is somehow associated with this browser window
      - _if you want to watch all files in dir, or if you want the `bw` to be reloaded on any changes and not necessarily changes on specific file(s), leave the `res` as empty `[]`._

Example
-------

Suppose it is the app file structure:

```
example_proj
  |
  |__views
  |    |__win1.html
  |    |__win2.html
  |    |__win1.js
  |    |__win2.js
  |
  |__stylesheets
  |    |__style.css
  |
  |__main.js

```
then, in the main process file where usually app and browser windows are created:

*main.js*

```js

const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
const elemon = require('elemon')

let win1, win2

function createWindows () {
  win1 = new BrowserWindow({width: 800, height: 600})
  win1.loadURL(url.format({
    pathname: path.join(__dirname, 'views', 'win1.html'),
    protocol: 'file:',
    slashes: true
  }))
  win1.on('closed', () => {
    win1 = null
  })

  win2 = new BrowserWindow({width: 800, height: 600})
  win2.loadURL(url.format({
    pathname: path.join(__dirname, 'views', 'win2.html'),
    protocol: 'file:',
    slashes: true
  }))
  win2.on('closed', () => {
    win2 = null
  })
}

// ... and other usual stuff ... //

app.on('ready', () => {
  createWindows()

  // this is all that you have to add to your main app script.
  // run your app normally with electron, then it will be reloaded
  // based on how you define references here
  elemon({
    app: app,
    mainFile: 'main.js',
    bws: [
      {bw: win1, res: ['win1.html', 'win1.js', 'style.css']},
      {bw: win2, res: ['win2.html', 'win2.js', 'style.css']}
    ]
  })
})
```
If you want to make sure that you don't get undefined error when you build your app, you can use `elemon` along with [electron-is-dev](https://github.com/sindresorhus/electron-is-dev) like this:

`npm i electron-is-dev --save`

```js
const {app, BrowserWindow} = require('electron')
const isDev = require('electron-is-dev')

function createWindows () {
  // ...
}

app.on('ready', () => {
  createWindows()

  if (isDev) {
    const elemon = require('elemon') // require elemon if electron is in dev
    elemon({
      app: app,
      mainFile: 'main.js',
      bws: [
        {bw: win1, res: ['win1.html', 'win1.js', 'style.css']},
        {bw: win2, res: ['win2.html', 'win2.js', 'style.css']}
      ]
    })
  }
})
```

That's it. Have fun writing your [Electron](https://github.com/electron/electron) applications.


text:
#include <sstream>
#include <utility>
#include <typeinfo>
#include <memory>
#include <tuple>
#include <string>

#include <gtest/gtest.h>

#include "joynr/MutableMessageFactory.h"
#include "joynr/MutableMessage.h"
#include "joynr/ImmutableMessage.h"
#include "joynr/MessagingQos.h"
#include "joynr/Request.h"
#include "joynr/Reply.h"
#include "joynr/exceptions/JoynrException.h"
#include "joynr/Logger.h"

#include "joynr/types/TestTypes/TEverythingStruct.h"
#include "joynr/types/TestTypes/TEverythingExtendedStruct.h"
#include "joynr/types/TestTypes/TStruct.h"
#include "joynr/types/TestTypes/TEnum.h"
#include "joynr/tests/test/MethodWithErrorEnumExtendedErrorEnum.h"
#include "joynr/types/Localisation/GpsLocation.h"
#include "joynr/types/Localisation/Trip.h"
#include "joynr/types/Version.h"
#include "joynr/system/RoutingTypes/ChannelAddress.h"
#include "joynr/types/GlobalDiscoveryEntry.h"

#include "joynr/serializer/Serializer.h"

template <typename Serializer>
class RequestReplySerializerTest : public ::testing::Test {
public:
    RequestReplySerializerTest()
        : Test(),
          complexParametersDatatypes({
            "joynr.types.TestTypes.TEverythingStruct",
            "joynr.types.TestTypes.TEverythingExtendedStruct",
            "joynr.types.TestTypes.TEnum"
          }),
          primitiveParametersDatatypes({
              "String",
              "Integer",
              "Float",
              "Bool"
          }),
          complexParametersValues(),
          primitiveParametersValues(std::string("Hello World"),
                                    101,
                                    9.99f,
                                    true),
          responseValues(std::string("Hello World"),
                         101,
                         9.99f,
                         true,
                         {1,2,3,4})
    {
    }

protected:

    using OutputStream = muesli::StringOStream;
    using InputStream = muesli::StringIStream;

    using OutputArchive = typename Serializer::template OutputArchive<OutputStream>;
    using InputArchive = typename Serializer::template InputArchive<InputStream>;

    template <typename T>
    std::string serialize(const T& value)
    {
        OutputStream stream;
        OutputArchive oarchive(stream);
        oarchive(value);
        JOYNR_LOG_TRACE(logger, "serialized to " + stream.getString());
        return stream.getString();
    }

    template <typename T>
    void deserialize(std::string str, T& value)
    {
        JOYNR_LOG_TRACE(logger, "trying to deserialize from JSON: {}", str);
        InputStream stream(std::move(str));
        auto iarchive = std::make_shared<InputArchive>(stream);
        (*iarchive)(value);
    }

    // we need to serialize, then deserialize the request/reply to get it in a state to get the data out again
    template <typename T>
    T initOutgoingIncoming(const T& outgoingType)
    {
        T incomingType;
        deserialize(serialize(outgoingType), incomingType);
        return incomingType;
    }

    template <typename Tuple, std::size_t... Indices>
    void setRequestParamsFromTuple(joynr::Request& request, Tuple tuple, std::index_sequence<Indices...>)
    {
        request.setParams(std::move(std::get<Indices>(tuple))...);
    }

    template <typename Tuple, std::size_t... Indices>
    void setReplyResponseFromTuple(joynr::Reply& reply, Tuple tuple, std::index_sequence<Indices...>)
    {
        reply.setResponse(std::move(std::get<Indices>(tuple))...);
    }

    template <typename... Ts>
    joynr::Request initRequest(std::string methodName,
                               std::string requestReplyId,
                               std::vector<std::string> paramDataTypes,
                               std::tuple<Ts...> paramValues)
    {
        joynr::Request outgoingRequest;
        outgoingRequest.setMethodName(methodName);
        outgoingRequest.setRequestReplyId(requestReplyId);
        outgoingRequest.setParamDatatypes(std::move(paramDataTypes));
        setRequestParamsFromTuple(outgoingRequest, paramValues, std::index_sequence_for<Ts...>{});

        return outgoingRequest;
    }

    template <typename T>
    joynr::Reply initReply(std::string requestReplyId,
                           std::shared_ptr<T> error)
    {
        joynr::Reply outgoingReply;
        outgoingReply.setRequestReplyId(requestReplyId);
        outgoingReply.setError(error);
        return initOutgoingIncoming(outgoingReply);
    }

    template <typename... Ts>
    joynr::Reply initReply(std::string requestReplyId,
                           std::tuple<Ts...> responseTuple)
    {
        joynr::Reply outgoingReply;
        outgoingReply.setRequestReplyId(requestReplyId);
        setReplyResponseFromTuple(outgoingReply, responseTuple, std::index_sequence_for<Ts...>{});
        return initOutgoingIncoming(outgoingReply);
    }

    joynr::Request initializeRequestWithComplexValues()
    {
        return initRequest("methodWithComplexParameters",
                           "000-10000-01100",
                           complexParametersDatatypes,
                           complexParametersValues
                           );
    }

    joynr::Request initializeRequestWithPrimitiveValues()
    {
        return initRequest("realMethod",
                           "000-10000-01011",
                           primitiveParametersDatatypes,
                           primitiveParametersValues
                           );
    }

    template <typename Tuple, std::size_t... Indices>
    void compareRequestData(joynr::Request& request, Tuple expectedData, std::index_sequence<Indices...>)
    {
        Tuple extractedData;
        request.getParams(std::get<Indices>(extractedData)...);
        EXPECT_EQ(expectedData, extractedData);
    }

    template <typename Tuple, std::size_t... Indices>
    void compareReplyData(joynr::Reply& reply, Tuple expectedData, std::index_sequence<Indices...>)
    {
        Tuple extractedData;
        reply.getResponse(std::get<Indices>(extractedData)...);
        EXPECT_EQ(expectedData, extractedData);
    }

    template <typename Tuple>
    using IndicesForTuple = std::make_index_sequence<std::tuple_size<Tuple>::value>;

    template <typename Tuple>
    auto getIndicesForTuple(Tuple&)
    {
        return IndicesForTuple<Tuple>{};
    }

    void compareRequestWithComplexValues(joynr::Request& request)
    {
        EXPECT_EQ(complexParametersDatatypes, request.getParamDatatypes());
        compareRequestData(request, complexParametersValues, getIndicesForTuple(complexParametersValues));
    }

    void compareRequestWithPrimitiveValues(joynr::Request& request)
    {
        EXPECT_EQ(primitiveParametersDatatypes, request.getParamDatatypes());
        compareRequestData(request, primitiveParametersValues, getIndicesForTuple(primitiveParametersValues));
    }

    void compareReplyWithExpectedResponse(joynr::Reply& reply)
    {
        ASSERT_TRUE(reply.hasResponse());
        compareReplyData(reply, responseValues, this->getIndicesForTuple(responseValues));
    }

    std::vector<std::string> complexParametersDatatypes;

    std::vector<std::string> primitiveParametersDatatypes;

    std::tuple<joynr::types::TestTypes::TEverythingStruct,
               joynr::types::TestTypes::TEverythingExtendedStruct,
               joynr::types::TestTypes::TEnum::Enum> complexParametersValues;

    std::tuple<std::string, int, float, bool> primitiveParametersValues;

    std::tuple<std::string, int, float, bool, std::vector<int32_t>> responseValues;
    ADD_LOGGER(RequestReplySerializerTest);
};

template <typename Serializer>
INIT_LOGGER(RequestReplySerializerTest<Serializer>);

struct JsonSerializer
{
    template <typename Stream>
    using OutputArchive = muesli::JsonOutputArchive<Stream>;

    template <typename Stream>
    using InputArchive = muesli::JsonInputArchive<Stream>;
};

// typelist of serializers which shall be tested in the following tests
using Serializers = ::testing::Types<JsonSerializer>;

TYPED_TEST_CASE(RequestReplySerializerTest, Serializers);

TYPED_TEST(RequestReplySerializerTest, exampleDeserializerJoynrReplyWithProviderRuntimeException)
{
    auto error = std::make_shared<joynr::exceptions::ProviderRuntimeException>("Message of ProviderRuntimeException");

    joynr::Reply reply = this->initReply("does-not-matter", error);
    auto deserializedError = reply.getError();

    const joynr::exceptions::ProviderRuntimeException * const errorPtr = error.get();
    const joynr::exceptions::JoynrException * const deserializedErrorPtr = deserializedError.get();
    ASSERT_EQ(typeid(*errorPtr), typeid(*deserializedErrorPtr));
    ASSERT_EQ(deserializedError->getMessage(), error->getMessage());
}

TYPED_TEST(RequestReplySerializerTest, exampleDeserializerJoynrReplyWithApplicationException)
{
    using namespace joynr::tests;
    std::string literal = test::MethodWithErrorEnumExtendedErrorEnum::getLiteral(
                test::MethodWithErrorEnumExtendedErrorEnum::BASE_ERROR_TYPECOLLECTION);
    // Create a ApplicationException
    auto error = std::make_shared<joynr::exceptions::ApplicationException>(
                literal,
                std::make_shared<test::MethodWithErrorEnumExtendedErrorEnum>());

    joynr::Reply reply = this->initReply("does-not-matter", error);
    auto deserializedError = reply.getError();

    const joynr::exceptions::ApplicationException * const errorPtr = error.get();
    const joynr::exceptions::JoynrException * const deserializedErrorPtr = deserializedError.get();
    ASSERT_EQ(typeid(*errorPtr), typeid(*deserializedErrorPtr));

    auto deserializedApplicationException = std::dynamic_pointer_cast<joynr::exceptions::ApplicationException>(deserializedError);
    ASSERT_TRUE(deserializedApplicationException != nullptr);
    ASSERT_EQ(*deserializedApplicationException, *error);
}

TYPED_TEST(RequestReplySerializerTest, exampleDeserializerJoynrReply)
{
    joynr::Reply reply = this->initReply("000-10000-01100", this->responseValues);
    this->compareReplyWithExpectedResponse(reply);
}

TYPED_TEST(RequestReplySerializerTest, exampleSerializerTestWithJoynrRequestOfPrimitiveParameters)
{
    // Create, initialize & check request with primitive parameters
    joynr::Request request = this->initializeRequestWithPrimitiveValues();
    this->compareRequestWithPrimitiveValues(request);
}

TYPED_TEST(RequestReplySerializerTest, exampleSerializerTestWithJoynrRequestOfComplexParameters)
{
    // Create, initialize & check request with complex parameters
    joynr::Request request = this->initializeRequestWithComplexValues();
    this->compareRequestWithComplexValues(request);
}

TYPED_TEST(RequestReplySerializerTest, serializeMessage)
{
    // Create a Request
    const bool isLocalMessage = true;
    joynr::Request outgoingRequest = this->initializeRequestWithPrimitiveValues();
    joynr::MutableMessage outgoingMessage = joynr::MutableMessageFactory().createRequest("sender",
                                                                                "receiver",
                                                                                joynr::MessagingQos(),
                                                                                outgoingRequest,
                                                                                isLocalMessage);
    std::unique_ptr<joynr::ImmutableMessage> incomingMessage = outgoingMessage.getImmutableMessage();

    joynr::Request incomingRequest;
    smrf::ByteArrayView bodyView = incomingMessage->getUnencryptedBody();
    std::string serializedPayloadStr(bodyView.data(), bodyView.data() + bodyView.size());
    this->deserialize(serializedPayloadStr, incomingRequest);
    this->compareRequestWithPrimitiveValues(incomingRequest);
}

TYPED_TEST(RequestReplySerializerTest, serialize_deserialize_RequestWithGpsLocationList)
{
    using joynr::types::Localisation::GpsLocation;
    using joynr::types::Localisation::GpsFixEnum;
    using joynr::types::Localisation::Trip;

    using GpsLocationList = std::vector<GpsLocation>;
    GpsLocationList locations;
    locations.emplace_back(1.1, 1.2, 1.3, GpsFixEnum::MODE2D, 1.4, 1.5, 1.6, 1.7, 18, 19, 110);
    locations.emplace_back(2.1, 2.2, 2.3, GpsFixEnum::MODE2D, 2.4, 2.5, 2.6, 2.7, 28, 29, 210);
    locations.emplace_back(3.1, 3.2, 3.3, GpsFixEnum::MODE2D, 3.4, 3.5, 3.6, 3.7, 38, 39, 310);

    Trip trip1(locations, "trip1_name");
    std::string stringParam("contentParam1");
    int intParam = 2;

    auto requestParamTuple = std::make_tuple(stringParam, trip1, intParam);

    joynr::Request request = this->initRequest("", "", {}, requestParamTuple);
    this->compareRequestData(request, requestParamTuple, this->getIndicesForTuple(requestParamTuple));
}

TYPED_TEST(RequestReplySerializerTest, serialize_deserialize_ReplyWithArrayAsResponse)
{
    using joynr::types::GlobalDiscoveryEntry;
    using joynr::types::ProviderQos;
    joynr::types::Version providerVersion(47, 11);
    std::int64_t lastSeenMs = 3;
    std::int64_t expiryDateMs = 7;

    std::string publicKeyId("publicKeyId");
    joynr::system::RoutingTypes::ChannelAddress channelAddress1("localhost", "channelId1");
    std::string serializedAddress1 = joynr::serializer::serializeToJson(channelAddress1);
    joynr::system::RoutingTypes::ChannelAddress channelAddress2("localhost", "channelId2");
    std::string serializedAddress2 = joynr::serializer::serializeToJson(channelAddress2);

    std::vector<GlobalDiscoveryEntry> globalDiscoveryEntries;
    globalDiscoveryEntries.emplace_back(providerVersion, "domain1", "interface1", "participant1", ProviderQos(), lastSeenMs, expiryDateMs, publicKeyId, serializedAddress1);
    globalDiscoveryEntries.emplace_back(providerVersion, "domain2", "interface2", "participant2", ProviderQos(), lastSeenMs, expiryDateMs, publicKeyId, serializedAddress2);

    const std::string requestReplyId("serialize_deserialize_Reply_with_Array_as_Response");

    using ResponseTuple = std::tuple<std::vector<GlobalDiscoveryEntry>>;
    ResponseTuple responseTuple {globalDiscoveryEntries};
    joynr::Reply reply = this->initReply(requestReplyId, responseTuple);
    this->compareReplyData(reply, responseTuple, this->getIndicesForTuple(responseTuple));
}


text:
require 'fluent/load'
require 'fluent/test'

require 'coveralls'
Coveralls.wear!
# prevent Test::Unit's AutoRunner from executing during RSpec's rake task
Test::Unit.run = true if defined?(Test::Unit) && Test::Unit.respond_to?(:run=)


text:
package madgik.exareme.worker.art.executionEngine.statusMgr;

import madgik.exareme.common.art.PlanSessionID;
import madgik.exareme.worker.art.executionEngine.session.ActiveExecutionPlan;
import madgik.exareme.worker.art.executionEngine.session.ConcreteOperatorStatus;

import java.rmi.RemoteException;
import java.util.List;

/**
 * @author herald
 */
public interface PlanSessionStatusManagerInterface {

    boolean hasFinished(PlanSessionID sessionID) throws RemoteException;

    void waitUntilFinish(PlanSessionID sessionID) throws RemoteException;

    boolean hasError(PlanSessionID sessionID) throws RemoteException;

    List<Exception> getErrorList(PlanSessionID sessionID) throws RemoteException;

    ActiveExecutionPlan getActiveExecutionPlan(PlanSessionID sessionID) throws RemoteException;

    ConcreteOperatorStatus getOperatorStatus(String operatorName, PlanSessionID sessionID)
        throws RemoteException;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Saprolegnia pseudocrustosa A. Lund

### Remarks
null


text:
"""Test provisioning module"""

from __future__ import unicode_literals

from test import test_base

class TestProvision(test_base.TestBase):
    """
        Test pyonep provisioning methods.
    """
    # yes, test this
    __test__ = True
    # @myvcr.use_cassette('vcr_cassettes/test_provision_example.yaml')

    def test_provision_example(self):
        """Test provisioning example code"""
        from examples import provisioning
        clonecik, clonerid = self.makeClient(self.cik)
        r = provisioning.provision_example(
            vendorname=self.vendorname,
            vendortoken=self.vendortoken,
            clonerid=clonerid,
            portalcik=self.cik,
            portalrid=self.rid
        )
        self.assertTrue(r, "provisioning example runs without error")


text:
module.exports = function buildVendorExtra () {
  this.emit('done');
};


text:
package com.minkov.thetwitterapp.responses;

/**
 * Created by minkov on 4/23/16.
 */
public class ResponseWithResult<T> {
    private T result;

    public T getResult() {
        return result;
    }

    public void setResult(T result) {
        this.result = result;
    }
}


text:
<?php

class Core_Form_Activity_Meeting_Search extends Zend_Form
{
    public function init()
    {
        $currentUser = Zend_Registry::get('user');

        $title = $this->createElement('text', 'name');
        $title->setLabel('Title');

        $startDateFrom = new Zend_Dojo_Form_Element_DateTextBox('start_date_from');
        $startDateFrom->setLabel('Start Date From');
        $startDateFrom->setFormatLength('long')
                    ->addValidator(new Core_Form_Activity_Task_Validate_DateCompare)
                    ->setInvalidMessage('Invalid date');

        $startDateTo = new Zend_Dojo_Form_Element_DateTextBox('start_date_to');
        $startDateTo->setLabel('Start Date To');
        $startDateTo->setFormatLength('long')
                    ->setInvalidMessage('Invalid date');

        $endDateFrom = new Zend_Dojo_Form_Element_DateTextBox('end_date_from');
        $endDateFrom->setLabel('End Date From');
        $endDateFrom->setFormatLength('long')
            ->setInvalidMessage('Invalid date');

        $endDateTo = new Zend_Dojo_Form_Element_DateTextBox('end_date_to');
        $endDateTo->setLabel('End Date To');
        $endDateTo->setFormatLength('long')
            ->setInvalidMessage('Invalid date');

        $assignedTo = new Zend_Dojo_Form_Element_FilteringSelect('assigned_to');
        $assignedTo->setLabel('Assign to User')
            ->setAutoComplete(true)
            ->setStoreId('userStore')
            ->setStoreType('dojo.data.ItemFileReadStore')
            ->setStoreParams(array('url'=>'/opportunity/assignto'))
            ->setAttrib("searchAttr", "email");

        $statusForm = new Core_Form_Activity_Meeting_Element_MeetingSearchStatus;
        $meetingStatus = $statusForm->getElement();

        $submit = $this->createElement('submit', 'submit')
                       ->setAttrib('class', 'submit_button');

        $this->addElements(
                array($title, $startDateFrom, $startDateTo, $endDateFrom,
                    $endDateTo, $meetingStatus, $assignedTo ,$submit));

       $startDateSearch = $this->addDisplayGroup(array('start_date_from', 'start_date_to'), 'start_date');
        $startDateSearch->getDisplayGroup('start_date')->setLegend('Start Date Search');

        $endDateSearch = $this->addDisplayGroup(array('end_date_from', 'end_date_to'), 'end_date');
        $endDateSearch->getDisplayGroup('end_date')->setLegend('End Date Search');

        $ownerGroup = $this->addDisplayGroup(array('name', 'assigned_to',
                    'task_status_id','meeting_status_id'), 'assignedGroup');

        $submitGroup = $this->addDisplayGroup(array('submit'), 'submitGroup');

        $lineElements = array(
            );
        foreach ($lineElements as $element) {
            $element->setAttrib('size', '18');
            $element->setDecorators(array(
            'ViewHelper',
            'Description',
            'Errors',
            array('Label'),
        ));
        }

       $lineElementsWithoutSizeAttrib = array();
        foreach ($lineElementsWithoutSizeAttrib as $element) {
            $element->setDecorators(array(
            'ViewHelper',
            'Description',
            'Errors',
            array('Label'),
            ));
        }

       $dojoLineItems = array($startDateFrom, $startDateTo, $endDateFrom, $endDateTo);
        foreach ($dojoLineItems as $element) {
            $element->setDecorators(array(
                'DijitElement',
                'Description',
                'Errors',
                array('Label'),
            ));
        }

        $startDateSearch->getDisplayGroup('start_date')->setAttrib('class','search_fieldset_small')
                    ->setLegend('Start date');
        $endDateSearch->getDisplayGroup('end_date')->setAttrib('class','search_fieldset_small')
                    ->setLegend('End date');
    }
}


text:
import { Emitter, Event } from 'vs/base/common/event';
import { IServerChannel } from 'vs/base/parts/ipc/common/ipc';
import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider';
import { Disposable, dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { ILogService } from 'vs/platform/log/common/log';
import { IURITransformer } from 'vs/base/common/uriIpc';
import { URI, UriComponents } from 'vs/base/common/uri';
import { VSBuffer } from 'vs/base/common/buffer';
import { ReadableStreamEventPayload, listenStream } from 'vs/base/common/stream';
import { IStat, IFileReadStreamOptions, IFileWriteOptions, IFileOpenOptions, IFileDeleteOptions, IFileOverwriteOptions, IFileChange, IWatchOptions, FileType, IFileAtomicReadOptions } from 'vs/platform/files/common/files';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { IRecursiveWatcherOptions } from 'vs/platform/files/common/watcher';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';

export interface ISessionFileWatcher extends IDisposable {
	watch(req: number, resource: URI, opts: IWatchOptions): IDisposable;
}

/**
 * A server implementation for a IPC based file system provider client.
 */
export abstract class AbstractDiskFileSystemProviderChannel<T> extends Disposable implements IServerChannel<T> {

	constructor(
		protected readonly provider: DiskFileSystemProvider,
		protected readonly logService: ILogService
	) {
		super();
	}

	call(ctx: T, command: string, arg?: any): Promise<any> {
		const uriTransformer = this.getUriTransformer(ctx);

		switch (command) {
			case 'stat': return this.stat(uriTransformer, arg[0]);
			case 'readdir': return this.readdir(uriTransformer, arg[0]);
			case 'open': return this.open(uriTransformer, arg[0], arg[1]);
			case 'close': return this.close(arg[0]);
			case 'read': return this.read(arg[0], arg[1], arg[2]);
			case 'readFile': return this.readFile(uriTransformer, arg[0], arg[1]);
			case 'write': return this.write(arg[0], arg[1], arg[2], arg[3], arg[4]);
			case 'writeFile': return this.writeFile(uriTransformer, arg[0], arg[1], arg[2]);
			case 'rename': return this.rename(uriTransformer, arg[0], arg[1], arg[2]);
			case 'copy': return this.copy(uriTransformer, arg[0], arg[1], arg[2]);
			case 'cloneFile': return this.cloneFile(uriTransformer, arg[0], arg[1]);
			case 'mkdir': return this.mkdir(uriTransformer, arg[0]);
			case 'delete': return this.delete(uriTransformer, arg[0], arg[1]);
			case 'watch': return this.watch(uriTransformer, arg[0], arg[1], arg[2], arg[3]);
			case 'unwatch': return this.unwatch(arg[0], arg[1]);
		}

		throw new Error(`IPC Command ${command} not found`);
	}

	listen(ctx: T, event: string, arg: any): Event<any> {
		const uriTransformer = this.getUriTransformer(ctx);

		switch (event) {
			case 'fileChange': return this.onFileChange(uriTransformer, arg[0]);
			case 'readFileStream': return this.onReadFileStream(uriTransformer, arg[0], arg[1]);
		}

		throw new Error(`Unknown event ${event}`);
	}

	protected abstract getUriTransformer(ctx: T): IURITransformer;

	protected abstract transformIncoming(uriTransformer: IURITransformer, _resource: UriComponents, supportVSCodeResource?: boolean): URI;

	//#region File Metadata Resolving

	private stat(uriTransformer: IURITransformer, _resource: UriComponents): Promise<IStat> {
		const resource = this.transformIncoming(uriTransformer, _resource, true);

		return this.provider.stat(resource);
	}

	private readdir(uriTransformer: IURITransformer, _resource: UriComponents): Promise<[string, FileType][]> {
		const resource = this.transformIncoming(uriTransformer, _resource);

		return this.provider.readdir(resource);
	}

	//#endregion

	//#region File Reading/Writing

	private async readFile(uriTransformer: IURITransformer, _resource: UriComponents, opts?: IFileAtomicReadOptions): Promise<VSBuffer> {
		const resource = this.transformIncoming(uriTransformer, _resource, true);
		const buffer = await this.provider.readFile(resource, opts);

		return VSBuffer.wrap(buffer);
	}

	private onReadFileStream(uriTransformer: IURITransformer, _resource: URI, opts: IFileReadStreamOptions): Event<ReadableStreamEventPayload<VSBuffer>> {
		const resource = this.transformIncoming(uriTransformer, _resource, true);
		const cts = new CancellationTokenSource();

		const emitter = new Emitter<ReadableStreamEventPayload<VSBuffer>>({
			onLastListenerRemove: () => {

				// Ensure to cancel the read operation when there is no more
				// listener on the other side to prevent unneeded work.
				cts.cancel();
			}
		});

		const fileStream = this.provider.readFileStream(resource, opts, cts.token);
		listenStream(fileStream, {
			onData: chunk => emitter.fire(VSBuffer.wrap(chunk)),
			onError: error => emitter.fire(error),
			onEnd: () => {

				// Forward event
				emitter.fire('end');

				// Cleanup
				emitter.dispose();
				cts.dispose();
			}
		});

		return emitter.event;
	}

	private writeFile(uriTransformer: IURITransformer, _resource: UriComponents, content: VSBuffer, opts: IFileWriteOptions): Promise<void> {
		const resource = this.transformIncoming(uriTransformer, _resource);

		return this.provider.writeFile(resource, content.buffer, opts);
	}

	private open(uriTransformer: IURITransformer, _resource: UriComponents, opts: IFileOpenOptions): Promise<number> {
		const resource = this.transformIncoming(uriTransformer, _resource, true);

		return this.provider.open(resource, opts);
	}

	private close(fd: number): Promise<void> {
		return this.provider.close(fd);
	}

	private async read(fd: number, pos: number, length: number): Promise<[VSBuffer, number]> {
		const buffer = VSBuffer.alloc(length);
		const bufferOffset = 0; // offset is 0 because we create a buffer to read into for each call
		const bytesRead = await this.provider.read(fd, pos, buffer.buffer, bufferOffset, length);

		return [buffer, bytesRead];
	}

	private write(fd: number, pos: number, data: VSBuffer, offset: number, length: number): Promise<number> {
		return this.provider.write(fd, pos, data.buffer, offset, length);
	}

	//#endregion

	//#region Move/Copy/Delete/Create Folder

	private mkdir(uriTransformer: IURITransformer, _resource: UriComponents): Promise<void> {
		const resource = this.transformIncoming(uriTransformer, _resource);

		return this.provider.mkdir(resource);
	}

	protected delete(uriTransformer: IURITransformer, _resource: UriComponents, opts: IFileDeleteOptions): Promise<void> {
		const resource = this.transformIncoming(uriTransformer, _resource);

		return this.provider.delete(resource, opts);
	}

	private rename(uriTransformer: IURITransformer, _source: UriComponents, _target: UriComponents, opts: IFileOverwriteOptions): Promise<void> {
		const source = this.transformIncoming(uriTransformer, _source);
		const target = this.transformIncoming(uriTransformer, _target);

		return this.provider.rename(source, target, opts);
	}

	private copy(uriTransformer: IURITransformer, _source: UriComponents, _target: UriComponents, opts: IFileOverwriteOptions): Promise<void> {
		const source = this.transformIncoming(uriTransformer, _source);
		const target = this.transformIncoming(uriTransformer, _target);

		return this.provider.copy(source, target, opts);
	}

	//#endregion

	//#region Clone File

	private cloneFile(uriTransformer: IURITransformer, _source: UriComponents, _target: UriComponents): Promise<void> {
		const source = this.transformIncoming(uriTransformer, _source);
		const target = this.transformIncoming(uriTransformer, _target);

		return this.provider.cloneFile(source, target);
	}

	//#endregion

	//#region File Watching

	private readonly sessionToWatcher = new Map<string /* session ID */, ISessionFileWatcher>();
	private readonly watchRequests = new Map<string /* session ID + request ID */, IDisposable>();

	private onFileChange(uriTransformer: IURITransformer, sessionId: string): Event<IFileChange[] | string> {

		// We want a specific emitter for the given session so that events
		// from the one session do not end up on the other session. As such
		// we create a `SessionFileWatcher` and a `Emitter` for that session.

		const emitter = new Emitter<IFileChange[] | string>({
			onFirstListenerAdd: () => {
				this.sessionToWatcher.set(sessionId, this.createSessionFileWatcher(uriTransformer, emitter));
			},
			onLastListenerRemove: () => {
				dispose(this.sessionToWatcher.get(sessionId));
				this.sessionToWatcher.delete(sessionId);
			}
		});

		return emitter.event;
	}

	private async watch(uriTransformer: IURITransformer, sessionId: string, req: number, _resource: UriComponents, opts: IWatchOptions): Promise<void> {
		const watcher = this.sessionToWatcher.get(sessionId);
		if (watcher) {
			const resource = this.transformIncoming(uriTransformer, _resource);
			const disposable = watcher.watch(req, resource, opts);
			this.watchRequests.set(sessionId + req, disposable);
		}
	}

	private async unwatch(sessionId: string, req: number): Promise<void> {
		const id = sessionId + req;
		const disposable = this.watchRequests.get(id);
		if (disposable) {
			dispose(disposable);
			this.watchRequests.delete(id);
		}
	}

	protected abstract createSessionFileWatcher(uriTransformer: IURITransformer, emitter: Emitter<IFileChange[] | string>): ISessionFileWatcher;

	//#endregion

	override dispose(): void {
		super.dispose();

		for (const [, disposable] of this.watchRequests) {
			disposable.dispose();
		}
		this.watchRequests.clear();

		for (const [, disposable] of this.sessionToWatcher) {
			disposable.dispose();
		}
		this.sessionToWatcher.clear();
	}
}

export abstract class AbstractSessionFileWatcher extends Disposable implements ISessionFileWatcher {

	private readonly watcherRequests = new Map<number, IDisposable>();

	// To ensure we use one file watcher per session, we keep a
	// disk file system provider instantiated for this session.
	// The provider is cheap and only stateful when file watching
	// starts.
	//
	// This is important because we want to ensure that we only
	// forward events from the watched paths for this session and
	// not other clients that asked to watch other paths.
	private readonly fileWatcher = this._register(new DiskFileSystemProvider(this.logService, { watcher: { recursive: this.getRecursiveWatcherOptions(this.environmentService) } }));

	constructor(
		private readonly uriTransformer: IURITransformer,
		sessionEmitter: Emitter<IFileChange[] | string>,
		private readonly logService: ILogService,
		private readonly environmentService: IEnvironmentService
	) {
		super();

		this.registerListeners(sessionEmitter);
	}

	private registerListeners(sessionEmitter: Emitter<IFileChange[] | string>): void {
		const localChangeEmitter = this._register(new Emitter<readonly IFileChange[]>());

		this._register(localChangeEmitter.event((events) => {
			sessionEmitter.fire(
				events.map(e => ({
					resource: this.uriTransformer.transformOutgoingURI(e.resource),
					type: e.type
				}))
			);
		}));

		this._register(this.fileWatcher.onDidChangeFile(events => localChangeEmitter.fire(events)));
		this._register(this.fileWatcher.onDidWatchError(error => sessionEmitter.fire(error)));
	}

	protected getRecursiveWatcherOptions(environmentService: IEnvironmentService): IRecursiveWatcherOptions | undefined {
		return undefined; // subclasses can override
	}

	protected getExtraExcludes(environmentService: IEnvironmentService): string[] | undefined {
		return undefined; // subclasses can override
	}

	watch(req: number, resource: URI, opts: IWatchOptions): IDisposable {
		const extraExcludes = this.getExtraExcludes(this.environmentService);
		if (Array.isArray(extraExcludes)) {
			opts.excludes = [...opts.excludes, ...extraExcludes];
		}

		this.watcherRequests.set(req, this.fileWatcher.watch(resource, opts));

		return toDisposable(() => {
			dispose(this.watcherRequests.get(req));
			this.watcherRequests.delete(req);
		});
	}

	override dispose(): void {
		super.dispose();

		for (const [, disposable] of this.watcherRequests) {
			disposable.dispose();
		}
		this.watcherRequests.clear();
	}
}


text:
/*global Backbone,templates,$,ViewTransaction,app,_*/
var ViewTransactions = Backbone.View.extend({
    id: "Transaction",
    className: "container",
    initialize: function initialize(options) {
        this.options = options;
        this.template = templates.get('transaction', 'Transactions');
        this.collection.on({
            "add": this.onNewTransaction,
            "remove": this.onDeleteTransaction
        }, this);
        this.options.friendCollection.on({
            "add": this.onNewFriends,
            "remove": this.onRemoveFriends
        }, this);
        this.tAmount = 0;
        this.yAmount = 0;
        this.newFriend = "";
        this.waitingForNewFriend = null;
        _.bindAll(this, "updateScroll");
        $(window).on("resize", this.updateScroll);
        $(window).on("orientationchange", this.updateScroll);
    },
    render: function render() {
        var self = this,
            modelIndex = 0;
        this.$el.html(this.template());
        this.$el.find(".dummyFriends").selectpicker('render');
        $("#" + this.options.parentDiv).append(this.$el);
        for (modelIndex = 0; modelIndex < this.collection.models.length; modelIndex++) {
            this._createTransactionView(this.collection.models[modelIndex]);
        }
        setTimeout(function () {
            for (modelIndex = 0; modelIndex < self.options.friendCollection.models.length; modelIndex++) {
                self.onNewFriends(self.options.friendCollection.models[modelIndex]);
            }
        }, 0);
        this.updateScroll();
        return this;
    },
    events: {
        "tap .dummyDebt": "onAddDebt",
        "tap .dummyCredit": "onAddCredit",
        "NoResult": "onNoResult",
        "ResultFound": "onResultFound"
    },

    onNewTransaction: function onNewTransaction(model, collection) {
        /*jslint unparam:true*/
        var transactionView = this._createTransactionView(model);
        if (model.isNew()) {
            model.save();
            app.scrollDown(transactionView.$el.offset().top - this.$el.find(".dummyTransaction").offset().top + this.$el.find(".dummyTransaction").scrollTop(), this.$el.find(".dummyTransaction"));
        }

    },
    onNoResult: function (event, name) {
        /*jslint unparam:true*/
        this.newFriend = name;
    },
    onResultFound: function (event, name) {
        /*jslint unparam:true*/
        this.newFriend = "";
    },
    onAddDebt: function onAddDebt() {
        this._onAddToCollection(this.$el.find(".dummyAmount").val(), "-", this.$el.find(".dummyFriends").val());
    },
    onAddCredit: function onAddCredit() {
        this._onAddToCollection(this.$el.find(".dummyAmount").val(), "+", this.$el.find(".dummyFriends").val());
    },
    _onAddToCollection: function _onAddToCollection(amount, type, userid) {
        this.$el.find(".has-feedback").removeClass("has-error").find(".form-control-feedback").removeClass("glyphicon-remove");
        var tempModel = new this.collection.model({
            amount: parseInt(amount, 10),
            type: type,
            userid: parseInt(userid, 10)
        });
        if (tempModel.isValid()) {
            if (this.newFriend) {
                this.waitingForNewFriend = {
                    amount: parseInt(amount, 10),
                    type: type
                };

                this.options.friendCollection.create({
                    name: this.newFriend
                }, {
                    wait: true
                });
                this.newFriend = "";
            } else {
                this.collection.add(this.waitingForNewFriend || tempModel, {
                    validate: true
                });
            }
        } else {
            this.$el.find(".has-feedback").addClass("has-error").find(".form-control-feedback").addClass("glyphicon-remove");
        }
    },
    onDeleteTransaction: function onDeleteTransaction(model) {
        if (model.get("type") === model.TYPE.DEBT) {
            this.tAmount -= model.get("amount");
            this.$el.find(".dummyTCount").html(this.tAmount);
        } else {
            this.yAmount -= model.get("amount");
            this.$el.find(".dummyYCount").html(this.yAmount);
        }
    },
    onNewFriends: function (model, collection) {
        /*jslint unparam:true*/
        var self = this;
        self.$el.find("select.dummyFriends").append($("<option>").attr("value", model.get("id")).html(model.get("name")));
        if (self.waitingForNewFriend) {
            self.waitingForNewFriend.userid = model.get("id");
            self._onAddToCollection();
            self.waitingForNewFriend = null;
        }
        self.$el.find(".dummyFriends").selectpicker('refresh');

    },
    onRemoveFriends: function (model, collection) {
        /*jslint unparam:true*/
        var self = this;
        self.$el.find(".dummyFriends option[value=" + model.get("id") + "]").remove();
        this.$el.find(".dummyFriends").selectpicker('refresh');
    },
    _createTransactionView: function _createTransactionView(model) {
        var transactionView = new ViewTransaction({
            model: model,
            friendCollection: this.options.friendCollection
        }).render();
        this.$el.find(".dummyTransaction").append(transactionView.el);
        this._updateOWEValue(model);
        return transactionView;
    },
    _updateOWEValue: function (model) {
        if (model.get("type") === model.TYPE.DEBT) {
            this.tAmount += model.get("amount");
            this.$el.find(".dummyTCount").html(this.tAmount);
        } else {
            this.yAmount += model.get("amount");
            this.$el.find(".dummyYCount").html(this.yAmount);

        }
    },
    updateScroll: function () {
        var height = window.innerHeight -
            parseInt($("#Dynamic").css("padding-top"), 10) -
            this.$el.find(".row:first-child").height() -
            this.$el.find(".row:nth-child(2)").height() -
            parseInt(this.$el.find(".dummyTransaction").css("margin-top"), 10);
        this.$el.find(".dummyTransaction").css("max-height", height);
    },
    remove: function () {
        $(window).off("resize", this.updateCSS);
        $(window).off("orientationchange", this.updateCSS);
        Backbone.View.prototype.remove.apply(this, arguments);
    }
});