text:
<?php

declare(strict_types=1);

namespace Arcanedev\LaravelHtml\Tests;

use Arcanedev\LaravelHtml\FormBuilder;
use Arcanedev\LaravelHtml\Tests\Stubs\FormBuilderModelStub;
use Closure;
use Illuminate\Contracts\Session\Session;
use Illuminate\Session\Store;
use Illuminate\Support\Collection;
use Mockery\MockInterface;
use SessionHandler;
use StdClass;

/**
 * Class     FormBuilderTest
 *
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class FormBuilderTest extends TestCase
{
    /* -----------------------------------------------------------------
     |  Properties
     | -----------------------------------------------------------------
     */

    /** @var \Arcanedev\LaravelHtml\FormBuilder */
    private $form;

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Setup the test environment.
     */
    public function setUp(): void
    {
        parent::setUp();

        $this->form = $this->getFormBuilder();
    }

    /**
     * Destroy the test environment.
     */
    public function tearDown(): void
    {
        unset($this->form);

        parent::tearDown();
    }

    /* -----------------------------------------------------------------
     |  Tests
     | -----------------------------------------------------------------
     */

    /** @test */
    public function it_can_be_instantiated(): void
    {
        static::assertInstanceOf(FormBuilder::class, $this->form);
        static::assertNull($this->form->getModel());
    }

    /** @test */
    public function it_can_be_instantiated_via_helper(): void
    {
        static::assertInstanceOf(FormBuilder::class, form());
        static::assertNull(form()->getModel());
    }

    /** @test */
    public function it_can_set_and_get_session(): void
    {
        static::assertEquals(
            $this->mockSession(),
            $this->form->getSessionStore()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideOpeningForms
     *
     * @param  string  $expected
     * @param  array   $attributes
     */
    public function it_can_open_form($expected, $attributes): void
    {
        static::assertEquals(
            $expected,
            $this->form->open($attributes)->toHtml()
        );
    }

    /** @test */
    public function it_can_open_form_with_different_actions(): void
    {
        $expected = implode('', [
            '<form method="POST" action="http://localhost" accept-charset="UTF-8">',
            '<input type="hidden" name="_token" value="abc">',
        ]);

        $attributes = [
            ['route'  => 'home'],
            ['action' => 'Arcanedev\LaravelHtml\Tests\Stubs\DummyController@index'],
        ];

        foreach ($attributes as $option) {
            static::assertEquals($expected, $this->form->open($option));
        }
    }

    /** @test */
    public function it_can_open_form_with_route_name_and_parameters(): void
    {
        static::assertEquals(
            '<form method="POST" action="http://localhost?hello" accept-charset="UTF-8"><input type="hidden" name="_token" value="abc">',
            $this->form->open(['route'  => ['home', 'hello']])->toHtml()
        );

        static::assertEquals(
            '<form method="POST" action="http://localhost?hello&world" accept-charset="UTF-8"><input type="hidden" name="_token" value="abc">',
            $this->form->open(['route'  => ['home', 'hello', 'world']])->toHtml()
        );
    }

    /** @test */
    public function it_can_open_form_with_action_name_and_parameters(): void
    {
        static::assertEquals(
            '<form method="POST" action="http://localhost?hello" accept-charset="UTF-8"><input type="hidden" name="_token" value="abc">',
            $this->form->open(['action' => ['Arcanedev\LaravelHtml\Tests\Stubs\DummyController@index', 'hello']])->toHtml()
        );

        static::assertEquals(
            '<form method="POST" action="http://localhost?hello&world" accept-charset="UTF-8"><input type="hidden" name="_token" value="abc">',
            $this->form->open(['action' => ['Arcanedev\LaravelHtml\Tests\Stubs\DummyController@index', 'hello', 'world']])->toHtml()
        );
    }

    /** @test */
    public function it_can_open_form_with_url_and_parameters(): void
    {
        static::assertEquals(
            '<form method="POST" action="http://localhost/hello" accept-charset="UTF-8"><input type="hidden" name="_token" value="abc">',
            $this->form->open(['url' => ['/', 'hello']])->toHtml()
        );

        static::assertEquals(
            '<form method="POST" action="http://localhost/hello/world" accept-charset="UTF-8"><input type="hidden" name="_token" value="abc">',
            $this->form->open(['url' => ['/', 'hello', 'world']])->toHtml()
        );
    }

    /** @test */
    public function it_can_close_form(): void
    {
        static::assertEquals('</form>', $this->form->close());
    }

    /**
     * @test
     *
     * @dataProvider provideLabels
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  string  $value
     * @param  array   $attributes
     * @param  bool    $escaped
     */
    public function it_can_make_label($expected, $name, $value, $attributes, $escaped = true): void
    {
        static::assertEquals(
            $expected,
            $this->form->label($name, $value, $attributes, $escaped)
        );
    }

    /**
     * @test
     *
     * @dataProvider provideInputs
     *
     * @param  string  $expected
     * @param  string  $type
     * @param  string  $name
     * @param  mixed   $value
     * @param  array   $attributes
     */
    public function it_can_make_form_inputs($expected, $type, $name, $value, array $attributes): void
    {
        static::assertEquals(
            $expected,
            $this->form->input($type, $name, $value, $attributes)->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider providePassword
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  array   $attributes
     */
    public function it_can_make_password_inputs($expected, $name, $attributes): void
    {
        static::assertEquals($expected, $this->form->password($name, $attributes)->toHtml());
    }

    /** @test */
    public function it_can_make_not_filled_passwords(): void
    {
        $this->mockSession(function (MockInterface $mock) {
            $mock->shouldNotReceive('getOldInput');
        });

        static::assertEquals(
            '<input type="password" name="password">',
            $this->form->password('password')->toHtml()
        );
    }

    /** @test */
    public function it_can_make_not_filled_files(): void
    {
        $this->mockSession(function (MockInterface $mock) {
            $mock->shouldNotReceive('getOldInput');
        });

        static::assertEquals(
            '<input type="file" name="img">',
            $this->form->file('img')->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideTextInputs
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  mixed   $value
     * @param  array   $attributes
     */
    public function it_can_make_text_inputs($expected, $name, $value, $attributes): void
    {
        static::assertEquals(
            $expected,
            $this->form->text($name, $value, $attributes)->toHtml()
        );
    }

    /** @test */
    public function it_can_make_populated_text_inputs(): void
    {
        $this->mockSession(function (MockInterface $mock) {
            $mock->shouldReceive('getOldInput')
                 ->with('name_with_dots')
                 ->andReturn('some value')
                 ->times(2);
        });

        $this->setModel($model = [
            'relation'  => [
                'key'   => 'attribute'
            ],
            'other'     => 'val'
        ]);

        static::assertEquals(
            '<input type="text" name="name.with.dots" value="some value">',
            $this->form->text('name.with.dots', 'default value')->toHtml()
        );

        $this->mockSession(function (MockInterface $mock) {
            $mock->shouldReceive('getOldInput')
                 ->with('text.key.sub')
                 ->andReturn(null)
                 ->once();
        });

        static::assertEquals(
            '<input type="text" name="text[key][sub]" value="default value">',
            $this->form->text('text[key][sub]', 'default value')->toHtml()
        );

        $this->mockSession(function (MockInterface $mock) {
            $mock->shouldReceive('getOldInput')
                 ->with('relation.key')
                 ->andReturn(null);
        });

        $textInput = $this->form->text('relation[key]')->toHtml();

        static::assertEquals(
            '<input type="text" name="relation[key]" value="attribute">',
            $textInput
        );

        $this->setModel($model, false);

        static::assertEquals(
            $textInput,
            $this->form->text('relation[key]')->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideTextArrayAndObjectModel
     *
     * @param  string  $expected
     * @param  string  $model
     * @param  string  $name
     */
    public function it_can_make_populated_text_inputs_with_mix_of_arrays_and_objects($expected, $model, $name): void
    {
        $this->form->model($model);

        static::assertEquals(
            $expected,
            $this->form->text($name)->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideHiddenData
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  mixed   $value
     * @param  array   $attributes
     */
    public function it_can_make_hidden_inputs($expected, $name, $value, $attributes): void
    {
        static::assertEquals(
            $expected,
            $this->form->hidden($name, $value, $attributes)->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideEmailData
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  mixed   $value
     * @param  array   $attributes
     */
    public function it_can_make_email_inputs($expected, $name, $value, $attributes): void
    {
        static::assertEquals($expected, $this->form->email($name, $value, $attributes)->toHtml());

        static::assertEquals(
            '<input type="email" name="foo" class="email-input">',
            $this->form->email('foo', null, ['class' => 'email-input'])->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideTelInputs
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  mixed   $value
     * @param  array   $attributes
     */
    public function it_can_make_tel_inputs($expected, $name, $value, $attributes): void
    {
        static::assertEquals($expected, $this->form->tel($name, $value, $attributes));
    }

    /**
     * @test
     *
     * @dataProvider provideNumberInputs
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  mixed   $value
     * @param  array   $attributes
     */
    public function it_can_make_number_inputs($expected, $name, $value, $attributes): void
    {
        static::assertEquals($expected, $this->form->number($name, $value, $attributes));
    }

    /**
     * @test
     *
     * @dataProvider provideDateInputs
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  mixed   $value
     * @param  array   $attributes
     */
    public function it_can_make_date_inputs($expected, $name, $value, $attributes): void
    {
        static::assertEquals(
            $expected,
            $this->form->date($name, $value, $attributes)->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideDateTimeInputs
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  string  $value
     * @param  array   $attributes
     */
    public function it_can_make_datetime_input($expected, $name, $value, $attributes): void
    {
        static::assertEquals(
            $expected,
            $this->form->datetime($name, $value, $attributes)->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideDateTimeLocaleInputs
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  string  $value
     * @param  array   $attributes
     */
    public function it_can_make_datetime_locale_input($expected, $name, $value, $attributes): void
    {
        static::assertEquals(
            $expected,
            $this->form->datetimeLocal($name, $value, $attributes)->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideColorInputs
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  string  $value
     * @param  array   $attributes
     */
    public function it_can_make_color_input($expected, $name, $value, $attributes): void
    {
        static::assertEquals(
            $expected,
            $this->form->color($name, $value, $attributes)->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideTimeInputs
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  mixed   $value
     * @param  array   $attributes
     */
    public function it_can_make_time_inputs($expected, $name, $value, $attributes): void
    {
        static::assertEquals($expected, $this->form->time($name, $value, $attributes));
    }

    /**
     * @test
     *
     * @dataProvider provideUrlInputs
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  array   $attributes
     */
    public function it_can_make_url_inputs($expected, $name, $attributes): void
    {
        static::assertEquals(
            $expected,
            $this->form->url($name, null, $attributes)->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideFileInputs
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  array   $attributes
     */
    public function it_can_make_files_inputs($expected, $name, $attributes): void
    {
        static::assertEquals(
            $expected,
            $this->form->file($name, $attributes)->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideTextAreaInputs
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  mixed   $value
     * @param  array   $attributes
     */
    public function it_can_make_textarea_inputs($expected, $name, $value, $attributes): void
    {
        static::assertEquals(
            $expected,
            $this->form->textarea($name, $value, $attributes)->toHtml()
        );
    }

    /**
     * @test
     *
     * @dataProvider provideSelectData
     *
     * @param  string  $expected
     * @param  string  $name
     * @param  array   $list
     * @param  mixed   $selected
     * @param  array   $attributes
     */
    public function it_can_make_select_inputs($expected, $name, $list, $selected, array $attributes): void
    {
        static::assertEquals(
            $expected,
            $this->form->select($name, $list, $selected, $attributes)->toHtml()
        );
    }

    /** @test */
    public function it_can_make_select_input_with_label(): void
    {
        static::assertHtmlStringEqualsHtmlString(
            '<label for="select-name-id">Select Name Id</label>',
            $this->form->label('select-name-id')->toHtml()
        );

        static::assertHtmlStringEqualsHtmlString(
            '<select name="select-name" id="select-name-id"></select>',
            $this->form->select(
                'select-name-id',
                [],
                null,
                ['name' => 'select-name']
            )->toHtml()
        );
    }

    /** @test */
    public function it_can_make_populated_select_inputs(): void
    {
        $list  = [
            'L' => 'Large',
            'M' => 'Medium',
            'S' => 'Small',
        ];
        $model = [
            'size'  => ['key' => 'S'],
            'other' => 'val'
        ];

        $this->setModel($model);

        $this->mockSession(function (MockInterface $mock) {
            $mock->shouldReceive('getOldInput')
                 ->with('size')
                 ->andReturn('M')
                 ->times(2);
        });

        static::assertEquals(
            implode('', [
                '<select name="size">',
                    '<option value="L">Large</option>',
                    '<option value="M" selected>Medium</option>',
                    '<option value="S">Small</option>',
                '</select>',
            ]),
            $this->form->select('size', $list, 'S')
        );

        $this->mockSession(function (MockInterface $mock) {
            $mock->shouldReceive('getOldInput')
                ->withArgs(['size.multi'])
                ->times(2)
                ->andReturn(['L', 'S']);
        });

        static::assertEquals(
            implode('', [
                '<select name="size[multi][]" multiple="multiple">',
                    '<option value="L" selected>Large</option>',
                    '<option value="M">Medium</option>',
                    '<option value="S" selected>Small</option>',
                '</select>'
            ]),
            $this->form->select('size[multi][]', $list, 'M', ['multiple' => 'multiple'])->toHtml()
        );

        $this->mockSession(function (MockInterface $mock) {
            $mock->shouldReceive('getOldInput')
                ->withArgs(['size.key'])
                ->andReturn(null);
        });

        static::assertEquals(
            implode('', [
                '<select name="size[key]">',
                    '<option value="L">Large</option>',
                    '<option value="M">Medium</option>',
                    '<option value="S" selected>Small</option>',
                '</select>',
            ]),
            $this->form->select('size[key]', $list)
        );
    }

    /** @test */
    public function it_can_make_select_options_with_attributes(): void
    {
        static::assertEquals(
            '<select name="size">'.
                '<option value="L" data-foo="bar" disabled>Large</option>'.
                '<option value="S">Small</option>'.
            '</select>',
            $this->form->select(
                'size',
                ['L' => 'Large', 'S' => 'Small'],
                null,
                [],
                ['L' => ['data-foo' => 'bar', 'disabled']]
            )->toHtml()
        );
    }

    /** @test */
    public function it_can_make_select_inputs_with_optional_placeholder(): void
    {
        $list = ['null' => 'Select One...', 'L' => 'Large', 'S' => 'Small'];

        static::assertEquals(
            implode('', [
                '<select name="size">',
                    '<option value="null">Select One...</option>',
                    '<option value="L" selected>Large</option>',
                    '<option value="S">Small</option>',
                '</select>'
            ]),
            $this->form->select('size', $list, 'L')->toHtml()
        );
    }

    /** @test */
    public function it_can_make_select_year_inputs(): void
    {
        static::assertStringStartsWith(
            implode('', [
                '<select name="year">',
                    '<option value="2000">2000</option>',
                    '<option value="2001">2001</option>'
                    // To be continued...
            ]),
            $this->form->selectYear('year', 2000, 2020)->toHtml()
        );

        static::assertStringStartsWith(
            implode('', [
                '<select name="year" id="foo">',
                    '<option value="2000">2000</option>',
                    '<option value="2001">2001</option>'
                    // To be continued...
            ]),
            $this->form->selectYear('year', 2000, 2020, null, ['id' => 'foo'])->toHtml()
        );

        static::assertStringStartsWith(
            implode('', [
                '<select name="year">',
                    '<option value="2000" selected>2000</option>',
                    '<option value="2001">2001</option>'
                    // To be continued...
            ]),
            $this->form->selectYear('year', 2000, 2020, '2000')->toHtml()
        );
    }

    /** @test */
    public function it_can_make_select_range_inputs(): void
    {
        $range = $this->form->selectRange('dob', 1900, 2013, 2000)->toHtml();

        static::assertStringStartsWith('<select name="dob"><option value="1900">1900</option>', $range);
        static::assertStringContainsString('<option value="2000" selected>2000</option>', $range);
        static::assertStringContainsString('<option value="2013">2013</option>', $range);
    }

    /** @test */
    public function it_can_make_select_month_inputs(): void
    {
        static::assertStringStartsWith(
            implode('', [
                '<select name="month">',
                    '<option value="1">January</option>',
                    '<option value="2">February</option>'
                    // To be continued ...
            ]),
            $this->form->selectMonth('month')->toHtml()
        );

        static::assertStringStartsWith(
            implode('', [
                '<select name="month">',
                    '<option value="1" selected>January</option>',
                    '<option value="2">February</option>'
                    // To be continued ...
            ]),
            $this->form->selectMonth('month', '1')->toHtml()
        );

        static::assertStringStartsWith(
            implode('', [
                '<select name="month" id="foo">',
                    '<option value="1">January</option>',
                    '<option value="2">February</option>'
                    // To be continued ...
            ]),
            $this->form->selectMonth('month', null, ['id' => 'foo'])->toHtml()
        );
    }

    /** @test */
    public function it_can_make_select_options_inputs(): void
    {
        $list     = [
            'country-1' => [
                'city-1' => 'City 1',
                'city-2' => 'City 2',
            ],
            'country-2' => [
                'city-3' => 'City 3',
                'city-4' => 'City 4',
            ],
        ];

        static::assertEquals(
            '<select name="countries">'.
                '<optgroup label="country-1">'.
                    '<option value="city-1">City 1</option>'.
                    '<option value="city-2">City 2</option>'.
                '</optgroup>'.
                '<optgroup label="country-2">'.
                    '<option value="city-3">City 3</option>'.
                    '<option value="city-4">City 4</option>'.
                '</optgroup>'.
            '</select>',
            $this->form->select('countries', $list, null)
        );
    }

    /** @test */
    public function it_can_make_select_input_with_nested_options(): void
    {
        $list = [
            'Large sizes' => [
                'L'  => 'Large',
                'XL' => 'Extra Large',
            ],
            'S' => 'Small',
        ];

        static::assertEquals(
            '<select name="size" id="select-id" class="class-name">'.
                '<optgroup label="Large sizes">'.
                    '<option value="L">Large</option>'.
                    '<option value="XL">Extra Large</option>'.
                '</optgroup>'.
                '<option value="S">Small</option>'.
            '</select>',
            $this->form->select('size', $list, null, ['id' => 'select-id', 'class' => 'class-name'])->toHtml()
        );

        $list = [
            'Large sizes' => [
                'L'  => 'Large',
                'XL' => 'Extra Large',
            ],
            'M'           => 'Medium',
            'Small sizes' => [
                'S'  => 'Small',
                'XS' => 'Extra Small',
            ],
        ];
        $attributesAttributes = [
            'L' => ['disabled'],
            'M' => ['disabled'],
        ];
        $optgroupAttributes = [
            'Small sizes' => ['disabled'],
        ];

        static::assertEquals(
            '<select name="size">'.
                '<optgroup label="Large sizes">'.
                    '<option value="L" disabled>Large</option>'.
                    '<option value="XL">Extra Large</option>'.
                '</optgroup>'.
                '<option value="M" disabled>Medium</option>'.
                '<optgroup label="Small sizes" disabled>'.
                    '<option value="S">Small</option>'.
                    '<option value="XS">Extra Small</option>'.
                '</optgroup>'.
            '</select>',
            $this->form->select('size', $list, null, [], $attributesAttributes, $optgroupAttributes)->toHtml()
        );

        static::assertHtmlStringEqualsHtmlString(
            '<select name="encoded_html">'.
                '<option value="no_break_space"> </option>'.
                '<option value="ampersand">&</option>'.
                '<option value="lower_than"><</option>'.
            '</select>',
            $this->form->select('encoded_html', ['no_break_space' => ' ', 'ampersand' => '&', 'lower_than' => '<'])->toHtml()
        );

        $list              = ['L' => 'Large', 'S' => 'Small'];
        $attributesAttributes = ['L' => ['data-foo' => 'bar', 'disabled']];

        static::assertEquals(
            '<select name="size">'.
                '<option value="L" data-foo="bar" disabled>Large</option>'.
                '<option value="S">Small</option>'.
            '</select>',
            $this->form->select('size', $list, null, [], $attributesAttributes)
        );

        $this->form->setSessionStore(
            tap(new Store('name', new SessionHandler), function (Store $store) {
                $store->put('_old_input', ['countries' => ['1']]);
            })
        );

        static::assertEquals(
            '<select name="countries"><option value="1" selected>L</option><option value="2">M</option></select>',
            $this->form->select('countries', [1 => 'L', 2 => 'M'])->toHtml()
        );

        static::assertEquals(
            '<select name="avc">'.
                '<option value="null">Select an option</option>'.
                '<option value="1" selected>Yes</option>'.
                '<option value="0">No</option>'.
            '</select>',
            $this->form->select('avc', ['null' => 'Select an option', 1 => 'Yes', 0 => 'No'], 1)->toHtml()
        );
    }

    /** @test */
    public function it_can_make_checkbox_inputs(): void
    {
        $session = $this->mockSession();

        $session->shouldReceive('getOldInput')->with('foo')->andReturn(null);
        $session->shouldReceive('getOldInput')->andReturn([]);

        static::assertEquals(
            '<input type="checkbox" name="foo">',
            $this->form->input('checkbox', 'foo')->toHtml()
        );

        static::assertEquals(
            '<input type="checkbox" name="foo" value="1">',
            $this->form->checkbox('foo')->toHtml()
        );

        static::assertEquals(
            '<input type="checkbox" name="foo" value="foobar" checked="checked">',
            $this->form->checkbox('foo', 'foobar', true)->toHtml()
        );

        static::assertEquals(
            '<input type="checkbox" name="foo" value="foobar" class="form-control">',
            $this->form->checkbox('foo', 'foobar', false, ['class' => 'form-control'])->toHtml()
        );
    }

    /** @test */
    public function it_can_make_populated_checkbox_inputs(): void
    {
        $this->mockSession(function (MockInterface $mock) {
            $mock->shouldReceive('getOldInput')->with('check')->andReturn(null);
            $mock->shouldReceive('getOldInput')->with('check.key')->andReturn('yes');
            $mock->shouldReceive('getOldInput')->with('multicheck')->andReturn([1, 3]);
            $mock->shouldReceive('getOldInput')->andReturn([1]);
        });

        static::assertEquals(
            '<input type="checkbox" name="check" value="1">',
            $this->form->checkbox('check', 1, true)->toHtml()
        );

        static::assertEquals(
            '<input type="checkbox" name="check[key]" value="yes" checked="checked">',
            $this->form->checkbox('check[key]', 'yes')->toHtml()
        );

        static::assertEquals(
            '<input type="checkbox" name="multicheck[]" value="1" checked="checked">',
            $this->form->checkbox('multicheck[]', 1)->toHtml()
        );

        static::assertEquals(
            '<input type="checkbox" name="multicheck[]" value="2">',
            $this->form->checkbox('multicheck[]', 2, true)->toHtml()
        );

        static::assertEquals(
            '<input type="checkbox" name="multicheck[]" value="3" checked="checked">',
            $this->form->checkbox('multicheck[]', 3)->toHtml()
        );
    }

    /** @test */
    public function it_can_make_checkbox_inputs_without_session(): void
    {
        static::assertEquals(
            '<input type="checkbox" name="foo" value="1">',
            $this->form->checkbox('foo')->toHtml()
        );

        static::assertEquals(
            '<input type="checkbox" name="foo" value="foobar" checked="checked">',
            $this->form->checkbox('foo', 'foobar', true)->toHtml()
        );
    }

    /** @test */
    public function it_can_make_checkbox_with_model_relation(): void
    {
        $this->mockSession(function (MockInterface $mock) {
            $mock->shouldReceive('getOldInput')->with('items')->andReturn(null);
            $mock->shouldReceive('getOldInput')->andReturn([]);
        });

        $models = [];

        foreach(range(2, 3) as $id) {
            $model     = new StdClass;
            $model->id = $id;
            $models[]  = $model;
        }

        $this->setModel(['items' => collect($models)]);

        static::assertEquals(
            '<input type="checkbox" name="items[]" value="1">',
            $this->form->checkbox('items[]', 1)->toHtml()
        );

        static::assertEquals(
            '<input type="checkbox" name="items[]" value="2" checked="checked">',
            $this->form->checkbox('items[]', 2)->toHtml()
        );

        static::assertEquals(
            '<input type="checkbox" name="items[]" value="3">',
            $this->form->checkbox('items[]', 3, false)->toHtml()
        );

        static::assertEquals(
            '<input type="checkbox" name="items[]" value="4" checked="checked">',
            $this->form->checkbox('items[]', 4, true)->toHtml()
        );
    }

    /** @test */
    public function it_can_test_the_checkable_method(): void
    {
        $reflector = new \ReflectionMethod(FormBuilder::class, 'checkable');
        $reflector->setAccessible(true);

        $result = $reflector->invokeArgs($this->form, ['checkable', 'checkable', 1, true, []]);

        static::assertEquals(
            '<input type="checkable" name="checkable" value="1">',
            $result->toHtml()
        );
    }

    /** @test */
    public function it_can_make_radio_inputs(): void
    {
        static::assertEquals(
            '<input type="radio" name="foo">',
            $this->form->input('radio', 'foo')->toHtml()
        );

        static::assertEquals(
            '<input type="radio" name="foo" value="foo">',
            $this->form->radio('foo')->toHtml()
        );

        static::assertEquals(
            '<input type="radio" name="foo" value="foobar" checked="checked">',
            $this->form->radio('foo', 'foobar', true)->toHtml()
        );

        static::assertEquals(
            '<input type="radio" name="foo" value="foobar" class="form-control">',
            $this->form->radio('foo', 'foobar', false, ['class' => 'form-control'])->toHtml()
        );
    }

    /** @test */
    public function it_can_make_populated_radio_inputs(): void
    {
        $this->mockSession(function (MockInterface $mock) {
            $mock->shouldReceive('getOldInput')
                ->with('radio')
                ->andReturn(1);
        });

        static::assertEquals(
            '<input type="radio" name="radio" value="1" checked="checked">',
            $this->form->radio('radio', 1)->toHtml()
        );

        static::assertEquals(
            '<input type="radio" name="radio" value="2">',
            $this->form->radio('radio', 2, true)->toHtml()
        );
    }

    /** @test */
    public function it_can_make_submit_inputs(): void
    {
        static::assertEquals(
            '<button type="submit">foo</button>',
            $this->form->submit('foo')->toHtml()
        );

        static::assertEquals(
            '<button type="submit" class="form-control">foo</button>',
            $this->form->submit('foo', ['class' => 'form-control'])->toHtml()
        );
    }

    /** @test */
    public function it_can_make_buttons(): void
    {
        static::assertEquals(
            '<button type="button">foo</button>',
            $this->form->button('foo')->toHtml()
        );

        static::assertEquals(
            '<button type="button" class="btn">foo</button>',
            $this->form->button('foo', ['class' => 'btn'])->toHtml()
        );

        static::assertEquals(
            '<button type="submit" class="btn">foo</button>',
            $this->form->button('foo', ['type' => 'submit', 'class' => 'btn'])->toHtml()
        );
    }

    /** @test */
    public function it_can_make_reset_inputs(): void
    {
        static::assertHtmlStringEqualsHtmlString(
            '<button type="reset">foo</button>',
            $this->form->reset('foo')->toHtml()
        );
    }

    /** @test */
    public function it_can_make_image_inputs(): void
    {
        $url = 'http://laravel.com/';

        static::assertHtmlStringEqualsHtmlString(
            '<input type="image" src="'. $url .'">',
            $this->form->image($url)->toHtml()
        );
    }

    /** @test */
    public function it_can_register_and_use_a_component(): void
    {
        $view       = '_components.text';
        $name       = 'first_name';
        $value      = null;
        $attributes = [];

        $this->form->component('bsText', $view, ['name', 'value', 'attributes']);

        static::assertEquals(
            view($view, compact('name', 'value', 'attributes'))->render(),
            $this->form->bsText($name, $value, $attributes)->toHtml()
        );
    }

    /* -----------------------------------------------------------------
     |  Other Methods
     | -----------------------------------------------------------------
     */

    /**
     * @return array
     */
    public function provideInputs(): array
    {
        return [
            [
                '<input type="text" name="foo">',
                'text',
                'foo',
                null,
                [],
            ],
            [
                '<input type="text" name="foo" value="foobar">',
                'text',
                'foo',
                'foobar',
                [],
            ],
            [
                '<input type="date" name="dob" class="form-control">',
                'date',
                'dob',
                null,
                ['class' => 'form-control'],
            ],
        ];
    }

    /**
     * @return array
     */
    public function providePassword(): array
    {
        return [
            [
                '<input type="password" name="foo">',
                'foo',
                []
            ],[
                '<input type="password" name="foo" class="form-control">',
                'foo',
                ['class' => 'form-control']
            ]
        ];
    }

    /**
     * Provider text inputs data
     *
     * @return array
     */
    public function provideTextInputs(): array
    {
        return [
            [
                '<input type="text" name="foo">',
                'foo',
                null,
                []
            ],[
                '<input type="text" name="foo" value="foobar">',
                'foo',
                'foobar',
                []
            ],[
                '<input type="text" name="foo" class="form-control">',
                'foo',
                null,
                ['class' => 'form-control']
            ]
        ];
    }

    /**
     * @return array
     */
    public function provideTextArrayAndObjectModel(): array
    {
        return [
            [
                '<input type="text" name="user[password]" value="apple">',
                [
                    'user' => (object) [
                        'password' => 'apple'
                    ]
                ],
                'user[password]'
            ],[
                '<input type="text" name="letters[1]" value="b">',
                (object) [
                    'letters' => ['a', 'b', 'c']
                ],
                'letters[1]'
            ]
        ];
    }

    /**
     * @return array
     */
    public function provideHiddenData(): array
    {
        return $this->getInputData('hidden');
    }

    /**
     * @return array
     */
    public function provideEmailData(): array
    {
        return $this->getInputData('email');
    }

    /**
     * @return array
     */
    public function provideTelInputs(): array
    {
        return $this->getInputData('tel');
    }

    /**
     * @return array
     */
    public function provideNumberInputs(): array
    {
        return $this->getInputData('number', 1);
    }

    /**
     * @return array
     */
    public function provideDateInputs(): array
    {
        return $this->getInputData('date', '2015-02-20', [
            [
                '<input type="date" name="foo" value="'.now()->format('Y-m-d').'">',
                'foo',
                now(),
                []
            ]
        ]);
    }

    /**
     * Provide datetime inputs.
     *
     * @return array
     */
    public function provideDateTimeInputs(): array
    {
        date_default_timezone_set('UTC');

        return [
            [
                '<input type="datetime" name="datetime" value="2015-01-01T00:00:00+00:00">',
                'datetime', new \DateTime('2015-01-01'), [],
            ],[
                '<input type="datetime" name="datetime" value="2015-01-01T15:01:01+00:00">',
                'datetime', new \DateTime('2015-01-01 15:01:01'), [],
            ],[
                '<input type="datetime" name="datetime" value="2015-01-01 15:01:01">',
                'datetime', '2015-01-01 15:01:01', [],
            ],[
                '<input type="datetime" name="datetime" value="2015-01-01 12:00:00" class="datetime-picker">',
                'datetime', '2015-01-01 12:00:00', ['class' => 'datetime-picker'],
            ]
        ];
    }

    /**
     * Provide datetime locale inputs.
     *
     * @return array
     */
    public function provideDateTimeLocaleInputs(): array
    {
        return [
            [
                '<input type="datetime-local" name="datetime-locale" value="2015-01-01T00:00">',
                'datetime-locale', new \DateTime('2015-01-01'), [],
            ],
            [
                '<input type="datetime-local" name="datetime-local" value="2015-01-01T15:01">',
                'datetime-local', new \DateTime('2015-01-01 15:01:01'), [],
            ],
            [
                '<input type="datetime-local" name="datetime-local" value="2015-01-01 15:01:01">',
                'datetime-local', '2015-01-01 15:01:01', [],
            ],
            [
                '<input type="datetime-local" name="datetime-local" value="2015-01-01 12:00:00" class="datetime-local-picker">',
                'datetime-local', '2015-01-01 12:00:00', ['class' => 'datetime-local-picker'],
            ],
        ];
    }

    /**
     * Provide color inputs.
     *
     * @return array
     */
    public function provideColorInputs(): array
    {
        return [
            [
                '<input type="color" name="palette">',
                'palette', null, [],
            ],
            [
                '<input type="color" name="palette" value="#BADA55">',
                'palette', '#BADA55', [],
            ],
            [
                '<input type="color" name="palette" value="#BADA55" class="palette-class">',
                'palette', '#BADA55', ['class' => 'palette-class'],
            ],
        ];
    }

    /**
     * @return array
     */
    public function provideTimeInputs(): array
    {
        return $this->getInputData('time', now()->format('H:i'));
    }

    /**
     * @return array
     */
    public function provideUrlInputs(): array
    {
        return [
            [
                '<input type="url" name="website">',
                'website',
                [],
            ],
            [
                '<input type="url" name="website" class="form-control">',
                'website',
                ['class' => 'form-control'],
            ],
        ];
    }

    /**
     * @return array
     */
    public function provideFileInputs(): array
    {
        return [
            [
                '<input type="file" name="foo">',
                'foo',
                [],
            ],
            [
                '<input type="file" name="foo" class="form-control">',
                'foo',
                ['class' => 'form-control'],
            ],
        ];
    }

    /**
     * @return array
     */
    public function provideTextAreaInputs(): array
    {
        return [
            [
                '<textarea name="foo"></textarea>',
                'foo', null, []
            ],[
                '<textarea name="foo" cols="50" rows="10">foobar</textarea>',
                'foo', 'foobar', ['cols' => 50, 'rows' => 10]
            ],[
                '<textarea name="foo" class="form-control"></textarea>',
                'foo', null, ['class' => 'form-control']
            ],[
                '<textarea name="foo" cols="60" rows="15"></textarea>',
                'foo', null, ['size' => '60x15']
            ],[
                '<textarea name="encoded_html" cols="60" rows="60">Eggs & Sausage</textarea>',
                'encoded_html', 'Eggs & Sausage', ['size' => '60x60']
            ],[
                '<textarea name="encoded_html" cols="60" rows="60">Eggs && Sausage</textarea>',
                'encoded_html', 'Eggs && Sausage', ['size' => '60x60']
            ],
        ];
    }

    /**
     * Provide form select data
     *
     * @return array
     */
    public function provideSelectData(): array
    {
        $list     = [
            'L' => 'Large',
            'S' => 'Small',
        ];
        $selected    = ['L', 'S'];
        $attributes  = [
            'name'     => 'sizes[]',
            'id'       => 'select-id',
            'multiple' => 'multiple',
            'class'    => 'class-name',
        ];

        return [
            [
                '<select name="size">'.
                '<option value="L">Large</option>'.
                '<option value="S">Small</option>'.
                '</select>',
                'size', $list, null, [],
            ],
            [
                '<select name="size">'.
                '<option value="L" selected>Large</option>'.
                '<option value="S">Small</option>'.
                '</select>',
                'size', $list, 'L', [],
            ],
            [
                '<select name="size" id="select-id" class="class-name">'.
                '<option value="L">Large</option>'.
                '<option value="S">Small</option>'.
                '</select>',
                'size', $list, null, ['id' => 'select-id', 'class' => 'class-name'],
            ],
            [
                '<select name="sizes[]" id="select-id" multiple="multiple" class="class-name">'.
                '<option value="L" selected>Large</option>'.
                '<option value="S" selected>Small</option>'.
                '</select>',
                'sizes', $list, $selected, $attributes,
            ],
            [
                // Test select with a option Collection
                '<select name="sizes[]" id="select-id" multiple="multiple" class="class-name">'.
                '<option value="L" selected>Large</option>'.
                '<option value="S" selected>Small</option>'.
                '</select>',
                'sizes', new Collection($list), $selected, $attributes,
            ],
            [
                // Test selects with a selected Collection
                '<select name="sizes[]" id="select-id" multiple="multiple" class="class-name">'.
                '<option value="L" selected>Large</option>'.
                '<option value="S" selected>Small</option>'.
                '</select>',
                'sizes', $list, new Collection($selected), $attributes
            ],
        ];
    }

    /**
     * Provide opening form data
     *
     * @return array
     */
    public function provideOpeningForms(): array
    {
        $url = $this->baseUrl . '/foo';

        return [
            [
                '<form method="GET" action="' . $url . '" accept-charset="UTF-8">',
                ['method' => 'GET']
            ],[
                '<form method="POST" action="' . $url . '" accept-charset="UTF-8" class="form" id="id-form">'.
                '<input type="hidden" name="_token" value="abc">',
                ['method' => 'POST', 'class' => 'form', 'id' => 'id-form']
            ],[
                '<form method="GET" action="' . $url . '" accept-charset="UTF-16">',
                ['method' => 'GET', 'accept-charset' => 'UTF-16']
            ],[
                '<form method="GET" action="' . $url . '" accept-charset="UTF-16" enctype="multipart/form-data">',
                ['method' => 'GET', 'accept-charset' => 'UTF-16', 'files' => true]
            ],[
                '<form method="POST" action="' . $url . '" accept-charset="UTF-8">'.
                '<input type="hidden" name="_method" value="PUT">'.
                '<input type="hidden" name="_token" value="abc">',
                ['method' => 'PUT']
            ]
        ];
    }

    /**
     * Provide labels data
     *
     * @return array
     */
    public function provideLabels(): array
    {
        return [
            [
                '<label for="foo">Foobar</label>',
                'foo',
                'Foobar',
                [],
            ],[
                '<label for="foo" class="control-label">Foobar</label>',
                'foo',
                'Foobar',
                ['class' => 'control-label'],
            ],[
                '<label for="foo">Foobar <i>bar</i></label>',
                'foo',
                'Foobar <i>bar</i>',
                [],
                false
            ],
        ];
    }

    /* -----------------------------------------------------------------
     |  Other Methods
     | -----------------------------------------------------------------
     */

    /**
     * Mock the session store.
     *
     * @param  \Closure|null  $mock
     *
     * @return \Mockery\MockInterface
     */
    protected function mockSession(Closure $mock = null): MockInterface
    {
        return tap($this->mock(Session::class, $mock), function ($session) {
            $this->form->setSessionStore($session);
        });
    }

    /**
     * Set model to form
     *
     * @param  array  $data
     * @param  bool   $object
     */
    protected function setModel(array $data, $object = true): void
    {
        $object = $object ? new FormBuilderModelStub($data) : $data;

        $this->form->model($object, ['method' => 'GET']);

        static::assertEquals($object, $this->form->getModel());
    }
}


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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent" >

  <ListView
    android:id="@+id/aboutList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</LinearLayout>
<!-- From: file:/local/mnt/workspace/jenkins-slave/workspace/FTC_External_Apps_Package/First/lib/FtcCommon/src/main/res/layout/about.xml -->

redpajama_set_name: RedPajamaGithub


text:
class Network
  include Processing::Proxy
  attr_accessor :neurons # this accessor is used to add neurons
  attr_reader :connections, :location

  def initialize(location:)
    @location = location
    @connections = []
  end

  # We can connection two Neurons
  def connect(from:, to:, weight: 0.5)
    c = Connection.new(from, to, weight)
    from.join(c)
    # Also add them to the network
    connections << c
  end

  # Sending an input to the first Neuron
  # We should do something better to track multiple inputs
  def feedforward(input)
    start = neurons.first
    start.feedforward(input)
  end

  # Update the animation
  def update
    connections.each(&:update)
  end

  # Draw everything
  def display
    push_matrix
    translate(location.x, location.y)
    neurons.each(&:display)
    connections.each(&:display)
    pop_matrix
  end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DiscordBot.Common;
using Google.Authenticator;
using MelissaNet;

namespace DiscordBot
{
    public partial class frmAuth : Form
    {
        public frmAuth()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.txtAccountTitle.Text = "MogiiBot3";
            string key = Guid.NewGuid().ToString().Replace("-", "");
            this.txtSecretKey.Text = key;
            Configuration.UpdateConfiguration(secretKey: Cryptography.EncryptString(key));

            TwoFactorAuthenticator tfA = new TwoFactorAuthenticator();
            var setupCode = tfA.GenerateSetupCode(this.txtAccountTitle.Text, this.txtSecretKey.Text, pbQR.Width, pbQR.Height);

            WebClient wc = new WebClient();
            MemoryStream ms = new MemoryStream(wc.DownloadData(setupCode.QrCodeSetupImageUrl));
            this.pbQR.Image = Image.FromStream(ms);
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            TwoFactorAuthenticator tfA = new TwoFactorAuthenticator();
            var result = tfA.ValidateTwoFactorPIN(txtSecretKey.Text, this.txtCode.Text);

            MessageBox.Show(result ? "Code Valid! TwoAuth setup successful." : "Incorrect", "Result");

            if (result)
            {
                Close();
            }
        }
    }
}


text:
package io.agora.contract.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.update.BmobUpdateAgent;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformDb;
import io.agora.contract.activity.FeedBackActivity;
import io.agora.contract.activity.MineSettingActivity;
import io.agora.contract.activity.ServiceCenterActivity;
import io.agora.contract.utils.LogUtils;
import io.agora.contract.utils.Utils;
import io.agora.contract.view.CircleImageView;
import io.agora.model.EventMsg;
import io.agora.model.LiveVideos;
import io.agora.model.MyUser;
import io.agora.openlive.R;
import io.agora.presenter.IContentFragmentPresenter;
import io.agora.presenter.IContentFragmentPresenterImpl;
import io.agora.presenter.IMineFragmentPresentImpl;
import io.agora.presenter.IMineFragmentPresenter;

/**
 * File Name:
 * Author:      ruan
 * Write Dates: 2017/7/6
 * Description:
 */

public class MineFragment extends BaseFragment implements  IMineFragment{

    private RadioButton setting;
    private CircleImageView avatar;
    private TextView tv_user_name;
    IMineFragmentPresenter iMineFragmentPresenter;
    TextView tv_like;
    TextView tv_live;
    TextView tv_gift;
    LinearLayout ll_service;
    LinearLayout ll_update;
    LinearLayout reply;
    TextView tv_app_version;

    private boolean isFirst = true;

    int like;
    int live;
    int gift;

    @Override
    public View initView() {
//        EventBus.getDefault().register(this);
        View view = View.inflate(context, R.layout.fragment_mine,null);
        setting = (RadioButton) view.findViewById(R.id.setting);
        avatar = (CircleImageView) view.findViewById(R.id.avatar);
        tv_user_name = (TextView) view.findViewById(R.id.tv_user_name);
        tv_like = (TextView) view.findViewById(R.id.tv_like);
        tv_gift = (TextView) view.findViewById(R.id.tv_gift);
        tv_live = (TextView) view.findViewById(R.id.tv_live);
        ll_service = (LinearLayout) view.findViewById(R.id.ll_service);
        tv_app_version = (TextView) view.findViewById(R.id.tv_app_version);
        ll_update = (LinearLayout) view.findViewById(R.id.ll_update);
        reply = (LinearLayout) view.findViewById(R.id.reply);
        return view;
    }

    @Override
    public void initData() {

        tv_like.setText("喜欢:"+like);
        tv_live.setText("直播:"+live);
        tv_gift.setText("礼物:"+gift);
        tv_app_version.setText(Utils.getVersionName(context)+"");
        if(isFirst&&BmobUser.getCurrentUser()!=null){
            iMineFragmentPresenter = new IMineFragmentPresentImpl(this,context);
            iMineFragmentPresenter.getData();
            iMineFragmentPresenter.RealTimeCallBack();
            isFirst = false;
        }

        //点击设置跳转到个人信息设置界面
        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MineSettingActivity.class);
                context.startActivity(intent);
            }
        });

        MyUser user = BmobUser.getCurrentUser(MyUser.class);
        if(user!=null){

            if(user.getHead_icon()!=null){

                Glide.with(context).load(user.getHead_icon().getUrl()).into(avatar);
            }else{
                Glide.with(context).load(user.getAuthIconUrl()).into(avatar);
            }
            if(!TextUtils.isEmpty(user.getUser_id_name())){
                tv_user_name.setText(user.getUser_id_name().toString());
            }
        }
        //客服中心按钮
        ll_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(context, ServiceCenterActivity.class);
                startActivity(intent);

            }
        });

        //应用更新
        ll_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BmobUpdateAgent.forceUpdate(context);
            }
        });

        //意见反馈
        reply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, FeedBackActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    public String setTitile() {
        return "我的";
    }

    @Override
    public void getData(int code, String e, LiveVideos liveVideos) {

        if(code == 0){

            LogUtils.e("获取到对应信息---->"+liveVideos.getLikes());
            like = liveVideos.getLikes();
            live = liveVideos.getLiveTimes();
            gift = liveVideos.getGift_times();
            tv_like.setText("喜欢:"+liveVideos.getLikes());
            tv_live.setText("直播:"+liveVideos.getLiveTimes());
            tv_gift.setText("礼物:"+liveVideos.getGift_times());

        }else{
            LogUtils.e("获取失败------>"+e);
        }

    }

    @Override
    public void RealTimeCallBack(int code, List<LiveVideos> videos) {

        if(iMineFragmentPresenter!=null){

            iMineFragmentPresenter.getData();
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        EventBus.getDefault().unregister(this);
    }

}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.DataVisualization.Charting;
using MOE.Common.Business.SplitFail;
using MOE.Common.Models;
using MOE.Common.Models.Repositories;

namespace MOE.Common.Business.WCFServiceLibrary
{
    [DataContract]
    public class SplitFailOptions : MetricOptions
    {
        public SplitFailOptions(string signalID, DateTime startDate, DateTime endDate,
            int metricTypeID, int firstSecondsOfRed, bool showFailLines, bool showAvgLines, bool showPercentFailLine)
        {
            SignalID = signalID;
            StartDate = startDate;
            EndDate = endDate;
            MetricTypeID = metricTypeID;
            FirstSecondsOfRed = firstSecondsOfRed;
            ShowFailLines = showFailLines;
            ShowAvgLines = showAvgLines;
            ShowPercentFailLines = showPercentFailLine;
        }

        public SplitFailOptions()
        {
            MetricTypeID = 12;
            SetDefaults();
        }

        [Required]
        [DataMember]
        [Display(Name = "First Seconds Of Red")]
        public int FirstSecondsOfRed { get; set; }

        [DataMember]
        [Display(Name = "Show Fail Lines")]
        public bool ShowFailLines { get; set; }

        [DataMember]
        [Display(Name = "Show Average Lines")]
        public bool ShowAvgLines { get; set; }

        [DataMember]
        [Display(Name = "Show Percent Fail Lines")]
        public bool ShowPercentFailLines { get; set; }

        public override List<string> CreateMetric()
        {
            base.CreateMetric();
            //EndDate = EndDate.AddSeconds(59);
            var returnString = new List<string>();
            var sr = SignalsRepositoryFactory.Create();
            var signal = sr.GetVersionOfSignalByDate(SignalID, StartDate);
            var metricApproaches = signal.GetApproachesForSignalThatSupportMetric(MetricTypeID);
            if (metricApproaches.Count > 0)
            {
                List<SplitFailPhase> splitFailPhases = new List<SplitFailPhase>();
                foreach (Approach approach in metricApproaches)
                {
                    if (approach.PermissivePhaseNumber != null && approach.PermissivePhaseNumber > 0)
                    {
                        splitFailPhases.Add(new SplitFailPhase(approach, this, true));
                    }
                    if (approach.ProtectedPhaseNumber > 0)
                    {
                        splitFailPhases.Add(new SplitFailPhase(approach, this, false));
                    }
                }
                splitFailPhases = splitFailPhases.OrderBy(s => s.PhaseNumberSort).ToList();
                foreach (var splitFailPhase in splitFailPhases)
                {
                    GetChart(splitFailPhase, returnString);
                }
            }
            return returnString;
        }

        private void GetChart(SplitFailPhase splitFailPhase, List<string> returnString)
        {
            var sfChart = new SplitFailChart(this, splitFailPhase, splitFailPhase.GetPermissivePhase);
            var detector = splitFailPhase.Approach.GetDetectorsForMetricType(12).FirstOrDefault();
            if (detector != null)
            {
                if (splitFailPhase.GetPermissivePhase)
                {
                    sfChart.Chart.BackColor = Color.LightGray;
                }
            }
            //Thread.Sleep(300);
            string chartName = CreateFileName();
            chartName = chartName.Replace(".", splitFailPhase.Approach.DirectionType.Description + ".");
            try
            {
                sfChart.Chart.SaveImage(MetricFileLocation + chartName, ChartImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                try
                {
                    sfChart.Chart.SaveImage(MetricFileLocation + chartName, ChartImageFormat.Jpeg);
                }
                catch
                {
                    var appEventRepository =
                        ApplicationEventRepositoryFactory.Create();
                    var applicationEvent = new ApplicationEvent();
                    applicationEvent.ApplicationName = "SPM Website";
                    applicationEvent.Description = MetricType.ChartName + ex.Message + " Failed While Saving File";
                    applicationEvent.SeverityLevel = ApplicationEvent.SeverityLevels.Medium;
                    applicationEvent.Timestamp = DateTime.Now;
                    appEventRepository.Add(applicationEvent);
                }
            }
            returnString.Add(MetricWebPath + chartName);
        }
    }
}


text:
"""
A very simple twisted.words.im-based logbot.

To run the script:
$ python minchat.py
"""

from __future__ import print_function

from twisted.words.im import basechat, baseaccount, ircsupport

# A list of account objects. We might as well create them at runtime, this is
# supposed to be a Minimalist Implementation, after all.

accounts = [
    ircsupport.IRCAccount("IRC", 1,
        "Tooty",            # nickname
        "",                 # passwd
        "irc.freenode.net", # irc server
        6667,               # port
        "#twisted",         # comma-separated list of channels
    )
]

class AccountManager (baseaccount.AccountManager):
    """
    This class is a minimal implementation of the Account Manager.

    Most implementations will show some screen that lets the user add and
    remove accounts, but we're not quite that sophisticated.
    """

    def __init__(self):

        self.chatui = MinChat()

        if len(accounts) == 0:
            print("You have defined no accounts.")
        for acct in accounts:
            acct.logOn(self.chatui)

class MinConversation(basechat.Conversation):
    """
    This class is a minimal implementation of the abstract Conversation class.

    This is all you need to override to receive one-on-one messages.
    """
    def show(self):
        """
        If you don't have a GUI, this is a no-op.
        """
        pass

    def hide(self):
        """
        If you don't have a GUI, this is a no-op.
        """
        pass

    def showMessage(self, text, metadata=None):
        print("<%s> %s" % (self.person.name, text))

    def contactChangedNick(self, person, newnick):
        basechat.Conversation.contactChangedNick(self, person, newnick)
        print("-!- %s is now known as %s" % (person.name, newnick))

class MinGroupConversation(basechat.GroupConversation):
    """
    This class is a minimal implementation of the abstract GroupConversation class.

    This is all you need to override to listen in on a group conversation.
    """
    def show(self):
        """
        If you don't have a GUI, this is a no-op.
        """
        pass

    def hide(self):
        """
        If you don't have a GUI, this is a no-op.
        """
        pass

    def showGroupMessage(self, sender, text, metadata=None):
        print("<%s/%s> %s" % (sender, self.group.name, text))

    def setTopic(self, topic, author):
        print("-!- %s set the topic of %s to: %s" % (author,
            self.group.name, topic))

    def memberJoined(self, member):
        basechat.GroupConversation.memberJoined(self, member)
        print("-!- %s joined %s" % (member, self.group.name))

    def memberChangedNick(self, oldnick, newnick):
        basechat.GroupConversation.memberChangedNick(self, oldnick, newnick)
        print("-!- %s is now known as %s in %s" % (oldnick, newnick,
            self.group.name))

    def memberLeft(self, member):
        basechat.GroupConversation.memberLeft(self, member)
        print("-!- %s left %s" % (member, self.group.name))

class MinChat(basechat.ChatUI):
    """
    This class is a minimal implementation of the abstract ChatUI class.

    There are only two methods that need overriding - and of those two,
    the only change that needs to be made is the default value of the Class
    parameter.
    """

    def getGroupConversation(self, group, Class=MinGroupConversation,
        stayHidden=0):

        return basechat.ChatUI.getGroupConversation(self, group, Class,
            stayHidden)

    def getConversation(self, person, Class=MinConversation,
        stayHidden=0):

        return basechat.ChatUI.getConversation(self, person, Class, stayHidden)

if __name__ == "__main__":
    from twisted.internet import reactor

    AccountManager()

    reactor.run()


text:
import socket
import time

from thrift.transport import TTransport
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
from thrift import Thrift
from milo.protocols.thrift import TMiloProtocol
from milo.thrift.ttypes import EventType
import milo.storage.thread_storage as thread_storage
import milo.util.span as span_util

class ThriftClient(object):
    def __init__(self, service, host, port, service_name=None, timeout=None, transport="framed"):
        self.socket = TSocket.TSocket(host, port)
        self.service = service

        if service_name:
            self.service_name = service_name
        else:
            self.service_name = service.__name__.split(".")[-1].capitalize()

        if timeout:
            self.socket.setTimeout(timeout)

        if transport == "framed":
            self.transport = TTransport.TFramedTransport(self.socket)
        elif transport == "buffered":
            self.transport = TTransport.TBufferedTransport(self.socket)
        else:
            raise ValueError("%s transport not supported" % (transport))

        self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
        self.client_ = self.service.Client(self.protocol)
        self.client_.transport = self.transport

    def isOpen(self):
        """Is the connection open?"""
        return self.client_.transport.isOpen()

    def open(self):
        """Connect to host"""
        self.client_.transport.open()

    def close(self):
        """Disconnect from host"""
        self.client_.transport.close()

    def __getattr__(self, attr):
        def default_method(*args, **kwargs):
            return getattr(self.client_, attr).__call__(*args, **kwargs)
        return default_method

class MiloThriftClient(ThriftClient):
    def __init__(self, *args, **kwargs):
        ThriftClient.__init__(self, *args, **kwargs)
        self.trace_context = thread_storage.getTraceContext()
        self.client_ip = socket.gethostbyname(socket.gethostname())
        self.protocol = TMiloProtocol(self.transport)
        self.client_ = self.service.Client(self.protocol)
        self.client_.transport = self.transport

    def enableTrace(self, root_span):
        self.trace_context.addSpan(root_span)
        self.trace_context.setTraceID(root_span.trace_id)
        self.trace_context.setSpanParentID(root_span.id)
        self.trace_context.setEnabled(True)

    def getTraceContext(self):
        return self.trace_context

    def logSpan(self, rpc_method, start_time, end_time):
        trace_id = self.trace_context.getTraceID()
        span_id = self.trace_context.getSpanID()
        span_parent_id = self.trace_context.getSpanParentID()
        name = span_util.createSpanName(self.service_name, rpc_method)
        span = span_util.createSpan(name=name,
                                     trace_id=trace_id,
                                     span_id=span_id,
                                     span_parent_id=span_parent_id)

        span.client_host = self.client_ip
        span.events = [span_util.createEvent(long(start_time), EventType.CLIENT_RECV), \
                       span_util.createEvent(long(end_time), EventType.CLIENT_SEND)]
        self.trace_context.addSpan(span)

    def __getattr__(self, attr):
        def default_method(*args, **kwargs):
            start_time = time.time() * 1000000
            func = getattr(self.client_, attr).__call__(*args, **kwargs)
            end_time = time.time() * 1000000

            if self.trace_context.isEnabled():
                self.logSpan(attr, start_time, end_time)

            return func
        return default_method


text:
:root {
  --card-background-color: white;
  --card-text-line-height: 1.4;
  --card-text-font-size: 14px;
  --card-text-color: #030303;
  --material-card-background-color: white;
  --material-card-text-line-height: 1.4;
  --material-card-text-font-size: 14px;
  --material-card-text-color: rgba(0, 0, 0, 0.54);
}

/*~
  name: Card
  category: Card
  markup: |

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

*/

.card {
  @apply(--reset-font);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12);
  border-radius: 8px;
  background-color: var(--card-background-color);
  box-sizing: border-box;
  display: block;
  margin: 8px;
  padding: 16px;
  text-align: left;
}

.card__content {
  margin: 0;
  font-size: var(--card-text-font-size);
  line-height: var(--card-text-line-height);
  color: var(--card-text-color);
}

/*~
  name: Card with Title
  category: Card
  markup: |

Card Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

*/
.card__title {
  @apply(--reset-font);
  font-weight: 400;
  font-size: 20px;
  margin: 4px 0 8px 0;
  padding: 0;
  display: block;
  box-sizing: border-box;
}

/*~
  name: Material Card
  category: Card
  markup: |

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

*/

.card--material {
  background-color: var(--material-card-background-color);
  border-radius: 2px;
  @apply(--material-shadow-1);
  @apply(--material-font);
}

.card--material__content {
  font-size: var(--material-card-text-font-size);
  line-height: var(--material-card-text-line-height);
  color: var(--material-card-text-color);
}

/*~
  name: Material Card with Title
  category: Card
  markup: |

Card Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

*/

.card--material__title {
  @apply(--material-font);
  font-size: 24px;
  margin: 8px 0 12px 0;
}


text:
dwilib
======

Personal C Library to make my life easier :)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Loki: Smart pointers</title>
<link href="tabs.css" rel="stylesheet" type="text/css">
<link href="doxygen.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

Smart pointers

Collaboration diagram for Smart pointers:

Classes

struct  	std::less< Loki::StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > >

class  	Loki::RefToValue< T >

struct  	Loki::NullPointerException

class  	Loki::SmartPtr< T, OwnershipPolicy, ConversionPolicy, CheckingPolicy, StoragePolicy, ConstnessPolicy >

class  	Loki::StrongPtr< T, Strong, OwnershipPolicy, ConversionPolicy, CheckingPolicy, ResetPolicy, DeletePolicy, ConstnessPolicy >

Namespaces

namespace  	std

Modules

 	Ownership policies

 	Storage policies

 	Conversion policies

 	Checking policies

 	StrongPtr Ownership policies

 	Delete policies

 	Reset policies

Functions

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP1, typename U >

bool 	Loki::operator== (const SmartPtr< T, OP, CP, KP, SP, CNP1 > &lhs, U *rhs)

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP1, typename U >

bool 	Loki::operator== (U *lhs, const SmartPtr< T, OP, CP, KP, SP, CNP1 > &rhs)

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

bool 	Loki::operator!= (const SmartPtr< T, OP, CP, KP, SP, CNP > &lhs, U *rhs)

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

bool 	Loki::operator!= (U *lhs, const SmartPtr< T, OP, CP, KP, SP, CNP > &rhs)

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

bool 	Loki::operator< (const SmartPtr< T, OP, CP, KP, SP, CNP > &lhs, U *rhs)

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

bool 	Loki::operator< (U *lhs, const SmartPtr< T, OP, CP, KP, SP, CNP > &rhs)

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

bool 	Loki::operator> (const SmartPtr< T, OP, CP, KP, SP, CNP > &lhs, U *rhs)

 	/////////////////////////////////////////////////////////////////////////////

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

bool 	Loki::operator> (U *lhs, const SmartPtr< T, OP, CP, KP, SP, CNP > &rhs)

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

bool 	Loki::operator<= (const SmartPtr< T, OP, CP, KP, SP, CNP > &lhs, U *rhs)

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

bool 	Loki::operator<= (U *lhs, const SmartPtr< T, OP, CP, KP, SP, CNP > &rhs)

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

bool 	Loki::operator>= (const SmartPtr< T, OP, CP, KP, SP, CNP > &lhs, U *rhs)

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

bool 	Loki::operator>= (U *lhs, const SmartPtr< T, OP, CP, KP, SP, CNP > &rhs)

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

bool 	Loki::operator== (const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &lhs, U *rhs)

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

bool 	Loki::operator== (U *lhs, const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &rhs)

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

bool 	Loki::operator!= (const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &lhs, U *rhs)

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

bool 	Loki::operator!= (U *lhs, const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &rhs)

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

bool 	Loki::operator< (const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &lhs, U *rhs)

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

bool 	Loki::operator< (U *lhs, const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &rhs)

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

bool 	Loki::operator> (U *lhs, const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &rhs)

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

bool 	Loki::operator<= (const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &lhs, U *rhs)

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

bool 	Loki::operator<= (U *lhs, const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &rhs)

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

bool 	Loki::operator>= (const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &lhs, U *rhs)

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

bool 	Loki::operator>= (U *lhs, const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &rhs)

Detailed Description

Policy based implementation of a smart pointer

Function Documentation

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

          bool Loki::operator!=
          (
          U *
           lhs,

          const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &
           rhs

          )
          		 [inline]

operator!= for lhs = raw pointer, rhs = StrongPtr

References Loki::StrongPtr< T, Strong, OwnershipPolicy, ConversionPolicy, CheckingPolicy, ResetPolicy, DeletePolicy, ConstnessPolicy >::Equals().

Here is the call graph for this function:

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

          bool Loki::operator!=
          (
          const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &
           lhs,

          U *
           rhs

          )
          		 [inline]

operator!= for lhs = StrongPtr, rhs = raw pointer

References Loki::StrongPtr< T, Strong, OwnershipPolicy, ConversionPolicy, CheckingPolicy, ResetPolicy, DeletePolicy, ConstnessPolicy >::Equals().

Here is the call graph for this function:

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

          bool Loki::operator!=
          (
          U *
           lhs,

          const SmartPtr< T, OP, CP, KP, SP, CNP > &
           rhs

          )
          		 [inline]

operator!= for lhs = raw pointer, rhs = SmartPtr

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

          bool Loki::operator!=
          (
          const SmartPtr< T, OP, CP, KP, SP, CNP > &
           lhs,

          U *
           rhs

          )
          		 [inline]

operator!= for lhs = SmartPtr, rhs = raw pointer

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

          bool Loki::operator<
          (
          U *
           lhs,

          const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &
           rhs

          )
          		 [inline]

operator< for lhs = raw pointer, rhs = StrongPtr

References Loki::StrongPtr< T, Strong, OwnershipPolicy, ConversionPolicy, CheckingPolicy, ResetPolicy, DeletePolicy, ConstnessPolicy >::GreaterThan().

Here is the call graph for this function:

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

          bool Loki::operator<
          (
          const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &
           lhs,

          U *
           rhs

          )
          		 [inline]

operator< for lhs = StrongPtr, rhs = raw pointer

References Loki::StrongPtr< T, Strong, OwnershipPolicy, ConversionPolicy, CheckingPolicy, ResetPolicy, DeletePolicy, ConstnessPolicy >::LessThan().

Here is the call graph for this function:

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

          bool Loki::operator<
          (
          U *
           lhs,

          const SmartPtr< T, OP, CP, KP, SP, CNP > &
           rhs

          )
          		 [inline]

operator< for lhs = raw pointer, rhs = SmartPtr

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

          bool Loki::operator<
          (
          const SmartPtr< T, OP, CP, KP, SP, CNP > &
           lhs,

          U *
           rhs

          )
          		 [inline]

operator< for lhs = SmartPtr, rhs = raw pointer

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

          bool Loki::operator<=
          (
          U *
           lhs,

          const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &
           rhs

          )
          		 [inline]

operator<= for lhs = raw pointer, rhs = StrongPtr

References Loki::StrongPtr< T, Strong, OwnershipPolicy, ConversionPolicy, CheckingPolicy, ResetPolicy, DeletePolicy, ConstnessPolicy >::LessThan().

Here is the call graph for this function:

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

          bool Loki::operator<=
          (
          const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &
           lhs,

          U *
           rhs

          )
          		 [inline]

operator<= for lhs = StrongPtr, rhs = raw pointer

References Loki::StrongPtr< T, Strong, OwnershipPolicy, ConversionPolicy, CheckingPolicy, ResetPolicy, DeletePolicy, ConstnessPolicy >::GreaterThan().

Here is the call graph for this function:

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

          bool Loki::operator<=
          (
          U *
           lhs,

          const SmartPtr< T, OP, CP, KP, SP, CNP > &
           rhs

          )
          		 [inline]

operator<= for lhs = raw pointer, rhs = SmartPtr

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

          bool Loki::operator<=
          (
          const SmartPtr< T, OP, CP, KP, SP, CNP > &
           lhs,

          U *
           rhs

          )
          		 [inline]

operator<= for lhs = SmartPtr, rhs = raw pointer

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

          bool Loki::operator==
          (
          U *
           lhs,

          const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &
           rhs

          )
          		 [inline]

operator== for lhs = raw pointer, rhs = StrongPtr

References Loki::StrongPtr< T, Strong, OwnershipPolicy, ConversionPolicy, CheckingPolicy, ResetPolicy, DeletePolicy, ConstnessPolicy >::Equals().

Here is the call graph for this function:

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

          bool Loki::operator==
          (
          const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &
           lhs,

          U *
           rhs

          )
          		 [inline]

operator== for lhs = StrongPtr, rhs = raw pointer

References Loki::StrongPtr< T, Strong, OwnershipPolicy, ConversionPolicy, CheckingPolicy, ResetPolicy, DeletePolicy, ConstnessPolicy >::Equals().

Here is the call graph for this function:

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP1, typename U >

          bool Loki::operator==
          (
          U *
           lhs,

          const SmartPtr< T, OP, CP, KP, SP, CNP1 > &
           rhs

          )
          		 [inline]

operator== for lhs = raw pointer, rhs = SmartPtr

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP1, typename U >

          bool Loki::operator==
          (
          const SmartPtr< T, OP, CP, KP, SP, CNP1 > &
           lhs,

          U *
           rhs

          )
          		 [inline]

operator== for lhs = SmartPtr, rhs = raw pointer

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

          bool Loki::operator>
          (
          U *
           lhs,

          const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &
           rhs

          )
          		 [inline]

operator> for lhs = raw pointer, rhs = StrongPtr

References Loki::StrongPtr< T, Strong, OwnershipPolicy, ConversionPolicy, CheckingPolicy, ResetPolicy, DeletePolicy, ConstnessPolicy >::LessThan().

Here is the call graph for this function:

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

          bool Loki::operator>
          (
          U *
           lhs,

          const SmartPtr< T, OP, CP, KP, SP, CNP > &
           rhs

          )
          		 [inline]

operator> for lhs = raw pointer, rhs = SmartPtr

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

          bool Loki::operator>=
          (
          U *
           lhs,

          const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &
           rhs

          )
          		 [inline]

operator>= for lhs = raw pointer, rhs = StrongPtr

References Loki::StrongPtr< T, Strong, OwnershipPolicy, ConversionPolicy, CheckingPolicy, ResetPolicy, DeletePolicy, ConstnessPolicy >::GreaterThan().

Here is the call graph for this function:

template<typename U , typename T , bool S, class OP , class CP , template< class > class KP, template< class > class RP, template< class > class DP, template< class > class CNP>

          bool Loki::operator>=
          (
          const StrongPtr< T, S, OP, CP, KP, RP, DP, CNP > &
           lhs,

          U *
           rhs

          )
          		 [inline]

operator>= for lhs = StrongPtr, rhs = raw pointer

References Loki::StrongPtr< T, Strong, OwnershipPolicy, ConversionPolicy, CheckingPolicy, ResetPolicy, DeletePolicy, ConstnessPolicy >::LessThan().

Here is the call graph for this function:

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

          bool Loki::operator>=
          (
          U *
           lhs,

          const SmartPtr< T, OP, CP, KP, SP, CNP > &
           rhs

          )
          		 [inline]

operator>= for lhs = raw pointer, rhs = SmartPtr

template<typename T , template< class > class OP, class CP , template< class > class KP, template< class > class SP, template< class > class CNP, typename U >

          bool Loki::operator>=
          (
          const SmartPtr< T, OP, CP, KP, SP, CNP > &
           lhs,

          U *
           rhs

          )
          		 [inline]

operator>= for lhs = SmartPtr, rhs = raw pointer

<address style="text-align: right;">Generated on Thu Jan 29 18:51:41 2009 for Loki by

 1.5.8 </address>


text:
from pprint import pprint, pformat
from collections import defaultdict

import birdsql

class ConnectionInfo(object):
    def __init__(self, host="", port=3306, user="", password="", db_name=""):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.db_name = db_name

class DatabaseObject(object):
    _table_name = None
    _id_column = "id"
    _ignore_list = [ _id_column ]

    def __init__(self, _strict_mode=False, **kwargs):
        """
        Pass in whatever instance variables you want set as kwargs.
        This can be called from any subclass in order to easily
        create instance objects. This should be called last
        as to prevent values being overridden with None.
        @strict_mode makes it so that only values that are
        already defined (usually set to None) can be set.
        --- this:
        obj = DatabaseObject()
        obj.id = 5
        obj.name = 'string'
        --- becomes:
        obj = DatabaseObject(id=5, name='string')
        """
        for key, val in kwargs.items():
            if not _strict_mode or key in self.__dict__:
                self.__dict__[key] = val

    def get_id(self):
        return self.__dict__[self._id_column]

    def set_id(self, val):
        self.__dict__[self._id_column] = val

    def dump(self):
        pprint(self.__dict__)

    def dump_str(self):
        return pformat(self.__dict__)

    def insert(self, replace_into=False):
        """
        Insert this item into the database, optionally "REPLACE INTO"
        """
        return birdsql._get_db().insert_generic(self, replace_into=replace_into)

    def insert_or_update(self):
        return birdsql._get_db().insert_or_update_generic(self)

    def update_full(self):
        return birdsql._get_db().update_generic_full(self)

    def update(self, what_list=None):
        return birdsql._get_db().update_generic(self, what_list)

    def delete(self):
        return birdsql._get_db().delete_generic(self)

    def from_id(self, id, include_extras=False):
        kwargs = { self._id_column : id }
        return self.query_one(include_extras=include_extras, **kwargs)

    def query_all(self, limit=None, order_by=None, include_extras=False, _log=False, **kwargs):
        #TODO: Does kwargs.keys() and kwargs.values() return items in the same order?
        where_clause = limit_clause = order_clause = ''
        values = []
        if kwargs is not None and len(kwargs.keys()) > 0:
            where_parts = []
            for key, value in kwargs.items():
                where_part, use_value = self.get_where_part(key, value)
                where_parts.append(where_part)
                if use_value:
                    values.append(value)
            where_clause = ' where ' + ' and '.join(where_parts)
        if limit is not None:
            limit_clause = ' limit {0} '.format(limit)
        if order_by is not None:
            order_clause = ' order by {0} '.format(order_by) if not order_by.strip().startswith('order') else order_by
        query = 'select * from `{0}` {1} {2} {3} '.format(self._table_name, where_clause, order_clause, limit_clause)
        if _log:
            print query
            pprint(kwargs)
        rows = birdsql._get_db().fetch_all(query, tuple(values))
        if _log:
            print 'Total rows returned:', len(rows)
        return self._create_objects(rows, include_extras)

    """
    Returns (where_part, use_value)
    """
    def get_where_part(self, key, value):
        if value is None:
            return '`{0}` is NULL'.format(key), False
        elif key.endswith("_like_"):
            return '`{0}` like %s'.format(key.replace("_like_", "")), True
        elif key.endswith("_null_"):
            return '`{0}` is {1}NULL'.format(key.replace("_null_", ""), "" if value else "not "), False
        else:
            return '`{0}`=%s'.format(key), True

    def query_one(self, order_by=None, include_extras=False, _log=False, **kwargs):
        all = self.query_all(limit=1, order_by=order_by, include_extras=include_extras, _log=_log, **kwargs)
        res = all[0] if all is not None else None
        if _log:
            res.dump()
        return res

    def raw_query_one(self, query, values, include_extras=False):
        row = birdsql._get_db().fetch_one(query, values)
        return self._create_object(row, include_extras)

    def raw_query_all(self, query, values, include_extras=False):
        rows = birdsql._get_db().fetch_all(query, values)
        return self._create_objects(rows, include_extras)

    def _create_objects(self, rows, include_extras=False):
        if rows is None or len(rows) == 0:
            return None
        else:
            return [ birdsql._get_db().get_generic(self.__class__(), row, include_extras) for row in rows ]

    def _create_object(self, row, include_extras=False):
        return birdsql._get_db().get_generic(self, row, include_extras)

    def query_all_grouped(self, group_col, limit=None, order_by=None, include_extras=False, _log=False, **kwargs):
        all = self.query_all(limit=limit, order_by=order_by, include_extras=include_extras, _log=_log, **kwargs)
        res = defaultdict(list)
        for item in all:
            key = item.__dict__[group_col]
            res[key].append(item)
        return res


text:
package com.gansuer.common.util;

import org.apache.log4j.Logger;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class ZipUtil {
    private static Logger logger = Logger.getLogger(ZipUtil.class);

    public static byte[] gZip(byte[] data) {
        byte[] b = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(bos);
            gzip.write(data);
            gzip.finish();
            gzip.close();
            b = bos.toByteArray();
            bos.close();
        } catch (Exception ex) {
            logger.error("解压缩出现异常:", ex);
        }
        return b;
    }

    /**
     * gZip解压方法
     */
    public static byte[] unGZip(byte[] data) {
        byte[] b = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(data);
            GZIPInputStream gzip = new GZIPInputStream(bis);
            byte[] buf = new byte[1024];
            int num = -1;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((num = gzip.read(buf, 0, buf.length)) != -1) {
                baos.write(buf, 0, num);
            }
            b = baos.toByteArray();
            baos.flush();
            baos.close();
            gzip.close();
            bis.close();
        } catch (Exception ex) {
            logger.error("解压缩出现异常:", ex);
        }
        return b;
    }
}


text:
export interface IMatch {
  id: string
  context: {
    sourceMessage: string
    [key: string]: unknown
  }
  error?: Error | undefined
  [key: string]: unknown
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lades.sihv.controller.NewConsultation;

import com.lades.sihv.bean.AbstractBean;
import com.lades.sihv.controller.RenderedFields;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author thiberius
 */
public class ControllerExamLaboratory extends AbstractBean {

    private final List<RenderedFields> listViewFields = new ArrayList();
    private final String ndn = "Nada digno de nota.";

//  GETs & SETs

    private RenderedFields getListViewFields(int index) {
        if (listViewFields.isEmpty()) {
            listViewFields.add(index, new RenderedFields());
        } else if ((listViewFields.size() - index) == 0) {
            listViewFields.add(index, new RenderedFields());
        }
        return listViewFields.get(index);
    }

    private void startIndexListViewFields() {
        for (int index = 0; index <= 5; index++) {
            listViewFields.add(index, new RenderedFields());
            listViewFields.get(index).setViewVariableBoolean(false);
        }
    }

    public RenderedFields getViewExamLaboratory() {
        if (getListViewFields(0).isViewVariableBoolean()) {

        } else {

            startIndexListViewFields();
        }
        return getListViewFields(0);
    }
}


text:
package com.doglandia.unearthed.model;

import com.google.android.gms.maps.model.LatLng;

import java.util.List;

public class PlaceDetails {

    Place place;

    int averageDistance;
    int bestDistance;

    List<LatLng> locationGuesses;

    public Place getPlace() {
        return place;
    }

    public int getAverageDistance() {
        return averageDistance;
    }

    public int getBestDistance() {
        return bestDistance;
    }

    public List<LatLng> getLocationGuesses() {
        return locationGuesses;
    }

    public void setPlace(Place place) {
        this.place = place;
    }

    public void setAverageDistance(int averageDistance) {
        this.averageDistance = averageDistance;
    }

    public void setBestDistance(int bestDistance) {
        this.bestDistance = bestDistance;
    }

    public void setLocationGuesses(List<LatLng> locationGuesses) {
        this.locationGuesses = locationGuesses;
    }
}