text:
<?php

use AdamWathan\BootForms\HorizontalFormBuilder;
use AdamWathan\Form\FormBuilder;

class HorizontalFormBuilderTest extends PHPUnit_Framework_TestCase
{
    private $form;
    private $builder;

    public function setUp()
    {
        $this->builder = new FormBuilder;
        $this->form = new HorizontalFormBuilder($this->builder);
    }

    public function tearDown()
    {
        Mockery::close();
    }

    public function testFormOpen()
    {
        $expected = '<form method="POST" action="" class="form-horizontal">';
        $result = $this->form->open()->render();
        $this->assertEquals($expected, $result);
    }

    public function testFormOpenGet()
    {
        $expected = '<form method="GET" action="" class="form-horizontal">';
        $result = $this->form->open()->get()->render();
        $this->assertEquals($expected, $result);
    }

    public function testFormOpenCustomAction()
    {
        $expected = '<form method="GET" action="/search" class="form-horizontal">';
        $result = $this->form->open()->get()->action('/search')->render();
        $this->assertEquals($expected, $result);
    }

    public function testFormClose()
    {
        $expected = '</form>';
        $result = $this->form->close();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextGroup()
    {
        $expected = '
Email
<input type="text" name="email" id="email" class="form-control">

';
        $result = $this->form->text('Email', 'email')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextGroupWithCustomWidths()
    {
        $this->form->setColumnSizes(['lg' => [3, 9]]);
        $expected = '
Email
<input type="text" name="email" id="email" class="form-control">

';
        $result = $this->form->text('Email', 'email')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextGroupWithMultipleBreakpointSizes()
    {
        $this->form->setColumnSizes(['xs' => [5, 7], 'lg' => [3, 9]]);
        $expected = '
Email
<input type="text" name="email" id="email" class="form-control">

';
        $result = $this->form->text('Email', 'email')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextGroupWithValue()
    {
        $expected = '
Email
<input type="text" name="email" id="email" class="form-control" value="example@example.com">

';
        $result = $this->form->text('Email', 'email')->value('example@example.com')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextGroupWithAttribute()
    {
        $expected = '
Email
<input type="text" name="email" id="email" class="form-control" maxlength="50">

';
        $result = $this->form->text('Email', 'email')->attribute('maxlength', '50')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextGroupWithError()
    {
        $errorStore = Mockery::mock('AdamWathan\Form\ErrorStore\ErrorStoreInterface');
        $errorStore->shouldReceive('hasError')->andReturn(true);
        $errorStore->shouldReceive('getError')->andReturn('Email is required.');

        $this->builder->setErrorStore($errorStore);

        $expected = '
Email
<input type="text" name="email" id="email" class="form-control">
Email is required.

';
        $result = $this->form->text('Email', 'email')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextGroupWithOldInput()
    {
        $oldInput = Mockery::mock('AdamWathan\Form\OldInput\OldInputInterface');
        $oldInput->shouldReceive('hasOldInput')->andReturn(true);
        $oldInput->shouldReceive('getOldInput')->andReturn('example@example.com');

        $this->builder->setOldInputProvider($oldInput);

        $expected = '
Email
<input type="text" name="email" value="example@example.com" id="email" class="form-control">

';
        $result = $this->form->text('Email', 'email')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextGroupWithOldInputAndDefaultValue()
    {
        $oldInput = Mockery::mock('AdamWathan\Form\OldInput\OldInputInterface');
        $oldInput->shouldReceive('hasOldInput')->andReturn(true);
        $oldInput->shouldReceive('getOldInput')->andReturn('example@example.com');

        $this->builder->setOldInputProvider($oldInput);

        $expected = '
Email
<input type="text" name="email" value="example@example.com" id="email" class="form-control">

';
        $result = $this->form->text('Email', 'email')->defaultValue('test@test.com')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextGroupWithDefaultValue()
    {
        $expected = '
Email
<input type="text" name="email" id="email" class="form-control" value="test@test.com">

';
        $result = $this->form->text('Email', 'email')->defaultValue('test@test.com')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextGroupWithOldInputAndError()
    {
        $oldInput = Mockery::mock('AdamWathan\Form\OldInput\OldInputInterface');
        $oldInput->shouldReceive('hasOldInput')->andReturn(true);
        $oldInput->shouldReceive('getOldInput')->andReturn('example@example.com');

        $this->builder->setOldInputProvider($oldInput);

        $errorStore = Mockery::mock('AdamWathan\Form\ErrorStore\ErrorStoreInterface');
        $errorStore->shouldReceive('hasError')->andReturn(true);
        $errorStore->shouldReceive('getError')->andReturn('Email is required.');

        $this->builder->setErrorStore($errorStore);

        $expected = '
Email
<input type="text" name="email" value="example@example.com" id="email" class="form-control">
Email is required.

';
        $result = $this->form->text('Email', 'email')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderPasswordGroup()
    {
        $expected = '
Password
<input type="password" name="password" id="password" class="form-control">

';
        $result = $this->form->password('Password', 'password')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderPasswordGroupDoesntKeepOldInput()
    {
        $oldInput = Mockery::mock('AdamWathan\Form\OldInput\OldInputInterface');
        $oldInput->shouldReceive('hasOldInput')->andReturn(true);
        $oldInput->shouldReceive('getOldInput')->andReturn('password');

        $this->builder->setOldInputProvider($oldInput);

        $expected = '
Password
<input type="password" name="password" id="password" class="form-control">

';
        $result = $this->form->password('Password', 'password')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderPasswordGroupWithError()
    {
        $errorStore = Mockery::mock('AdamWathan\Form\ErrorStore\ErrorStoreInterface');
        $errorStore->shouldReceive('hasError')->andReturn(true);
        $errorStore->shouldReceive('getError')->andReturn('Password is required.');

        $this->builder->setErrorStore($errorStore);

        $expected = '
Password
<input type="password" name="password" id="password" class="form-control">
Password is required.

';
        $result = $this->form->password('Password', 'password')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderButton()
    {
        $expected = '

<button type="button" class="btn btn-default">Click Me</button>

';
        $result = $this->form->button('Click Me')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderButtonWithCustomColumnSizes()
    {
        $this->form->setColumnSizes(['lg' => [3, 9]]);
        $expected = '

<button type="button" class="btn btn-default">Click Me</button>

';
        $result = $this->form->button('Click Me')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderButtonWithMultipleBreakpointSizes()
    {
        $this->form->setColumnSizes(['xs' => [5, 7], 'lg' => [3, 9]]);
        $expected = '

<button type="button" class="btn btn-default">Click Me</button>

';
        $result = $this->form->button('Click Me')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderButtonWithMultipleBreakpointSizesThatDontFillFullWidth()
    {
        $this->form->setColumnSizes(['xs' => [5, 7], 'lg' => [3, 6]]);
        $expected = '

<button type="button" class="btn btn-default">Click Me</button>

';
        $result = $this->form->button('Click Me')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderSubmit()
    {
        $expected = '

<button type="submit" class="btn btn-default">Submit</button>

';
        $result = $this->form->submit()->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderCheckbox()
    {
        $expected = '

<input type="checkbox" name="terms" value="1">Agree to Terms

';
        $result = $this->form->checkbox('Agree to Terms', 'terms')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderCheckboxWithError()
    {
        $errorStore = Mockery::mock('AdamWathan\Form\ErrorStore\ErrorStoreInterface');
        $errorStore->shouldReceive('hasError')->andReturn(true);
        $errorStore->shouldReceive('getError')->andReturn('Must agree to terms.');

        $this->builder->setErrorStore($errorStore);

        $expected = '

<input type="checkbox" name="terms" value="1">Agree to Terms
Must agree to terms.

';
        $result = $this->form->checkbox('Agree to Terms', 'terms')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderCheckboxWithOldInput()
    {
        $oldInput = Mockery::mock('AdamWathan\Form\OldInput\OldInputInterface');
        $oldInput->shouldReceive('hasOldInput')->andReturn(true);
        $oldInput->shouldReceive('getOldInput')->andReturn('1');

        $this->builder->setOldInputProvider($oldInput);

        $expected = '

<input type="checkbox" name="terms" value="1" checked="checked">Agree to Terms

';
        $result = $this->form->checkbox('Agree to Terms', 'terms')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderCheckboxChecked()
    {
        $expected = '

<input type="checkbox" name="terms" value="1" checked="checked">Agree to Terms

';
        $result = $this->form->checkbox('Agree to Terms', 'terms')->check()->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderCheckboxWithAdditionalAttributes()
    {
        $expected = '

<input type="checkbox" name="terms" value="1" data-foo="bar">Agree to Terms

';
        $result = $this->form->checkbox('Agree to Terms', 'terms')->attribute('data-foo', 'bar')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderRadio()
    {
        $expected = '

<input type="radio" name="color" value="red">Red

';
        $result = $this->form->radio('Red', 'color', 'red')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderRadioWithError()
    {
        $errorStore = Mockery::mock('AdamWathan\Form\ErrorStore\ErrorStoreInterface');
        $errorStore->shouldReceive('hasError')->andReturn(true);
        $errorStore->shouldReceive('getError')->andReturn('Sample error');

        $this->builder->setErrorStore($errorStore);
        $expected = '

<input type="radio" name="color" value="red">Red
Sample error

';
        $result = $this->form->radio('Red', 'color', 'red')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderRadioWithOldInput()
    {
        $oldInput = Mockery::mock('AdamWathan\Form\OldInput\OldInputInterface');
        $oldInput->shouldReceive('hasOldInput')->andReturn(true);
        $oldInput->shouldReceive('getOldInput')->andReturn('red');

        $this->builder->setOldInputProvider($oldInput);

        $expected = '

<input type="radio" name="color" value="red" checked="checked">Red

';
        $result = $this->form->radio('Red', 'color', 'red')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextarea()
    {
        $expected = '
Bio
<textarea name="bio" rows="10" cols="50" id="bio" class="form-control"></textarea>

';
        $result = $this->form->textarea('Bio', 'bio')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextareaWithRows()
    {
        $expected = '
Bio
<textarea name="bio" rows="5" cols="50" id="bio" class="form-control"></textarea>

';
        $result = $this->form->textarea('Bio', 'bio')->rows(5)->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextareaWithCols()
    {
        $expected = '
Bio
<textarea name="bio" rows="10" cols="20" id="bio" class="form-control"></textarea>

';
        $result = $this->form->textarea('Bio', 'bio')->cols(20)->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextareaWithOldInput()
    {
        $oldInput = Mockery::mock('AdamWathan\Form\OldInput\OldInputInterface');
        $oldInput->shouldReceive('hasOldInput')->andReturn(true);
        $oldInput->shouldReceive('getOldInput')->andReturn('Sample bio');

        $this->builder->setOldInputProvider($oldInput);
        $expected = '
Bio
<textarea name="bio" rows="10" cols="50" id="bio" class="form-control">Sample bio</textarea>

';
        $result = $this->form->textarea('Bio', 'bio')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderTextareaWithError()
    {
        $errorStore = Mockery::mock('AdamWathan\Form\ErrorStore\ErrorStoreInterface');
        $errorStore->shouldReceive('hasError')->andReturn(true);
        $errorStore->shouldReceive('getError')->andReturn('Sample error');

        $this->builder->setErrorStore($errorStore);
        $expected = '
Bio
<textarea name="bio" rows="10" cols="50" id="bio" class="form-control"></textarea>
Sample error

';
        $result = $this->form->textarea('Bio', 'bio')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderSelect()
    {
        $expected = '
Favorite Color
<select name="color" id="color" class="form-control"><option value="1">Red</option><option value="2">Green</option><option value="3">Blue</option></select>

';

        $options = ['1' => 'Red', '2' => 'Green', '3' => 'Blue'];
        $result = $this->form->select('Favorite Color', 'color', $options)->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderSelectWithError()
    {
        $errorStore = Mockery::mock('AdamWathan\Form\ErrorStore\ErrorStoreInterface');
        $errorStore->shouldReceive('hasError')->andReturn(true);
        $errorStore->shouldReceive('getError')->andReturn('Color is required.');

        $this->builder->setErrorStore($errorStore);

        $expected = '
Favorite Color
<select name="color" id="color" class="form-control"><option value="1">Red</option><option value="2">Green</option><option value="3">Blue</option></select>
Color is required.

';

        $options = ['1' => 'Red', '2' => 'Green', '3' => 'Blue'];
        $result = $this->form->select('Favorite Color', 'color', $options)->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderSelectWithOldInput()
    {
        $oldInput = Mockery::mock('AdamWathan\Form\OldInput\OldInputInterface');
        $oldInput->shouldReceive('hasOldInput')->andReturn(true);
        $oldInput->shouldReceive('getOldInput')->andReturn('2');

        $this->builder->setOldInputProvider($oldInput);

        $expected = '
Favorite Color
<select name="color" id="color" class="form-control"><option value="1">Red</option><option value="2" selected>Green</option><option value="3">Blue</option></select>

';

        $options = ['1' => 'Red', '2' => 'Green', '3' => 'Blue'];
        $result = $this->form->select('Favorite Color', 'color', $options)->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderDateGroup()
    {
        $expected = '
Birthday
<input type="date" name="birthday" id="birthday" class="form-control">

';
        $result = $this->form->date('Birthday', 'birthday')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderDateTimeLocalGroup()
    {
        $expected = '
Date & time of birth
<input type="datetime-local" name="dob" id="dob" class="form-control">

';
        $result = $this->form->dateTimeLocal('Date & time of birth', 'dob')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderFileGroup()
    {
        $expected = '
File
<input type="file" name="file" id="file">

';
        $result = $this->form->file('File', 'file')->render();
        $this->assertEquals($expected, $result);
    }

    public function testRenderFileGroupWithError()
    {
        $errorStore = Mockery::mock('AdamWathan\Form\ErrorStore\ErrorStoreInterface');
        $errorStore->shouldReceive('hasError')->andReturn(true);
        $errorStore->shouldReceive('getError')->andReturn('Sample error');

        $this->builder->setErrorStore($errorStore);
        $expected = '
File
<input type="file" name="file" id="file">
Sample error

';
        $result = $this->form->file('File', 'file')->render();
        $this->assertEquals($expected, $result);
    }
}


text:
#include "fennel/common/CommonPreamble.h"
#include "fennel/calculator/ExtendedInstructionTable.h"
#include "fennel/calculator/SqlDate.h"

FENNEL_BEGIN_CPPFILE("$Id$");

using namespace boost::local_time;

void
CastDateToStrA(
    RegisterRef<char*>* result,
    RegisterRef<int64_t>* date)
{
    assert(date->type() == STANDARD_TYPE_INT_64);
    assert(StandardTypeDescriptor::isTextArray(result->type()));

    if (date->isNull()) {
        result->toNull();
        result->length(0);
    } else {
        // Produce a result like "2004-05-12"
        int64_t v = date->value() * 1000;
        int len = SqlDateToStr<1, 1, SQLDATE>(
            result->pointer(), result->storage(), v,
            (result->type() == STANDARD_TYPE_CHAR ? true : false));
        result->length(len);
    }
}

void
CastTimeToStrA(
    RegisterRef<char*>* result,
    RegisterRef<int64_t>* time)
{
    assert(time->type() == STANDARD_TYPE_INT_64);
    assert(StandardTypeDescriptor::isTextArray(result->type()));

    if (time->isNull()) {
        result->toNull();
        result->length(0);
    } else {
        int64_t v = time->value() * 1000;
        int len = SqlDateToStr<1, 1, SQLTIME>(
            result->pointer(), result->storage(), v,
            (result->type() == STANDARD_TYPE_CHAR ? true : false));
        result->length(len);
    }
}

void
CastTimestampToStrA(
    RegisterRef<char*>* result,
    RegisterRef<int64_t>* tstamp)
{
    assert(tstamp->type() == STANDARD_TYPE_INT_64);
    assert(StandardTypeDescriptor::isTextArray(result->type()));

    if (tstamp->isNull()) {
        result->toNull();
        result->length(0);
    } else {
        int64_t v = tstamp->value() * 1000;
        int len = SqlDateToStr<1, 1, SQLTIMESTAMP>(
            result->pointer(), result->storage(), v,
            (result->type() == STANDARD_TYPE_CHAR ? true : false));
        result->length(len);
    }
}

void
CastStrAToDate(
    RegisterRef<int64_t>* result,
    RegisterRef<char*>* dateStr)
{
    assert(result->type() == STANDARD_TYPE_INT_64);
    assert(StandardTypeDescriptor::isTextArray(dateStr->type()));

    if (dateStr->isNull()) {
        result->toNull();
    } else {
        result->value(
            SqlStrToDate<1, 1, SQLDATE>(
                dateStr->pointer(),
                dateStr->stringLength()));
    }
}

void
CastStrAToTime(
    RegisterRef<int64_t>* result,
    RegisterRef<char*>* timeStr)
{
    assert(result->type() == STANDARD_TYPE_INT_64);
    assert(StandardTypeDescriptor::isTextArray(timeStr->type()));

    if (timeStr->isNull()) {
        result->toNull();
    } else {
        result->value(
            SqlStrToDate<1, 1, SQLTIME>(
                timeStr->pointer(),
                timeStr->stringLength()));
    }
}

void
CastStrAToTimestamp(
    RegisterRef<int64_t>* result,
    RegisterRef<char*>* timestampStr)
{
    assert(result->type() == STANDARD_TYPE_INT_64);
    assert(StandardTypeDescriptor::isTextArray(timestampStr->type()));

    if (timestampStr->isNull()) {
        result->toNull();
    } else {
        result->value(
            SqlStrToDate<1, 1, SQLTIMESTAMP>(
                timestampStr->pointer(),
                timestampStr->stringLength()));
    }
}

// for debugging - see the millisec value passed through to fennel.
void CastDateTimeToInt64(
    RegisterRef<int64_t>* result,
    RegisterRef<int64_t>* dtime)
{
    assert(result->type() == STANDARD_TYPE_INT_64);
    assert(dtime->type() == STANDARD_TYPE_INT_64);

    if (dtime->isNull()) {
        result->toNull();
    } else {
        result->value(dtime->value());
    }
}

void CurrentTime(RegisterRef<int64_t>* result)
{
    assert(result->type() == STANDARD_TYPE_INT_64);
    result->value(UniversalTime());
}

void CurrentTimestamp(RegisterRef<int64_t>* result)
{
    assert(result->type() == STANDARD_TYPE_INT_64);
    result->value(UniversalTimestamp());
}

void CurrentTime(
    RegisterRef<int64_t>* result,
    RegisterRef<int32_t>* precision)
{
    assert(result->type() == STANDARD_TYPE_INT_64);
    assert(precision->type() == STANDARD_TYPE_INT_32);

    // precision is ignored for now
    result->value(UniversalTime());
}

void CurrentTimestamp(
    RegisterRef<int64_t>* result,
    RegisterRef<int32_t>* precision)
{
    assert(result->type() == STANDARD_TYPE_INT_64);
    assert(precision->type() == STANDARD_TYPE_INT_32);

    // precision is ignored for now
    result->value(UniversalTimestamp());
}

void LocalTime(
    RegisterRef<int64_t>* result,
    RegisterRef<char *>* tz)
{
    assert(result->type() == STANDARD_TYPE_INT_64);
    assert(tz->type() == STANDARD_TYPE_CHAR);

    time_zone_ptr tzPtr(
        new posix_time_zone(
            string(tz->pointer(), tz->stringLength())));

    result->value(LocalTime(tzPtr));
}

void LocalTimestamp(
    RegisterRef<int64_t>* result,
    RegisterRef<char *>* tz)
{
    assert(result->type() == STANDARD_TYPE_INT_64);
    assert(tz->type() == STANDARD_TYPE_CHAR);

    time_zone_ptr tzPtr(
        new posix_time_zone(
            string(tz->pointer(), tz->stringLength())));

    result->value(LocalTimestamp(tzPtr));
}

void LocalTime(
    RegisterRef<int64_t>* result,
    RegisterRef<char *>* tz,
    RegisterRef<int32_t>* precision)
{
    assert(result->type() == STANDARD_TYPE_INT_64);
    assert(tz->type() == STANDARD_TYPE_CHAR);
    assert(precision->type() == STANDARD_TYPE_INT_32);

    time_zone_ptr tzPtr(
        new posix_time_zone(
            string(tz->pointer(), tz->stringLength())));

    // precision is ignored for now
    result->value(LocalTime(tzPtr));
}

void LocalTimestamp(
    RegisterRef<int64_t>* result,
    RegisterRef<char *>* tz,
    RegisterRef<int32_t>* precision)
{
    assert(result->type() == STANDARD_TYPE_INT_64);
    assert(tz->type() == STANDARD_TYPE_CHAR);
    assert(precision->type() == STANDARD_TYPE_INT_32);

    time_zone_ptr tzPtr(
        new posix_time_zone(
            string(tz->pointer(), tz->stringLength())));

    // precision is ignored for now
    result->value(LocalTimestamp(tzPtr));
}

void
ExtDateTimeRegister(ExtendedInstructionTable* eit)
{
    assert(eit != NULL);

    vector<StandardTypeDescriptorOrdinal> params_V_I64;
    params_V_I64.push_back(STANDARD_TYPE_VARCHAR);
    params_V_I64.push_back(STANDARD_TYPE_INT_64);

    vector<StandardTypeDescriptorOrdinal> params_C_I64;
    params_C_I64.push_back(STANDARD_TYPE_CHAR);
    params_C_I64.push_back(STANDARD_TYPE_INT_64);

    vector<StandardTypeDescriptorOrdinal> params_I64_V;
    params_I64_V.push_back(STANDARD_TYPE_INT_64);
    params_I64_V.push_back(STANDARD_TYPE_VARCHAR);

    vector<StandardTypeDescriptorOrdinal> params_I64_C;
    params_I64_C.push_back(STANDARD_TYPE_INT_64);
    params_I64_C.push_back(STANDARD_TYPE_CHAR);

    vector<StandardTypeDescriptorOrdinal> params_I64_C_I32;
    params_I64_C_I32.push_back(STANDARD_TYPE_INT_64);
    params_I64_C_I32.push_back(STANDARD_TYPE_CHAR);
    params_I64_C_I32.push_back(STANDARD_TYPE_INT_32);

    vector<StandardTypeDescriptorOrdinal> params_I64_I64;
    params_I64_I64.push_back(STANDARD_TYPE_INT_64);
    params_I64_I64.push_back(STANDARD_TYPE_INT_64);

    vector<StandardTypeDescriptorOrdinal> params_I64;
    params_I64.push_back(STANDARD_TYPE_INT_64);

    vector<StandardTypeDescriptorOrdinal> params_I64_I32;
    params_I64_I32.push_back(STANDARD_TYPE_INT_64);
    params_I64_I32.push_back(STANDARD_TYPE_INT_32);

    // date -> str
    eit->add(
        "CastDateToStrA", params_V_I64,
        (ExtendedInstruction2<char*, int64_t>*) NULL,
        &CastDateToStrA);

    eit->add(
        "CastDateToStrA", params_C_I64,
        (ExtendedInstruction2<char*, int64_t>*) NULL,
        &CastDateToStrA);

    eit->add(
        "CastTimeToStrA", params_V_I64,
        (ExtendedInstruction2<char*, int64_t>*) NULL,
        &CastTimeToStrA);

    eit->add(
        "CastTimeToStrA", params_C_I64,
        (ExtendedInstruction2<char*, int64_t>*) NULL,
        &CastTimeToStrA);

    eit->add(
        "CastTimestampToStrA", params_V_I64,
        (ExtendedInstruction2<char*, int64_t>*) NULL,
        &CastTimestampToStrA);

    eit->add(
        "CastTimestampToStrA", params_C_I64,
        (ExtendedInstruction2<char*, int64_t>*) NULL,
        &CastTimestampToStrA);

    // str -> date
    eit->add(
        "CastStrAToDate", params_I64_V,
        (ExtendedInstruction2<int64_t, char*>*) NULL,
        &CastStrAToDate);

    eit->add(
        "CastStrAToDate", params_I64_C,
        (ExtendedInstruction2<int64_t, char*>*) NULL,
        &CastStrAToDate);

    eit->add(
        "CastStrAToTime", params_I64_V,
        (ExtendedInstruction2<int64_t, char*>*) NULL,
        &CastStrAToTime);

    eit->add(
        "CastStrAToTime", params_I64_C,
        (ExtendedInstruction2<int64_t, char*>*) NULL,
        &CastStrAToTime);

    eit->add(
        "CastStrAToTimestamp", params_I64_V,
        (ExtendedInstruction2<int64_t, char*>*) NULL,
        &CastStrAToTimestamp);

    eit->add(
        "CastStrAToTimestamp", params_I64_C,
        (ExtendedInstruction2<int64_t, char*>*) NULL,
        &CastStrAToTimestamp);

    // others
    eit->add(
        "CastDateTimeToInt64", params_I64_I64,
        (ExtendedInstruction2<int64_t, int64_t>*) NULL,
        &CastDateTimeToInt64);

    eit->add(
        "LocalTime2", params_I64_C,
        (ExtendedInstruction2<int64_t, char *>*) NULL,
        &LocalTime);

    eit->add(
        "LocalTimestamp2", params_I64_C,
        (ExtendedInstruction2<int64_t, char *>*) NULL,
        &LocalTimestamp);

    eit->add(
        "LocalTime3", params_I64_C_I32,
        (ExtendedInstruction3<int64_t, char *, int32_t>*) NULL,
        &LocalTime);

    eit->add(
        "LocalTimestamp3", params_I64_C_I32,
        (ExtendedInstruction3<int64_t, char *, int32_t>*) NULL,
        &LocalTimestamp);

    eit->add(
        "CurrentTime1", params_I64,
        (ExtendedInstruction1<int64_t>*) NULL,
        &CurrentTime);

    eit->add(
        "CurrentTimestamp1", params_I64,
        (ExtendedInstruction1<int64_t>*) NULL,
        &CurrentTimestamp);

    eit->add(
        "CurrentTime2", params_I64_I32,
        (ExtendedInstruction2<int64_t, int32_t>*) NULL,
        &CurrentTime);

    eit->add(
        "CurrentTimestamp2", params_I64_I32,
        (ExtendedInstruction2<int64_t, int32_t>*) NULL,
        &CurrentTimestamp);

}

FENNEL_END_CPPFILE("$Id$");

// End ExtDateTime.cpp

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;

namespace BenchmarkDotNet.Validators
{
    public class BaselineValidator : IValidator
    {
        public static readonly BaselineValidator FailOnError = new BaselineValidator();

        private BaselineValidator() { }

        public bool TreatsWarningsAsErrors => true; // it is a must!

        public IEnumerable<ValidationError> Validate(ValidationParameters input)
        {
            var allBenchmarks = input.Benchmarks.ToImmutableArray();
            var orderProvider = input.Config.Orderer;

            var benchmarkLogicalGroups = allBenchmarks
                .Select(benchmark => orderProvider.GetLogicalGroupKey(allBenchmarks, benchmark))
                .ToArray();

            var logicalGroups = benchmarkLogicalGroups.Distinct().ToArray();
            foreach (string logicalGroup in logicalGroups)
            {
                var benchmarks = allBenchmarks.Where((benchmark, index) => benchmarkLogicalGroups[index] == logicalGroup).ToArray();
                int methodBaselineCount = benchmarks.Select(b => b.Descriptor).Distinct().Count(it => it.Baseline);
                int jobBaselineCount = benchmarks.Select(b => b.Job).Distinct().Count(it => it.Meta.Baseline);
                string className = benchmarks.First().Descriptor.Type.Name;

                if (methodBaselineCount > 1)
                    yield return CreateError("benchmark method", "Baseline = true", logicalGroup, className, methodBaselineCount.ToString());

                if (jobBaselineCount > 1)
                    yield return CreateError("job", "Baseline = true", logicalGroup, className, jobBaselineCount.ToString());
            }
        }

        private ValidationError CreateError(string subject, string property, string groupName, string className, string actual) =>
            new ValidationError(
                TreatsWarningsAsErrors,
                $"Only 1 {subject} in a group can have \"{property}\" applied to it, group {groupName} in class {className} has {actual}");
    }
}


text:
layout: post
title: "Great stories happen to people who can tell them."
description: "Great stories happen to people who can tell them."
comments: false
category: "Links"
keywords: "Links, extravaganza, Tech, IT, Microservices, NodeJs, C#, Javascript, Solution architecture"
redirect_from: "/2016/10/14/soon-link-generality-entered-scene"
---
## Categories ##
 * [My favorites](#favorites)
 * [Ideas, Thoughts, comments and process](#ideas)
 * [Agile](#agile)
 * [Architecture & Software development practices](#development)
 * [.Net & C#](#net)
 * [Javascript](#javascript)
 * [NodeJs](#nodejs)
 * [Other Languages](#polygloting)
 * [Web including html and css](#web)
 * [Tools](#tools)
 * [Releases](#releases)
 * [Conferences](#conferences)
 * [Monitoring](#monitoring)
 * [Cloud, DevOps and Security](#devops)
 * [Containers](#containers)
 * [Machine Learning, IoT and other very fancy buzzwords](#iot)
 * [Videos & Podcasts](#videos)
 * [Books](#books)
 * [Made me Laugh, Cry or just news](#news)

# My favorites #
 * [Service Design: Isn't It Just Ux With A Different Name? - Gds Design Notes](https://designnotes.blog.gov.uk/2016/10/04/service-design-isnt-it-just-ux-with-a-different-name/)
 * [Why Big Companies Need Lean Startup Techniques - Smarter With Gartner](http://www.gartner.com/smarterwithgartner/why-big-companies-need-lean-startup-techniques/)
 * [Stakeholder Collaboration - Gregormeyenberg.de](http://blog.gregormeyenberg.de/2016/09/19/stakeholder-collaboration/?__s=amwwwz5judsp1dsfgko7)
 * [Versions Are Evil – How To Do Without In Your Apis – Serialseb](https://serialseb.com/speaker/versions-are-evil/)
 * [Freedom and responsibility culture](http://www.slideshare.net/reed2001/culture-1798664/3-Seven_Aspects_of_our_Culture)
 * ["Inclusive Markup" View Source Conference Talk By Estelle Weyl - Youtube](https://www.youtube.com/watch?v=FN3g39bnSRA)
 * [Introducing Steeltoe Rc1, A Microservices Toolkit For .Net - Pivotal](https://blog.pivotal.io/pivotal-cloud-foundry/products/introducing-steeltoe-rc1-a-microservices-toolkit-for-net) + [Steeltoe Oss](https://github.com/SteeltoeOSS)
 * [Facebook React.js License - El Camino Legal Llp - Tech And Media](http://www.elcaminolegal.com/single-post/2016/10/04/Facebook-Reactjs-License)
 * [Getters And Setters Are Evil](http://www.marcus-biel.com/getters-and-setters-are-evil/?__s=amwwwz5judsp1dsfgko7)

## Ideas, Thoughts, comments  ##
 * [Maintaining Open-source Software Projects - Digitalocean](https://www.digitalocean.com/community/tutorials/maintaining-open-source-software-projects)
 * [Stop Adopting Other People's Anxiety](https://deardesignstudent.com/don-t-adopt-anxiety-6662515d2416#.z0t58eycz)
 * [The Architecture Interview — Susan J. Fowler](http://www.susanjfowler.com/blog/2016/10/7/the-architecture-interview)

## Agile, Organizations and process ##
 * [Scrum Er Ikke En Løsning](http://qed.dk/therese-hansen/2016/10/10/scrum-er-ikke-en-loesning/)
 * [Barriers To Devops In Government – Medium](https://medium.com/@cote/barriers-to-devops-in-government-72d657ecf722#.cxdwmlw4t)
 * [Yow! West 2016 Paul Rayner - Eventstorming - Youtube](https://www.youtube.com/watch?v=bXm8Cznyb_s&__s=amwwwz5judsp1dsfgko7)

## Architecture & Software development practices  ##
 * [Introducing Security Practices Within The Health Domain - Thoughtworks](https://www.thoughtworks.com/insights/blog/introducing-security-practices-within-health-domain)
 * [Distributed Systems Vs Compositionality—roland Kuhn - Youtube](https://www.youtube.com/watch?v=LcUIIRqXwTY)
 * [Cqrs/es – Or Is It? – Adaptech Solutions](http://adaptechsolutions.net/cqrs-es-or-is-it/?__s=amwwwz5judsp1dsfgko7)
 * [Renato Cavalcanti - Functional And Reactive Event Sourced Applications - Youtube](https://www.youtube.com/watch?v=A-oAFV5__4k&feature=youtu.be&__s=amwwwz5judsp1dsfgko7)
 * [Event Storming For Fun And Profit - Skillscast - 9th June 2016](https://skillsmatter.com/skillscasts/8003-event-storming-for-fun-and-profit)
 * [Service-based Architecture As An Alternative To Microservice Architecture](https://www.infoq.com/news/2016/10/service-based-architecture)
 * [Oliver Gierke - Evolving Distributed Systems](http://olivergierke.de/2016/10/evolving-distributed-systems/)
 * [Kafka Streams With Jay Kreps - Software Engineering Daily](http://softwareengineeringdaily.com/2016/10/07/kafka-streams-with-jay-kreps/)
 * [Pacts To The Rescue! Making Your Microservices Play Nicely Together ](https://www.youtube.com/watch?v=kz3YI2YGODs)
 * [Business Process Management In A "Microservices World" – Red Hat Developer Blog](http://developers.redhat.com/blog/2016/10/10/business-process-management-in-a-microservices-world/)
 * [Oliver Gierke - Evolving Distributed Systems](http://olivergierke.de/2016/10/evolving-distributed-systems/)
 * [Eventsourcing: Why Are People Into That? – Adaptech Solutions](http://adaptechsolutions.net/eventsourcing-why-are-people-into-that/?__s=amwwwz5judsp1dsfgko7)
 * [Developing Transactional Microservices Using Aggregates, Event Sourcing And Cqrs - Part 1](https://www.infoq.com/articles/microservices-aggregates-events-cqrs-part-1-richardson?__s=amwwwz5judsp1dsfgko7)
 * [Event Sourcing, Cqrs, Stream Processing And Apache Kafka: What's The Connection? - Confluent](http://www.confluent.io/blog/event-sourcing-cqrs-stream-processing-apache-kafka-whats-connection/?__s=amwwwz5judsp1dsfgko7)

## **.Net, C, F (& Powershell)**   ##
 * [C# 7.0 – And Beyond!](https://channel9.msdn.com/Shows/Dev-Channel/Csharp70-and-beyond)
 * [Cutting Edge - Event-command-saga Approach For Business Logic](https://msdn.microsoft.com/magazine/mt742866?__s=amwwwz5judsp1dsfgko7)
 * [Dockerizing Nerd Dinner: Part 1, Running Legacy Asp.net Apps In Docker - Elton Stoneman](https://blog.sixeyed.com/dockerizing-nerd-dinner-part-1-running-a-legacy-asp-net-app-in-a-windows-container/) - maybe Sitecore?

## Other Languages   ##
 * [Handling Eventual Consistency In Jvm Microservices With Event Sourcing](https://www.youtube.com/watch?v=53DVkaW5Fb0)
 * [Learning Systems Programming With Rust - Julia Evans](https://jvns.ca/blog/2016/09/11/rustconf-keynote/)
 * [Building High Performance Apis In Go Using Grpc And Protocol Buffers – Medium](https://medium.com/@shijuvar/building-high-performance-apis-in-go-using-grpc-and-protocol-buffers-2eda5b80771b#.f5hd467un)
 * [Exploring Cli Best Practices // Localytics Engineering Blog](http://eng.localytics.com/exploring-cli-best-practices/)
 * [Building Distributed Systems Without Docker, Using Docker Plumbing Pr…](http://www.slideshare.net/chanezon/building-distributed-systems-without-docker-using-docker-plumbing-projects-linuxcon-berlin-2016)
 * [Bryan Hunter - Cqrs With Erlang](https://vimeo.com/97318824?__s=amwwwz5judsp1dsfgko7)

## Javascript   ##
 * [State of Js 2016](http://stateofjs.com/2016/introduction/)
 * [Hyperform - Capture Form Validation Back From The Browser](https://hyperform.js.org/)
 * [Npm Vs Yarn Cheat Sheet](https://shift.infinite.red/npm-vs-yarn-cheat-sheet-8755b092e5cc#.y586t8bdv)

## NodeJs  ##
 * [Zeit/micro: Async Http Microservices Made Easy](https://github.com/zeit/micro)
 * [Yarn: A new package manager for JavaScript](https://code.facebook.com/posts/1840075619545360)

## Web including html and css   ##
 * [Module Bundling With Webpack: Getting Started Guide - Codementor](https://www.codementor.io/javascript/tutorial/module-bundler-webpack-getting-started-guide)
 * [The Average Web Page From Top Twenty Google Results Study](https://www.advancedwebranking.com/html/)
 * [Usability Testing Of Inline Form Validation: 40% Don't Have It, 20% Get It Wrong - Articles - Baymard Institute](https://baymard.com/blog/inline-form-validation)
 * [Andreleon/critical-style-snapshot: Capture Css Above The Fold With One Click.](https://github.com/andreleon/critical-style-snapshot)

## Tools and things from Github  ##
 * [Facebook/rocksdb: A Library That Provides An Embeddable, Persistent Key-value Store For Fast Storage.](https://github.com/facebook/rocksdb)
 * [Richard's Toolbox](http://richardstoolbox.com/)
 * [Cake - Cake For Visual Studio Released](http://cakebuild.net/blog/2016/09/cake-for-visual-studio)
 * [Tracing Http Request Latency In Go With Opentracing – Opentracing – Medium](https://medium.com/opentracing/tracing-http-request-latency-in-go-with-opentracing-7cc1282a100a#.hqnib1vmk)

## Cloud, DevOps and Security ##
 * [Continuous Delivery Anti-patterns From The Wild - Matthew Skelton- Ip…](http://www.slideshare.net/SkeltonThatcher/continuous-delivery-antipatterns-from-the-wild-matthew-skelton-ipexpo-europe)
 * [Open-guides/og-aws: 📙 Amazon Web Services — A Practical Guide](https://github.com/open-guides/og-aws)
 * [6 Tips And Tricks For Aws Command Line Ninjas - Codementor](https://www.codementor.io/aws/tutorial/tips-and-tricks-aws-command-line-ninjas)
 * [Uncovering The Magic: How Serverless Platforms Really Work! – Openwhisk – Medium](https://medium.com/openwhisk/uncovering-the-magic-how-serverless-platforms-really-work-3cb127b05f71#.gd19zwc51)

## Containers  ##
 * [A Comparative Study Of Docker Engine On Windows Server Vs Linux Platform – Collabnix](http://collabnix.com/archives/1965)
 * [A Checklist For Docker In The Enterprise](https://medium.com/zwischenzugs/a-checklist-for-docker-in-the-enterprise-d69f2ae3091b#.mgeh1dr7y)
 * [Docker Gotchas - Dan Sosedoff](http://sosedoff.com/2016/10/05/docker-gotchas.html)
 * [Managing Performance Of Microservices In Containers - Youtube](https://www.youtube.com/watch?v=_zuucHJzssc)
 * [Image2docker: A New Tool For Prototyping Windows Vm Conversions - Docker Blog](https://blog.docker.com/2016/09/image2docker-prototyping-windows-vm-conversions/)
 * [What Even Is A Container: Namespaces And Cgroups - Julia Evans](https://jvns.ca/blog/2016/10/10/what-even-is-a-container/)

## Monitoring and Performance  ##
 * [Elasticsearch And Kafka For High Speed Log Tracking - Dropbox Tech Blog](https://blogs.dropbox.com/tech/2016/10/netflash-tracking-dropbox-network-traffic-in-real-time-with-elasticsearch/)
 * [A Monitoring Solution For Docker Hosts, Containers And Containerized Services](https://stefanprodan.com/2016/a-monitoring-solution-for-docker-hosts-containers-and-containerized-services/)
 * [Sflow: Collecting Docker Swarm Service Metrics](http://blog.sflow.com/2016/10/collecting-docker-swarm-service-metrics.html)
 * [How To Monitor Elasticsearch Performance](https://www.datadoghq.com/blog/monitor-elasticsearch-performance-metrics/)

## Machine Learning, IoT and other very fancy buzzwords  ##
 * [Off-the-shelf Hacker: Create An Early Warning Detector With Passive Infrared Sensors - The New Stack](http://thenewstack.io/off-shelf-hacker-create-early-warning-detector-passive-infrared-sensors/)

## Videos, presentations & Podcasts  ##

## Books and Papers  ##

## Releases  ##

## Conferences or Courses ##

## Made me Laugh, Cry or just news.  ##
 * [Free Tool Protects Mac Users From Webcam Surveillance - Threatpost - The First Stop For Security News](https://threatpost.com/free-tool-protects-mac-users-from-webcam-surveillance/121154/)
 * [Cloudy Gamer: Playing Overwatch On Azure's New Monster Gpu Instances](http://lg.io/2016/10/12/cloudy-gamer-playing-overwatch-on-azures-new-monster-gpu-instances.html)


text:
"use strict";
var vows = require('vows'),
    fs = require('fs'),
    path = require('path'),
    sandbox = require('sandboxed-module'),
    log4js = require('../lib/log4js'),
    assert = require('assert'),
    zlib = require('zlib'),
    EOL = require('os').EOL || '\n';

log4js.clearAppenders();

function remove(filename) {
  try {
    fs.unlinkSync(filename);
  } catch (e) {
    //doesn't really matter if it failed
  }
}

vows.describe('log4js fileAppender').addBatch({
  'adding multiple fileAppenders': {
    topic: function topic() {
      var listenersCount = process.listeners('exit').length,
          logger = log4js.getLogger('default-settings'),
          count = 5,
          logfile;

      while (count--) {
        logfile = path.join(__dirname, '/fa-default-test' + count + '.log');
        log4js.addAppender(require('../lib/appenders/file').appender(logfile), 'default-settings');
      }

      return listenersCount;
    },

    'does not add more than one `exit` listeners': function doesNotAddMoreThanOneExitListeners(initialCount) {
      assert.ok(process.listeners('exit').length <= initialCount + 1);
    }
  },

  'exit listener': {
    topic: function topic() {
      var exitListener,
          openedFiles = [],
          fileAppender = sandbox.require('../lib/appenders/file', {
        globals: {
          process: {
            on: function on(evt, listener) {
              exitListener = listener;
            }
          }
        },
        requires: {
          '../streams': {
            RollingFileStream: function RollingFileStream(filename) {
              openedFiles.push(filename);

              this.end = function () {
                openedFiles.shift();
              };

              this.on = function () {};
            }
          }
        }
      });
      for (var i = 0; i < 5; i += 1) {
        fileAppender.appender('test' + i, null, 100);
      }
      assert.isNotEmpty(openedFiles);
      exitListener();
      return openedFiles;
    },
    'should close all open files': function shouldCloseAllOpenFiles(openedFiles) {
      assert.isEmpty(openedFiles);
    }
  },

  'with default fileAppender settings': {
    topic: function topic() {
      var that = this,
          testFile = path.join(__dirname, '/fa-default-test.log'),
          logger = log4js.getLogger('default-settings');
      remove(testFile);

      log4js.clearAppenders();
      log4js.addAppender(require('../lib/appenders/file').appender(testFile), 'default-settings');

      logger.info("This should be in the file.");

      setTimeout(function () {
        fs.readFile(testFile, "utf8", that.callback);
      }, 100);
    },
    'should write log messages to the file': function shouldWriteLogMessagesToTheFile(err, fileContents) {
      assert.include(fileContents, "This should be in the file." + EOL);
    },
    'log messages should be in the basic layout format': function logMessagesShouldBeInTheBasicLayoutFormat(err, fileContents) {
      assert.match(fileContents, /\[\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}\] \[INFO\] default-settings - /);
    }
  },
  'fileAppender subcategories': {
    topic: function topic() {
      var that = this;

      log4js.clearAppenders();

      function addAppender(cat) {
        var testFile = path.join(__dirname, '/fa-subcategories-test-' + cat.join('-').replace(/\./g, "_") + '.log');
        remove(testFile);
        log4js.addAppender(require('../lib/appenders/file').appender(testFile), cat);
        return testFile;
      }

      var file_sub1 = addAppender(['sub1']);

      var file_sub1_sub12$sub1_sub13 = addAppender(['sub1.sub12', 'sub1.sub13']);

      var file_sub1_sub12 = addAppender(['sub1.sub12']);

      var logger_sub1_sub12_sub123 = log4js.getLogger('sub1.sub12.sub123');

      var logger_sub1_sub13_sub133 = log4js.getLogger('sub1.sub13.sub133');

      var logger_sub1_sub14 = log4js.getLogger('sub1.sub14');

      var logger_sub2 = log4js.getLogger('sub2');

      logger_sub1_sub12_sub123.info('sub1_sub12_sub123');

      logger_sub1_sub13_sub133.info('sub1_sub13_sub133');

      logger_sub1_sub14.info('sub1_sub14');

      logger_sub2.info('sub2');

      setTimeout(function () {
        that.callback(null, {
          file_sub1: fs.readFileSync(file_sub1).toString(),
          file_sub1_sub12$sub1_sub13: fs.readFileSync(file_sub1_sub12$sub1_sub13).toString(),
          file_sub1_sub12: fs.readFileSync(file_sub1_sub12).toString()
        });
      }, 3000);
    },
    'check file contents': function checkFileContents(err, fileContents) {

      // everything but category 'sub2'
      assert.match(fileContents.file_sub1, /^(\[\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}\] \[INFO\] (sub1.sub12.sub123 - sub1_sub12_sub123|sub1.sub13.sub133 - sub1_sub13_sub133|sub1.sub14 - sub1_sub14)[\s\S]){3}$/);
      assert.ok(fileContents.file_sub1.match(/sub123/) && fileContents.file_sub1.match(/sub133/) && fileContents.file_sub1.match(/sub14/));
      assert.ok(!fileContents.file_sub1.match(/sub2/));

      // only catgories starting with 'sub1.sub12' and 'sub1.sub13'
      assert.match(fileContents.file_sub1_sub12$sub1_sub13, /^(\[\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}\] \[INFO\] (sub1.sub12.sub123 - sub1_sub12_sub123|sub1.sub13.sub133 - sub1_sub13_sub133)[\s\S]){2}$/);
      assert.ok(fileContents.file_sub1_sub12$sub1_sub13.match(/sub123/) && fileContents.file_sub1_sub12$sub1_sub13.match(/sub133/));
      assert.ok(!fileContents.file_sub1_sub12$sub1_sub13.match(/sub14|sub2/));

      // only catgories starting with 'sub1.sub12'
      assert.match(fileContents.file_sub1_sub12, /^(\[\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}\] \[INFO\] (sub1.sub12.sub123 - sub1_sub12_sub123)[\s\S]){1}$/);
      assert.ok(!fileContents.file_sub1_sub12.match(/sub14|sub2|sub13/));
    }
  },
  'with a max file size and no backups': {
    topic: function topic() {
      var testFile = path.join(__dirname, '/fa-maxFileSize-test.log'),
          logger = log4js.getLogger('max-file-size'),
          that = this;
      remove(testFile);
      remove(testFile + '.1');
      //log file of 100 bytes maximum, no backups
      log4js.clearAppenders();
      log4js.addAppender(require('../lib/appenders/file').appender(testFile, log4js.layouts.basicLayout, 100, 0), 'max-file-size');
      logger.info("This is the first log message.");
      logger.info("This is an intermediate log message.");
      logger.info("This is the second log message.");
      //wait for the file system to catch up
      setTimeout(function () {
        fs.readFile(testFile, "utf8", that.callback);
      }, 100);
    },
    'log file should only contain the second message': function logFileShouldOnlyContainTheSecondMessage(err, fileContents) {
      assert.include(fileContents, "This is the second log message.");
      assert.equal(fileContents.indexOf("This is the first log message."), -1);
    },
    'the number of files': {
      topic: function topic() {
        fs.readdir(__dirname, this.callback);
      },
      'starting with the test file name should be two': function startingWithTheTestFileNameShouldBeTwo(err, files) {
        //there will always be one backup if you've specified a max log size
        var logFiles = files.filter(function (file) {
          return file.indexOf('fa-maxFileSize-test.log') > -1;
        });
        assert.equal(logFiles.length, 2);
      }
    }
  },
  'with a max file size and 2 backups': {
    topic: function topic() {
      var testFile = path.join(__dirname, '/fa-maxFileSize-with-backups-test.log'),
          logger = log4js.getLogger('max-file-size-backups');
      remove(testFile);
      remove(testFile + '.1');
      remove(testFile + '.2');

      //log file of 50 bytes maximum, 2 backups
      log4js.clearAppenders();
      log4js.addAppender(require('../lib/appenders/file').appender(testFile, log4js.layouts.basicLayout, 50, 2), 'max-file-size-backups');
      logger.info("This is the first log message.");
      logger.info("This is the second log message.");
      logger.info("This is the third log message.");
      logger.info("This is the fourth log message.");
      var that = this;
      //give the system a chance to open the stream
      setTimeout(function () {
        fs.readdir(__dirname, function (err, files) {
          if (files) {
            that.callback(null, files.sort());
          } else {
            that.callback(err, files);
          }
        });
      }, 200);
    },
    'the log files': {
      topic: function topic(files) {
        var logFiles = files.filter(function (file) {
          return file.indexOf('fa-maxFileSize-with-backups-test.log') > -1;
        });
        return logFiles;
      },
      'should be 3': function shouldBe3(files) {
        assert.equal(files.length, 3);
      },
      'should be named in sequence': function shouldBeNamedInSequence(files) {
        assert.deepEqual(files, ['fa-maxFileSize-with-backups-test.log', 'fa-maxFileSize-with-backups-test.log.1', 'fa-maxFileSize-with-backups-test.log.2']);
      },
      'and the contents of the first file': {
        topic: function topic(logFiles) {
          fs.readFile(path.join(__dirname, logFiles[0]), "utf8", this.callback);
        },
        'should be the last log message': function shouldBeTheLastLogMessage(contents) {
          assert.include(contents, 'This is the fourth log message.');
        }
      },
      'and the contents of the second file': {
        topic: function topic(logFiles) {
          fs.readFile(path.join(__dirname, logFiles[1]), "utf8", this.callback);
        },
        'should be the third log message': function shouldBeTheThirdLogMessage(contents) {
          assert.include(contents, 'This is the third log message.');
        }
      },
      'and the contents of the third file': {
        topic: function topic(logFiles) {
          fs.readFile(path.join(__dirname, logFiles[2]), "utf8", this.callback);
        },
        'should be the second log message': function shouldBeTheSecondLogMessage(contents) {
          assert.include(contents, 'This is the second log message.');
        }
      }
    }
  },
  'with a max file size and 2 compressed backups': {
    topic: function topic() {
      var testFile = path.join(__dirname, '/fa-maxFileSize-with-backups-compressed-test.log'),
          logger = log4js.getLogger('max-file-size-backups');
      remove(testFile);
      remove(testFile + '.1.gz');
      remove(testFile + '.2.gz');

      //log file of 50 bytes maximum, 2 backups
      log4js.clearAppenders();
      log4js.addAppender(require('../lib/appenders/file').appender(testFile, log4js.layouts.basicLayout, 50, 2, true), 'max-file-size-backups');
      logger.info("This is the first log message.");
      logger.info("This is the second log message.");
      logger.info("This is the third log message.");
      logger.info("This is the fourth log message.");
      var that = this;
      //give the system a chance to open the stream
      setTimeout(function () {
        fs.readdir(__dirname, function (err, files) {
          if (files) {
            that.callback(null, files.sort());
          } else {
            that.callback(err, files);
          }
        });
      }, 1000);
    },
    'the log files': {
      topic: function topic(files) {
        var logFiles = files.filter(function (file) {
          return file.indexOf('fa-maxFileSize-with-backups-compressed-test.log') > -1;
        });
        return logFiles;
      },
      'should be 3': function shouldBe3(files) {
        assert.equal(files.length, 3);
      },
      'should be named in sequence': function shouldBeNamedInSequence(files) {
        assert.deepEqual(files, ['fa-maxFileSize-with-backups-compressed-test.log', 'fa-maxFileSize-with-backups-compressed-test.log.1.gz', 'fa-maxFileSize-with-backups-compressed-test.log.2.gz']);
      },
      'and the contents of the first file': {
        topic: function topic(logFiles) {
          fs.readFile(path.join(__dirname, logFiles[0]), "utf8", this.callback);
        },
        'should be the last log message': function shouldBeTheLastLogMessage(contents) {
          assert.include(contents, 'This is the fourth log message.');
        }
      },
      'and the contents of the second file': {
        topic: function topic(logFiles) {
          zlib.gunzip(fs.readFileSync(path.join(__dirname, logFiles[1])), this.callback);
        },
        'should be the third log message': function shouldBeTheThirdLogMessage(contents) {
          assert.include(contents.toString('utf8'), 'This is the third log message.');
        }
      },
      'and the contents of the third file': {
        topic: function topic(logFiles) {
          zlib.gunzip(fs.readFileSync(path.join(__dirname, logFiles[2])), this.callback);
        },
        'should be the second log message': function shouldBeTheSecondLogMessage(contents) {
          assert.include(contents.toString('utf8'), 'This is the second log message.');
        }
      }
    }
  }
}).addBatch({
  'configure': {
    'with fileAppender': {
      topic: function topic() {
        var log4js = require('../lib/log4js'),
            logger;
        //this config file defines one file appender (to ./tmp-tests.log)
        //and sets the log level for "tests" to WARN
        log4js.configure('./test/log4js.json');
        logger = log4js.getLogger('tests');
        logger.info('this should not be written to the file');
        logger.warn('this should be written to the file');

        fs.readFile('tmp-tests.log', 'utf8', this.callback);
      },
      'should load appender configuration from a json file': function shouldLoadAppenderConfigurationFromAJsonFile(err, contents) {
        assert.include(contents, 'this should be written to the file' + EOL);
        assert.equal(contents.indexOf('this should not be written to the file'), -1);
      }
    }
  }
}).addBatch({
  'when underlying stream errors': {
    topic: function topic() {
      var consoleArgs,
          errorHandler,
          fileAppender = sandbox.require('../lib/appenders/file', {
        globals: {
          console: {
            error: function error() {
              consoleArgs = Array.prototype.slice.call(arguments);
            }
          }
        },
        requires: {
          '../streams': {
            RollingFileStream: function RollingFileStream(filename) {

              this.end = function () {};
              this.on = function (evt, cb) {
                if (evt === 'error') {
                  errorHandler = cb;
                }
              };
            }
          }
        }
      });
      fileAppender.appender('test1.log', null, 100);
      errorHandler({ error: 'aargh' });
      return consoleArgs;
    },
    'should log the error to console.error': function shouldLogTheErrorToConsoleError(consoleArgs) {
      assert.isNotEmpty(consoleArgs);
      assert.equal(consoleArgs[0], 'log4js.fileAppender - Writing to file %s, error happened ');
      assert.equal(consoleArgs[1], 'test1.log');
      assert.equal(consoleArgs[2].error, 'aargh');
    }
  }

})['export'](module);

//# sourceMappingURL=fileAppender-test-compiled.js.map


text:
using UnrealBuildTool;

public class AndroidDeviceDetection : ModuleRules
{
	public AndroidDeviceDetection( TargetInfo Target )
	{
		BinariesSubFolder = "Android";

        PrivateDependencyModuleNames.AddRange(
			new string[]
			{
				"Core",
			}
		);

		PublicIncludePaths.AddRange(
			new string[]
			{
				"Runtime/Core/Public/Android"
			}
		);

		if (UEBuildConfiguration.bCompileAgainstEngine)
		{
			PrivateDependencyModuleNames.Add("Engine");
		}
	}
}


text:
<app-link-input></app-link-input>
<app-link-list [categoryId]="category.id"></app-link-list>


text:
Keywords used on the text-based UI.\
_keywords are case-insensitive_

## Verbs
* add
* adv|advice
* assign
* create
* del|delete
* dem|demote
* est|estimate
* exit
* help
* link
* list
* load
* open
* promote
* quit
* remove
* report
* save
* show
* summary
* sync|synchronize

## Objects & Attributes
* best
* act|actual
* dat|date
* est|estimated
* file
* planned
* project
* stat|status
* task
* worst

## Decorators
* on
* to
* from


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.ApplicationModel.Store;
using Windows.Storage;
using Windows.System;

namespace Podcasts
{
    public sealed partial class AboutPage
    {
        public AboutPage()
        {
            InitializeComponent();
        }

        private void AboutPage_Loaded(object sender, RoutedEventArgs e)
        {
            var version = Package.Current.Id.Version;
            VersionText.Text = "Podcasts v" + version.StringVersion();

            GlobalStateManager.SelectedMenuIndex = 6;

            if (!AppSettings.Instance.TipSent)
            {
                try
                {
                    var active = (Application.Current as App).LicenseInformation.ProductLicenses["Support"].IsActive || (Application.Current as App).LicenseInformation.ProductLicenses["SupportMax"].IsActive;

                    if (active)
                    {
                        MarkSupportActivated();
                    }
                }
                catch
                {
                    // Ignore error
                }
            }
            else
            {
                MarkSupportActivated();
            }
        }

        void MarkSupportActivated()
        {
            SupportButton.Visibility = Visibility.Collapsed;
            SupportMaxButton.Visibility = Visibility.Collapsed;
            SupportText.Text = StringsHelper.ThankYou;
        }

        private async void SupportButton_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                WaitRingManager.IsWaitRingVisible = true;
                await CurrentApp.RequestProductPurchaseAsync("Support");
                WaitRingManager.IsWaitRingVisible = false;
                var active = (Application.Current as App).LicenseInformation.ProductLicenses["Support"].IsActive;

                if (active)
                {
                    MarkSupportActivated();
                    AppSettings.Instance.TipSent = true;
                    await App.MessageAsync(StringsHelper.ThankYou);
                }
            }
            catch
            {
                WaitRingManager.IsWaitRingVisible = false;
            }
        }

        private async void SupportMaxButton_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                WaitRingManager.IsWaitRingVisible = true;
                await CurrentApp.RequestProductPurchaseAsync("SupportMax");
                WaitRingManager.IsWaitRingVisible = false;
                var active = (Application.Current as App).LicenseInformation.ProductLicenses["SupportMax"].IsActive;

                if (active)
                {
                    MarkSupportActivated();
                    AppSettings.Instance.TipSent = true;
                    await App.MessageAsync(StringsHelper.ThankYou);
                }
            }
            catch
            {
                WaitRingManager.IsWaitRingVisible = false;
            }
        }

        private async void FeedbackButton_OnClick(object sender, RoutedEventArgs e)
        {
            App.TrackEvent("Review");
            await Launcher.LaunchUriAsync(new Uri("ms-windows-store:REVIEW?PFN=15798DavidCatuhe.Cast_x8akzp4bebrnj", UriKind.Absolute));
        }
    }
}


text:
package storm.bolt;

import backtype.storm.tuple.Tuple;
import org.apache.log4j.Logger;
//import storm.starter.tools.Rankings;

import storm.tools.Rankings;

public final class TotalRankingsBolt extends AbstractRankerBolt {

  private static final long serialVersionUID = -8447525895532302198L;
  private static final Logger LOG = Logger.getLogger(TotalRankingsBolt.class);

  public TotalRankingsBolt() {
    super();
  }

  public TotalRankingsBolt(int topN) {
    super(topN);
  }

  public TotalRankingsBolt(int topN, int emitFrequencyInSeconds) {
    super(topN, emitFrequencyInSeconds);
  }

  @Override
  void updateRankingsWithTuple(Tuple tuple) {
    Rankings rankingsToBeMerged = (Rankings) tuple.getValue(0);
    super.getRankings().updateWith(rankingsToBeMerged);
    super.getRankings().pruneZeroCounts();
  }

  @Override
  Logger getLogger() {
    return LOG;
  }

}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:fitsSystemWindows="true">

    <include layout="@layout/toolbar"/>

    <com.eccyan.widget.SpinningTabStrip
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />

    <com.eccyan.widget.SpinningViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        tools:context=".MainActivity"/>

    <LinearLayout
        android:id="@+id/colors"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_marginBottom="8dip"
        android:layout_marginLeft="4dip"
        android:layout_marginRight="4dip"
        android:orientation="horizontal" >

        <ImageView
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_margin="4dip"
            android:layout_weight="1"
            android:background="?attr/colorPrimary"
            android:onClick="onColorClicked"
            android:tag="@color/green" />

        <ImageView
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_margin="4dip"
            android:layout_weight="1"
            android:background="#FFC74B46"
            android:onClick="onColorClicked"
            android:tag="#FFC74B46" />

        <ImageView
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_margin="4dip"
            android:layout_weight="1"
            android:background="#FFF4842D"
            android:onClick="onColorClicked"
            android:tag="#FFF4842D" />

        <ImageView
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_margin="4dip"
            android:layout_weight="1"
            android:background="#FF3F9FE0"
            android:onClick="onColorClicked"
            android:tag="#FF3F9FE0" />

        <ImageView
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_margin="4dip"
            android:layout_weight="1"
            android:background="#FF5161BC"
            android:onClick="onColorClicked"
            android:tag="#FF5161BC" />
    </LinearLayout>

</LinearLayout>


text:
package org.assertj.core.api.abstract_; // Make sure that package-private access is lost

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;

import org.assertj.core.api.AbstractAssert;
import org.assertj.core.api.AbstractSoftAssertions;
import org.assertj.core.api.StandardSoftAssertionsProvider;
import org.assertj.core.api.SoftAssertionsProvider;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

/**
 * This tests that classes extended from {@link StandardSoftAssertionsProvider} will have access to the list of
 * collected errors that the various proxies have collected.
 */
@DisplayName("Multiple custom SoftAssertions")
class SoftAssertionsMultipleProjectsTest {

  static class NotClassy {

  }

  static class Classy {

  }

  static class NotClassyAssert extends AbstractAssert<NotClassyAssert, NotClassy> {
    public NotClassyAssert(NotClassy actual) {
      super(actual, NotClassyAssert.class);
    }

    public NotClassyAssert isClassy() {
      throw new AssertionError("Sorry I'm not classy!");
    }

    public NotClassyAssert isNotClassy() {
      return this;
    }
  }

  static class ClassyAssert extends AbstractAssert<ClassyAssert, Classy> {
    public ClassyAssert(Classy actual) {
      super(actual, ClassyAssert.class);
    }

    public ClassyAssert isClassy() {
      return this;
    }

    public ClassyAssert isNotClassy() {
      throw new AssertionError("Hey I'm classy!");
    }
  }

  interface Class1SoftAssertions extends SoftAssertionsProvider {
    default NotClassyAssert assertThat(NotClassy actual) {
      return proxy(NotClassyAssert.class, NotClassy.class, actual);
    }
  }

  interface Class2SoftAssertions extends SoftAssertionsProvider {
    default ClassyAssert assertThat(Classy actual) {
      return proxy(ClassyAssert.class, Classy.class, actual);
    }
  }

  static class UberSoftAssertions extends AbstractSoftAssertions
      implements Class1SoftAssertions, Class2SoftAssertions, StandardSoftAssertionsProvider {
  }

  private final NotClassy notClassy = new NotClassy();
  private final Classy classy = new Classy();
  private final UberSoftAssertions softly = new UberSoftAssertions();

  @Test
  void should_return_an_empty_list_of_errors_for_passing_assertions() {
    // GIVEN succesfull assertions
    softly.assertThat(notClassy).isNotClassy();
    softly.assertThat(classy).isClassy();
    softly.assertThat("String").isEqualTo("String");
    // WHEN
    List<Throwable> errorsCollected = softly.errorsCollected();
    // THEN
    assertThat(errorsCollected).isEqualTo(softly.assertionErrorsCollected())
                               .isEmpty();
  }

  @Test
  void should_return_errors_in_the_order_they_were_asserted() {
    // GIVEN
    softly.assertThat(notClassy).isClassy();
    softly.assertThat(classy).isNotClassy();
    softly.assertThat("String").isEqualTo("Strung");
    softly.assertThat("String").isEqualTo("String"); // No errors to collect
    // WHEN
    List<Throwable> errorsCollected = softly.errorsCollected();
    // THEN
    assertThat(errorsCollected).isEqualTo(softly.assertionErrorsCollected())
                               .hasSize(3);
    assertThat(errorsCollected.get(0)).as("0").hasMessage("Sorry I'm not classy!");
    assertThat(errorsCollected.get(1)).as("1").hasMessage("Hey I'm classy!");
    assertThat(errorsCollected.get(2)).as("2").hasMessageMatching("(?s).*String.*equal to.*Strung.*not.*");
  }
}


text:
#import "NSView.h"

@interface RoundedCornersView : NSView
{
}

- (void)drawRect:(struct CGRect)arg1;

@end


text:
from panda3d.core import *
from panda3d.direct import *
from direct.directnotify import DirectNotifyGlobal
import CogHood
from toontown.toonbase import ToontownGlobals, TTLocalizer
from toontown.hood import ZoneUtil
from toontown.coghq import CashbotCogHQLoader

class CashbotHQ(CogHood.CogHood):
    notify = DirectNotifyGlobal.directNotify.newCategory('CashbotHQ')

    def __init__(self, parentFSM, doneEvent, dnaStore, hoodId):
        CogHood.CogHood.__init__(self, parentFSM, doneEvent, dnaStore, hoodId)
        self.id = ToontownGlobals.CashbotHQ
        self.cogHQLoaderClass = CashbotCogHQLoader.CashbotCogHQLoader
        self.storageDNAFile = None
        self.skyFile = 'phase_3.5/models/props/TT_sky'
        self.titleColor = (0.5, 0.5, 0.5, 1.0)
        return

    def load(self):
        CogHood.CogHood.load(self)
        self.parentFSM.getStateNamed('CashbotHQ').addChild(self.fsm)

    def unload(self):
        self.parentFSM.getStateNamed('CashbotHQ').removeChild(self.fsm)
        del self.cogHQLoaderClass
        CogHood.CogHood.unload(self)

    def enter(self, *args):
        CogHood.CogHood.enter(self, *args)
        localAvatar.setCameraFov(ToontownGlobals.CogHQCameraFov)
        base.camLens.setNearFar(ToontownGlobals.CashbotHQCameraNear, ToontownGlobals.CashbotHQCameraFar)

    def exit(self):
        localAvatar.setCameraFov(ToontownGlobals.DefaultCameraFov)
        base.camLens.setNearFar(ToontownGlobals.DefaultCameraNear, ToontownGlobals.DefaultCameraFar)
        CogHood.CogHood.exit(self)

    def spawnTitleText(self, zoneId, floorNum = None):
        if ZoneUtil.isMintInteriorZone(zoneId):
            text = '%s\n%s' % (ToontownGlobals.StreetNames[zoneId][-1], TTLocalizer.MintFloorTitle % (floorNum + 1))
            self.doSpawnTitleText(text)
        else:
            CogHood.CogHood.spawnTitleText(self, zoneId)


text:
/*jshint curly:true, eqeqeq:true, immed:true, latedef:true,
  newcap:true, noarg:true, sub:true, undef:true, boss:true,
  strict:false, eqnull:true, browser:true, node:true */
/*global assert, refute */

var buster = typeof buster !== 'undefined' ? buster : require("buster");
var LilObj = typeof module !== 'undefined' ? require('../lib/lilobj') : require('lilobj');

buster.testCase("LilObj", {

    "should extend and create objects": function () {

      var Parent = LilObj.obj.extend({
        type: null,
        construct: function (name) {
          this.name = name;
        },
        hey: function () {
          return this.type + ' here';
        }
      });

      var Dad = Parent.extend({
        type: 'Dad'
      });

      var Mom = Parent.extend({
        type: 'Mom'
      });

      var jayz = Dad.create('jay-z');
      var gus = Dad.create('gus');
      var gaga = Mom.create('gaga');

      assert.equals(jayz.type, 'Dad');
      assert.equals(jayz.name, 'jay-z');
      assert.equals(jayz.hey(), 'Dad here');
      assert(jayz.isA(Dad));
      refute(jayz.isA(Mom));
      assert.equals(gus.type, 'Dad');
      assert.equals(gus.name, 'gus');
      assert.equals(gus.hey(), 'Dad here');
      assert(gus.isA(Dad));
      refute(gus.isA(Mom));
      assert.equals(gaga.type, 'Mom');
      assert.equals(gaga.name, 'gaga');
      assert.equals(gaga.hey(), 'Mom here');
      assert(gaga.isA(Mom));
      refute(gaga.isA(Dad));

    },

    "should extend and create arrays": function () {

      var Parents = LilObj.arr.extend({

        young: false,
        construct: function (rents) {

          rents.forEach(function (rent) {
            this.push(rent);
          }, this);

        }
      });

      var parents = Parents.create([
        'azure',
        'gus'
      ]);

      assert.equals(parents.length, 2);
      assert(parents instanceof Array);
      assert(parents.isA(Parents));

      parents.push('martina');
      var azure = parents.shift();

      assert.equals(parents.length, 2);
      assert.equals(azure, 'azure');
      assert.equals(parents[1], 'martina');

    }

});


text:
package org.nutz.mvc.impl.contextCollector;

import org.nutz.lang.Lang;
import org.nutz.lang.util.Context;
import org.nutz.mvc.ViewContextCollector;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求对象的属性列表
 */
public class AttrCollector implements ViewContextCollector {
    @Override
    public Context collect(HttpServletRequest req, Object obj) {
        Map<String, Object> req_attr = new HashMap<String, Object>();
        for (Enumeration<String> en = req.getAttributeNames(); en.hasMoreElements();) {
            String tem = en.nextElement();
            if (!tem.startsWith("$"))
                req_attr.put(tem, req.getAttribute(tem));
        }
        Context ctx = Lang.context();
        ctx.set("a", req_attr);// 兼容最初的写法
        ctx.set("req_attr", req_attr);
        return ctx;
    }
}


text:
package discovery

import (
	"fmt"
	"os"
	"testing"

	"gopkg.in/redis.v5"

	pb "github.com/TheThingsNetwork/ttn/api/discovery"
	. "github.com/smartystreets/assertions"
)

func getRedisClient(db int) *redis.Client {
	host := os.Getenv("REDIS_HOST")
	if host == "" {
		host = "localhost"
	}
	return redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:6379", host),
		Password: "", // no password set
		DB:       db,
	})
}

func TestDiscoveryAnnounce(t *testing.T) {
	a := New(t)

	client := getRedisClient(1)
	d := NewRedisDiscovery(client)
	defer func() {
		client.Del("discovery:announcement:broker:broker1.1")
		client.Del("discovery:announcement:broker:broker1.2")
	}()

	broker1a := &pb.Announcement{ServiceName: "broker", Id: "broker1.1", NetAddress: "current address"}
	broker1b := &pb.Announcement{ServiceName: "broker", Id: "broker1.1", NetAddress: "updated address"}
	broker2 := &pb.Announcement{ServiceName: "broker", Id: "broker1.2", NetAddress: "other address"}

	err := d.Announce(broker1a)
	a.So(err, ShouldBeNil)

	services, err := d.GetAll("broker", 0, 0)
	a.So(err, ShouldBeNil)
	a.So(services, ShouldHaveLength, 1)
	a.So(services[0].NetAddress, ShouldEqual, "current address")

	err = d.Announce(broker1b)
	a.So(err, ShouldBeNil)

	services, err = d.GetAll("broker", 0, 0)
	a.So(err, ShouldBeNil)
	a.So(services, ShouldHaveLength, 1)
	a.So(services[0].NetAddress, ShouldEqual, "updated address")

	err = d.Announce(broker2)
	a.So(err, ShouldBeNil)

	services, err = d.GetAll("broker", 0, 0)
	a.So(err, ShouldBeNil)
	a.So(services, ShouldHaveLength, 2)

}

func TestDiscoveryDiscover(t *testing.T) {
	a := New(t)

	client := getRedisClient(2)
	d := NewRedisDiscovery(client)
	defer func() {
		client.Del("discovery:announcement:router:router2.0")
		client.Del("discovery:announcement:broker:broker2.1")
		client.Del("discovery:announcement:broker:broker2.2")
	}()

	// This depends on the previous test to pass
	d.Announce(&pb.Announcement{ServiceName: "router", Id: "router2.0"})
	d.Announce(&pb.Announcement{ServiceName: "broker", Id: "broker2.1"})
	d.Announce(&pb.Announcement{ServiceName: "broker", Id: "broker2.2"})

	services, err := d.GetAll("random", 0, 0)
	a.So(err, ShouldBeNil)
	a.So(services, ShouldBeEmpty)

	services, err = d.GetAll("router", 0, 0)
	a.So(err, ShouldBeNil)
	a.So(services, ShouldHaveLength, 1)
	a.So(services[0].Id, ShouldEqual, "router2.0")

	services, err = d.GetAll("broker", 0, 0)
	a.So(err, ShouldBeNil)
	a.So(services, ShouldHaveLength, 2)

}

func TestDiscoveryMetadata(t *testing.T) {
	a := New(t)

	client := getRedisClient(1)
	d := NewRedisDiscovery(client)
	defer func() {
		client.Del("discovery:announcement:broker:broker3")
		client.Del("discovery:announcement:broker:broker4")
		client.Del("discovery:app-id:app-id-2")
	}()

	broker3 := &pb.Announcement{ServiceName: "broker", Id: "broker3", Metadata: []*pb.Metadata{&pb.Metadata{
		Metadata: &pb.Metadata_AppId{AppId: "app-id-1"},
	}}}
	broker4 := &pb.Announcement{ServiceName: "broker", Id: "broker4", Metadata: []*pb.Metadata{&pb.Metadata{
		Metadata: &pb.Metadata_AppId{AppId: "app-id-2"},
	}}}

	// Announce should not change metadata
	err := d.Announce(broker3)
	a.So(err, ShouldBeNil)
	service, err := d.Get("broker", "broker3")
	a.So(err, ShouldBeNil)
	a.So(service.Metadata, ShouldHaveLength, 0)

	d.Announce(broker4)

	// AddMetadata should add one
	err = d.AddMetadata("broker", "broker3", &pb.Metadata{
		Metadata: &pb.Metadata_AppId{AppId: "app-id-2"},
	})
	a.So(err, ShouldBeNil)
	service, err = d.Get("broker", "broker3")
	a.So(err, ShouldBeNil)
	a.So(service.Metadata, ShouldHaveLength, 1)

	// And should remove it from the other broker
	service, err = d.Get("broker", "broker4")
	a.So(err, ShouldBeNil)
	a.So(service.Metadata, ShouldHaveLength, 0)

	// AddMetadata again should not add one
	err = d.AddMetadata("broker", "broker3", &pb.Metadata{
		Metadata: &pb.Metadata_AppId{AppId: "app-id-2"},
	})
	service, err = d.Get("broker", "broker3")
	a.So(err, ShouldBeNil)
	a.So(service.Metadata, ShouldHaveLength, 1)

	// DeleteMetadata for non-existing should not delete one
	err = d.DeleteMetadata("broker", "broker3", &pb.Metadata{
		Metadata: &pb.Metadata_AppId{AppId: "app-id-3"},
	})
	a.So(err, ShouldBeNil)
	service, err = d.Get("broker", "broker3")
	a.So(err, ShouldBeNil)
	a.So(service.Metadata, ShouldHaveLength, 1)

	// Announce should not change metadata
	err = d.Announce(broker3)
	a.So(err, ShouldBeNil)
	service, err = d.Get("broker", "broker3")
	a.So(err, ShouldBeNil)
	a.So(service.Metadata, ShouldHaveLength, 1)

	// DeleteMetadata should delete one
	err = d.DeleteMetadata("broker", "broker3", &pb.Metadata{
		Metadata: &pb.Metadata_AppId{AppId: "app-id-2"},
	})
	a.So(err, ShouldBeNil)
	service, err = d.Get("broker", "broker3")
	a.So(err, ShouldBeNil)
	a.So(service.Metadata, ShouldHaveLength, 0)

}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class UR_model extends CI_Model {

    public $id_unidad_relacionada;
    public $ur_contenido;
    public $ur_contenedor;
    public $ur_tipo;
    public $ur_estado;

    public function __construct()
    {
        parent::__construct();

    }

    /**
     * añade una nueva relacion esta funcion sera llamada cada vez que se ingrese
     * una unidad intermedia, embalaje o pallet
     * @param ur_contenido  => gtin_contenido
     * @param ur_contenedor => gtin_contenedor
     * @param ur_tipo       => tipo de relacion (BI, IE, EP)
     * @return int numero de filas afectadas
     */
    public function add()
    {
        $data = [
            'ur_contenido'      => $this->ur_contenido,
            'ur_contenedor'     => $this->ur_contenedor,
            'ur_tipo'           => $this->ur_tipo
        ];

        return $this->db->insert('mv_unidad_relacionada', $data);
    }

    /**
     *
     * @param
     * @param
     * @return
     */
    public function getContent()
    {
        $this->db->select('ur_contenido, ur_contenedor');
        $this->db->from('mv_unidad_relacionada');
        $this->db->where('ur_contenido', $this->ur_contenido);

        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            return $query->row();
        }else{
            return false;
        }

    }

    /**
     * obtiene el gtin del contenedor en base a la unidad contenida
     * @param single        => true cuando trae mas de un registro
     * @param ur_contenido  => gtin_contenido
     * @param ur_tipo       => tipo de relacion (BI, IE, EP)
     * @return object con las filas
     */
    public function getRelacionContent($single = false)
    {
        $this->db->select('u.ur_contenedor');
        $this->db->from('mv_unidad_relacionada u');
        $this->db->where('u.ur_contenido',  $this->ur_contenido);
        $this->db->where('u.ur_tipo',       $this->ur_tipo);

        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            if ($single) {
                return $query->row();
            }else {
                return $query->result();
            }
        }else{
            return false;
        }
    }

    /**
     * obtiene el gtin del contenido en base a la unidad contenedora
     * @param ur_contenido  => gtin_contenido
     * @param ur_tipo       => tipo de relacion (BI, IE, EP)
     * @return object con las filas
     */
    public function getRelacionContainer()
    {
        $this->db->select('u.ur_contenido');
        $this->db->from('mv_unidad_relacionada u');
        $this->db->where('u.ur_contenedor', $this->ur_contenedor);
        $this->db->where('u.ur_tipo',       $this->ur_tipo);

        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            return $query->row();
        }else{
            return false;
        }
    }

    /**
     *  elimina la realcion en base a su id
     * @param id_unidad_relacionada => id de la relacion
     * @return numero de filas afectadas
     */
    public function delete()
    {
        $this->db->where('id_unidad_relacionada', $this->id_unidad_relacionada);
        return $this->db->delete('mv_unidad_relacionada');
    }

    /**
     * elimina una realacion
     * @param  ur_contenido     => gtin contenido
     * @param  ur_contenedor    => gtin contenedor
     * @param  ur_tipo          => tipo de relacion
     * @return numero de filas afectadas
     */
    public function deleteByRelacion()
    {
        $this->db->where('ur_contenido',    $this->ur_contenido);
        $this->db->where('ur_contenedor',   $this->ur_contenedor);
        $this->db->where('ur_tipo',         $this->ur_tipo);
        return $this->db->delete('mv_unidad_relacionada');
    }

}

/* End of file ModelName.php */
/* Location: ./application/models/ModelName.php */


text:
package com.alipay.api.domain;

import java.util.List;

import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;

/**
 * 云凤蝶空间详情模型
 *
 * @author auto create
 * @since 1.0, 2018-02-02 11:00:25
 */
public class FengdieSpaceDetailModel extends AlipayObject {

	private static final long serialVersionUID = 8317379359546885511L;

	/**
	 * 空间可用域名列表,云凤蝶站点发布后链接可用采用的域名
	 */
	@ApiListField("domains")
	@ApiField("fengdie_space_domains")
	private List<FengdieSpaceDomains> domains;

	/**
	 * 空间创建时间
	 */
	@ApiField("gmt_create")
	private String gmtCreate;

	/**
	 * 空间 ID
	 */
	@ApiField("space_id")
	private String spaceId;

	/**
	 * 空间标题
	 */
	@ApiField("title")
	private String title;

	public List<FengdieSpaceDomains> getDomains() {
		return this.domains;
	}
	public void setDomains(List<FengdieSpaceDomains> domains) {
		this.domains = domains;
	}

	public String getGmtCreate() {
		return this.gmtCreate;
	}
	public void setGmtCreate(String gmtCreate) {
		this.gmtCreate = gmtCreate;
	}

	public String getSpaceId() {
		return this.spaceId;
	}
	public void setSpaceId(String spaceId) {
		this.spaceId = spaceId;
	}

	public String getTitle() {
		return this.title;
	}
	public void setTitle(String title) {
		this.title = title;
	}

}


text:
//  Copyright 2020 Google Inc. All Rights Reserved.
//
//  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.

using NtApiDotNet.Win32.Security.Native;
using System;
using System.Runtime.InteropServices;

namespace NtApiDotNet.Win32.SafeHandles
{
    internal class SafeAuthZClientContextHandle : SafeHandle
    {
        protected override bool ReleaseHandle()
        {
            return SecurityNativeMethods.AuthzFreeContext(handle);
        }

        public SafeAuthZClientContextHandle(IntPtr handle, bool owns_handle)
            : base(IntPtr.Zero, owns_handle)
        {
            SetHandle(handle);
        }

        public SafeAuthZClientContextHandle()
            : base(IntPtr.Zero, true)
        {
        }

        public override bool IsInvalid
        {
            get
            {
                return handle == IntPtr.Zero;
            }
        }
    }
}


text:
package com.example.dagger;

import arez.annotations.Action;
import arez.annotations.ArezComponent;
import arez.annotations.Feature;

@ArezComponent( dagger = Feature.ENABLE, sting = Feature.DISABLE )
public abstract class MultipleConstructorsModel
{
  MultipleConstructorsModel()
  {
  }

  MultipleConstructorsModel( int i )
  {
  }

  @Action
  void myAction()
  {
  }
}


text:
  const { showModal, hideModals } = require( "./modal.js" );

  function initAttendances ( ) {
    document.addEventListener( "click",
      ( e ) => {
        if ( e.target.classList.contains( "show-attendance-modal" ) ) {
          let id = e.target.getAttribute( "data-attendance-id" );
          showModal( `.modal[data-attendance-id="${ id }"]` );
        }

        if ( e.target.classList.contains( "update-attendance" ) ) {
          let id = e.target.getAttribute( "data-attendance-id" );

          const value = document.querySelector(
            `.modal[data-attendance-id='${id}'] option:checked`
          ).value;

          if ( value ) {
            document.querySelector(
              `button[data-attendance-id='${id}'] i`
            ).classList.add(
              "attendance-comment__icon--set"
            );
          } else {
            document.querySelector(
              `button[data-attendance-id='${id}'] i`
            ).classList.remove(
              "attendance-comment__icon--set"
            );
          }

          hideModals();
        }

      }
    );
  }

  module.exports.initAttendances = initAttendances;


text:
<mvc:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:l="sap.ui.layout" xmlns:model="sap.ui.model"
	controllerName="convista.com.arp.demo.controller.schedulingManageGroups" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:form="sap.ui.layout.form" class="sapUiSizeCompact">
	<Page
      id="pageSchedulingManageGroups"
      class="html_container imageResponsive"
      showHeader="false">
    	<content>
    		<l:Grid defaultSpan="L6 M12 S12">
    			<form:Form
					id="yourGroupsForm"
					editable="true"
					class="ccPanelBG">
    				<form:title >
						<core:Title text="{i18n>manageExistingGroups}"/>
					</form:title>
					<form:layout>
                    <form:ResponsiveGridLayout
	                    class="manageTitle"
                    	visible="true"
                		labelSpanL="12"
                		labelSpanM="12"
                		labelSpanS="12"
                		columnsL="2"
                		columnsM="2"
                		columnsS="2"
                		breakpointL="800"
                		breakpointM="400">
                    </form:ResponsiveGridLayout>
                </form:layout>

    			 <form:formContainers>
                    <form:FormContainer>
                        <form:formElements>
                        	<form:FormElement label="{i18n>manageYourGroups}" class="sapUiTinyMarginTop">
                                <form:fields>
									<Select
										id="yourGroups"
										forceSelection="true"
										required="true"
										change="groupSelectChange"
										items="{
												path: '/groups'
											}">
										<core:Item key="{groupKey}" text="{groupDesc}" />
									</Select>
                                </form:fields>
                            </form:FormElement>
                            <form:FormElement>
                                <form:fields>
										<Button text="{i18n>manageDeleteExistingGroup}" press="handleButtonDeletePressed" />
                                </form:fields>
                            </form:FormElement>
                        </form:formElements>
                    </form:FormContainer>
                </form:formContainers>

                <form:formContainers>
                    <form:FormContainer>
                        <form:formElements>
                            <form:FormElement label="{i18n>manageReportsSelectedGroup}" class="sapUiSmallMarginTop sapUiTinyMarginBottom">
                                <form:fields>
                                	<ScrollContainer
				        				id="reportsSelectedGroupContainer"
				        				class="selectionList groupContainer"
				        				horizontal="false"
										vertical="true">
				        				<SelectList
											id="reportsSelectedGroup" class="listItem">
										</SelectList>
				        			</ScrollContainer>
                                </form:fields>
                            </form:FormElement>
                        </form:formElements>
                    </form:FormContainer>
                </form:formContainers>

                </form:Form>
                <form:Form
					id="selectedReportsForm"
					editable="true"
					class="ccPanelBG">
                	<form:title>
						<core:Title text="{i18n>manageCreateGroup}"  />
					</form:title>
					<form:layout>
                    <form:ResponsiveGridLayout
                	  class="manageTitle"
                    	visible="true"
                		labelSpanL="12"
                		labelSpanM="12"
                		labelSpanS="12"
                		columnsL="2"
                		columnsM="2"
                		columnsS="2"
                		breakpointL="800"
                		breakpointM="400">
                    </form:ResponsiveGridLayout>
                </form:layout>

    			<form:formContainers>
                    <form:FormContainer>
                        <form:formElements>
                            <form:FormElement label="{i18n>manageNewGroupName}">
                                <form:fields>
									<Input
				    					id="newGrpInput"
				    					type="Text"
				    					placeholder="{i18n>manageInputPlaceholder}">
				    				</Input>
                                </form:fields>
                            </form:FormElement>
                            <form:FormElement>
                                <form:fields>
									<Button text="{i18n>manageSaveNewGroup}" press="handleButtonSavePressed" class="sapUiTinyMarginBottom"/>
                                </form:fields>
                            </form:FormElement>
                            <form:FormElement label="{i18n>manageAllAvailableReports}" class="sapUiTinyMarginBottom">
                                <form:fields>
                                	<ScrollContainer
										id="availableReportsContainer"
			            				class="selectionList"
			            				height="387px"
			            				horizontal="false"
										vertical="true">
										<SelectList
											id="availableReports"
											class="listItem"
											items="{
												path: '/reports'
											}">
											<core:Item
												text="{descr}"
												key="{query}"/>
										</SelectList>
									</ScrollContainer>
                                </form:fields>
                            </form:FormElement>
                        </form:formElements>
                    </form:FormContainer>
                </form:formContainers>

                <form:formContainers>
                    <form:FormContainer>
                        <form:formElements>
                            <form:FormElement label="{i18n>manageSelectedReports}" class="sapUiSmallMarginTop sapUiTinyMarginBottom">
                                <form:fields>
                                	<ScrollContainer
				            				id = "selectedReportsContainer"
				            				class="selectedContainer"
				            				height="380px"
				            				horizontal="false"
											vertical="true">
						            	<SelectList id="selectedReports" class="listItem" >
						            	</SelectList>
						            	<Text id="selectedText" text="{i18n>manageAddReports}" class="selectedText" textAlign="Center"></Text>
						            	<core:Icon id="selectedIcon" src="sap-icon://add" class="selectedIcon"></core:Icon>
									</ScrollContainer>
                                </form:fields>
                            </form:FormElement>
                            <form:FormElement>
                                <form:fields>
                                	<ScrollContainer
				            				id = "garbageContainer"
				            				class="garbageContainer"
				            				height="100px"
				            				horizontal="false"
											vertical="false">
				            			<content>
				            				<core:Icon src="sap-icon://delete" class="garbageIcon"></core:Icon>
				            				<Text text="{i18n>manageRemoveReports}" textAlign="Center" class="garbageText"></Text>
				            			</content>
									</ScrollContainer>
                                </form:fields>
                            </form:FormElement>
                        </form:formElements>
                    </form:FormContainer>
                </form:formContainers>

    	</form:Form>
    			</l:Grid>

  		</content>
	</Page>
</mvc:View>


text: {% extends "events/object_detail.html" %}


text:
from indico.modules.events.management.views import WPEventManagement
from indico.modules.events.views import WPConferenceDisplayBase
from indico.util.mathjax import MathjaxMixin

class WPManageTracks(MathjaxMixin, WPEventManagement):
    template_prefix = 'events/tracks/'
    sidemenu_option = 'program'
    bundles = ('markdown.js', 'module_events.tracks.js')

    def _get_head_content(self):
        return WPEventManagement._get_head_content(self) + MathjaxMixin._get_head_content(self)

class WPDisplayTracks(WPConferenceDisplayBase):
    template_prefix = 'events/tracks/'
    menu_entry_name = 'program'
    bundles = ('markdown.js', 'module_events.tracks.js')


text:
'use strict';

FbFriends.View.SearchToolsView = Backbone.View.extend({
	events: {
		'keyup #search-query': 'search',
		'click #sort-by-name': 'sortByName',
		'click #sort-by-birthdate': 'sortByBirthday',
		'click #sort-by-location' : 'sortByLocation',
		'click #sort-toggle-order' : 'sortToggleOrder'
	},
	render: function() {
		this.$el.html(
			this.tmpl()
		);
	},
	initialize: function(options) {
		_.extend(this, options || {});
	},
	search: function(event) {
		this.friends.filterByFullname(event.target.value);
	},
	sortByName: function(event) {
		this.friends.sortByAttribute('first_name');
		this.sortButtonHighlight(event.target);
	},
	sortByBirthday: function(event) {
		this.friends.sortByAttribute('birthday_date');
		this.sortButtonHighlight(event.target);
	},
	sortByLocation: function(event) {
		this.friends.sortByAttribute('current_location.city');
		this.sortButtonHighlight(event.target);
	},
	sortToggleOrder: function(event) {
		this.friends.sortToggleOrder();
		$(event.currentTarget).find('i')
				.removeClass('fa-sort-alpha-desc fa-sort-alpha-asc')
				.addClass(this.friends.sortOrder === this.friends.SORT_ORDER_ASC ? 'fa-sort-alpha-asc' : 'fa-sort-alpha-desc');
	},
	sortButtonHighlight: function(element) {
		this.$el.find('#sort-panel .button').removeClass('selected');
		$(element).addClass('selected');
	}
});


text:
package com.mgmtp.jfunk.data.generator.field;

import static com.google.common.base.Preconditions.checkState;

import java.util.Calendar;
import java.util.List;

import org.jdom.Element;

import com.google.common.collect.Lists;
import com.mgmtp.jfunk.common.random.MathRandom;
import com.mgmtp.jfunk.common.util.Range;
import com.mgmtp.jfunk.data.generator.control.FieldCase;
import com.mgmtp.jfunk.data.generator.util.XMLTags;

/**
 * This field describes a date range in relation to the current calendar year. The elements
 * {@code min} and {@code max} in the XML configuration describe the minimum and maximum values,
 * respectively.
 *

 * Example:
 *
 *

 * {@code
 * <field class="com.mgmtp.jfunk.data.generator.field.DynamicYearField">
 *   <min>-3</min>
 *   <max>+2</max>
 * </field>
 * }
 *

 *
 * If the current calender year is 2011, so the years 2008 to 2013 are generated.
 *
 */
public final class DynamicYearField extends Field {

	private final List<String> values;
	private Range range;

	public DynamicYearField(final MathRandom random, final Element element, final String characterSetId) {
		super(random, element, characterSetId);

		String minString = element.getChildText(XMLTags.MIN);
		if (minString.startsWith("+")) {
			minString = minString.substring(1);
		}
		String maxString = element.getChildText(XMLTags.MAX);
		if (maxString.startsWith("+")) {
			maxString = maxString.substring(1);
		}

		int min = Integer.parseInt(minString);
		int max = Integer.parseInt(maxString);

		checkState(min <= max, "min (=" + min + ") must not exceed the max (=" + max + ") ");

		int year = Calendar.getInstance().get(Calendar.YEAR);
		int minYear = year + min;
		int maxYear = year + max;

		values = Lists.newArrayListWithExpectedSize(maxYear - minYear + 1);
		for (int i = minYear; i <= maxYear; ++i) {
			values.add(String.valueOf(i));
		}
		range = new Range(0, values.size() - 1);
	}

	@Override
	public Range getRange() {
		return range;
	}

	@Override
	public void setRange(final Range range) {
		this.range = range;
	}

	@Override
	public int getMaxLength() {
		return 4;
	}

	@Override
	public String getString(final FieldCase c) {
		int index = c.getSize();
		index = index < 0 ? 0 : index;
		return values.get(index % values.size());
	}
}


text:
package org.ovirt.engine.core.bll;

import java.util.Collections;
import java.util.List;

import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;

public class DisplayAllAuditLogAlertsCommand<T extends VdcActionParametersBase> extends CommandBase<T> {

    public DisplayAllAuditLogAlertsCommand(T parameters) {
        super(parameters);
    }

    @Override
    protected boolean canDoAction() {
        return true;
    }

    @Override
    protected void executeCommand() {
        DbFacade.getInstance().getAuditLogDao().displayAllAlerts();
        setSucceeded(true);
    }

    @Override
    public List<PermissionSubject> getPermissionCheckSubjects() {
        return Collections.singletonList(new PermissionSubject(Guid.SYSTEM,
                VdcObjectType.System,
                ActionGroup.AUDIT_LOG_MANAGEMENT));
    }

    @Override
    public AuditLogType getAuditLogTypeValue() {
        return getSucceeded() ? AuditLogType.USER_DISPLAY_ALL_AUDIT_LOG : AuditLogType.USER_DISPLAY_ALL_AUDIT_LOG_FAILED;
    }
}