text:
<?php
namespace Aws\Test\Endpoint;

use Aws\Endpoint\Partition;
use Aws\Endpoint\PartitionInterface;
use Aws\Endpoint\UseDualstackEndpoint;
use Aws\Endpoint\UseFipsEndpoint;
use Yoast\PHPUnitPolyfills\TestCases\TestCase;

/**
 * @covers \Aws\Endpoint\Partition
 */
class PartitionTest extends TestCase
{
    /**
     * @dataProvider partitionDefinitionProvider
     *
     * @param array $definition
     */
    public function testAcceptsValidDefinitions(array $definition)
    {
        $this->assertInstanceOf(
            PartitionInterface::class,
            new Partition($definition)
        );
    }

    /**
     * @dataProvider invalidPartitionDefinitionProvider
     *
     * @param array $invalidDefinition
     */
    public function testRejectsInvalidDefinitions(array $invalidDefinition)
    {
        $this->expectExceptionMessageMatches("/missing required \w+ field/");
        $this->expectException(\InvalidArgumentException::class);
        new Partition($invalidDefinition);
    }

    /**
     * @dataProvider partitionDefinitionProvider
     *
     * @param array $definition
     */
    public function testReportsData(array $definition)
    {
        $this->assertSame(
            $definition['partition'],
            (new Partition($definition))->getName()
        );
        $this->assertSame(
            $definition['dnsSuffix'],
            (new Partition($definition))->getDnsSuffix()
        );
    }
    /**
     * @dataProvider partitionDefinitionProvider
     *
     * @param array $definition
     */
    public function testFipsEndpoint(array $definition)
    {
        $partition = new Partition($definition);
        $resolved = $partition(['region' => 'fips-aws-global', 'service' => 'service']);
        self::assertStringContainsString('service-fips.amazonaws.com', $resolved['endpoint']);
    }

    public function partitionDefinitionProvider()
    {
        return [
            [[
                'partition' => 'aws_test',
                'dnsSuffix' => 'amazonaws.com',
                'regions' => [
                    'region' => [
                        'description' => 'A description',
                    ],
                ],
                'services' => [
                    'service' => [
                        'endpoints' => [
                            'us-east-1' => [],
                            'us-west-2' => [],
                            'fips-aws-global' => ['hostname' => 'service-fips.amazonaws.com'],
                        ],
                    ],
                ],
            ]],
        ];
    }

    public function invalidPartitionDefinitionProvider()
    {
        $validDefinition = $this->partitionDefinitionProvider()[0][0];
        $return = [];

        foreach ($validDefinition as $requiredKey => $v) {
            $def = $validDefinition;
            unset($def[$requiredKey]);

            $return []= [$def];
        }

        return $return;
    }

    /**
     * @dataProvider partitionDefinitionProvider
     *
     * @param array $definition
     */
    public function testReportsRegionMatches(array $definition)
    {
        $partition = new Partition($definition);

        $this->assertTrue($partition->isRegionMatch('region', 'service'));
        $this->assertFalse($partition->isRegionMatch('foo', 'bar'));
    }

    /**
     * @dataProvider partitionDefinitionProvider
     *
     * @param array $definition
     */
    public function testReportsRegionMatchesByPattern(array $definition)
    {
        $definition['regionRegex'] = '^fo[\w]{1}';
        $partition = new Partition($definition);

        $this->assertTrue($partition->isRegionMatch('foo', 's3'));
        $this->assertTrue($partition->isRegionMatch('fou', 's3'));
        $this->assertFalse($partition->isRegionMatch('bar', 's3'));
    }

    /**
     * @dataProvider serviceRegionsProvider
     *
     * @param Partition $partition
     * @param string $service
     * @param array $regions
     * @param bool $allowNonRegionalEndpoints
     */
    public function testEnumeratesRegionsForGivenService(
        Partition $partition,
        $service,
        array $regions,
        $allowNonRegionalEndpoints
    ) {
        $this->assertSame($regions, $partition->getAvailableEndpoints(
            $service,
            $allowNonRegionalEndpoints
        ));
    }

    public function serviceRegionsProvider()
    {
        $partition = new Partition([
            'partition' => 'foo',
            'dnsSuffix' => 'bar',
            'regions' => [
                'foo-global' => [],
                'buzz' => [],
                'pop' => [],
            ],
            'services' => [
                'baz' => [
                    'isRegionalized' => false,
                    'partitionEndpoint' => 'foo-global',
                    'endpoints' => [
                        'foo-global' => [
                            'credentialScope' => ['region' => 'quux']
                        ],
                    ],
                ],
                'fizz' => [
                    'endpoints' => [
                        'buzz' => [],
                        'pop' => [],
                        'pop-external-1-fips' => [],
                    ],
                ],
            ],
        ]);

        return [
            [$partition, 'baz', ['foo-global'], false],
            [$partition, 'fizz', ['buzz', 'pop'], false],
            [$partition, 'fizz', ['buzz', 'pop', 'pop-external-1-fips'], true],
            [$partition, 'quux', [], true],
        ];
    }

    /**
     * @dataProvider signingRegionProvider
     *
     * @param Partition $partition
     * @param $region
     * @param $service
     * @param $signingRegion
     */
    public function testDeterminesSigningRegion(
        Partition $partition,
        $region,
        $service,
        $signingRegion
    ) {
        $resolved = $partition([
            'scheme' => 'https',
            'service' => $service,
            'region' => $region,
        ]);

        $this->assertArrayHasKey('signingRegion', $resolved);
        $this->assertSame($signingRegion, $resolved['signingRegion']);
    }

    public function signingRegionProvider()
    {
        $partition = new Partition([
            'partition' => 'foo',
            'dnsSuffix' => 'bar',
            'regions' => [],
            'services' => [
                'baz' => [
                    'isRegionalized' => false,
                    'partitionEndpoint' => 'foo-global',
                    'endpoints' => [
                        'foo-global' => [
                            'credentialScope' => ['region' => 'quux']
                        ],
                    ],
                ],
                'fizz' => [
                    'endpoints' => [
                        'buzz' => [],
                    ],
                ],
            ],
        ]);

        return [
            [$partition, 'eu-central-1', 'baz', 'quux'],
            [$partition, 'eu-central-1', 'fizz', 'eu-central-1'],
            [$partition, 'us-east-1', 'iot', 'us-east-1'],
        ];
    }

    /**
     * @dataProvider endpointProvider
     *
     * @param Partition $partition
     * @param $region
     * @param $service
     * @param $endpoint
     */
    public function testDeterminesEndpoint(
        Partition $partition,
        $region,
        $service,
        $endpoint
    ) {
        $resolved = $partition([
            'scheme' => 'https',
            'service' => $service,
            'region' => $region,
        ]);

        $this->assertArrayHasKey('endpoint', $resolved);
        $this->assertSame($endpoint, $resolved['endpoint']);
    }

    public function endpointProvider()
    {
        $partition = new Partition([
            'partition' => 'foo',
            'dnsSuffix' => 'bar',
            'defaults' => ['hostname' => '{service}.{region}.{dnsSuffix}'],
            'regions' => [],
            'services' => [
                'baz' => [
                    'isRegionalized' => false,
                    'partitionEndpoint' => 'foo-global',
                    'endpoints' => [
                        'foo-global' => ['hostname' => 'quux'],
                    ],
                ],
                'fizz' => [
                    'endpoints' => [
                        'buzz' => [],
                        'pop' => [
                            'hostname' => '{region}.{service}.{dnsSuffix}',
                        ],
                    ],
                ],
            ],
        ]);

        return [
            [$partition, 'us-east-1', 'baz', 'https://quux'],
            [$partition, 'buzz', 'fizz', 'https://fizz.buzz.bar'],
            [$partition, 'pop', 'fizz', 'https://pop.fizz.bar'],
            [$partition, 'us-east-1', 'iot', 'https://iot.us-east-1.bar'],
        ];
    }

    public function testIgnoresIsRegionalizedFlagIfPartitionEndpointAbsent()
    {
        $partition = new Partition([
            'partition' => 'foo',
            'dnsSuffix' => 'bar',
            'defaults' => ['hostname' => '{service}.{region}.{dnsSuffix}'],
            'regions' => [],
            'services' => [
                'baz' => [
                    'isRegionalized' => false,
                    'endpoints' => [
                        'foo-global' => ['hostname' => 'quux'],
                    ],
                ],
            ],
        ]);

        $resolved = $partition([
            'service' => 'baz',
            'region' => 'us-east-1',
            'scheme' => 'https',
        ]);

        $this->assertArrayHasKey('endpoint', $resolved);
        $this->assertSame('https://baz.us-east-1.bar', $resolved['endpoint']);
    }

    /**
     * @dataProvider signatureVersionProvider
     *
     * @param Partition $partition
     * @param $region
     * @param $service
     * @param $signatureVersion
     */
    public function testDeterminesSignatureVersion(
        Partition $partition,
        $region,
        $service,
        $signatureVersion
    ) {
        $resolved = $partition([
            'scheme' => 'https',
            'service' => $service,
            'region' => $region,
        ]);

        $this->assertArrayHasKey('signatureVersion', $resolved);
        $this->assertSame($signatureVersion, $resolved['signatureVersion']);
    }

    public function signatureVersionProvider()
    {
        $partition = new Partition([
            'partition' => 'foo',
            'dnsSuffix' => 'bar',
            'defaults' => ['signatureVersions' => ['v4']],
            'regions' => [],
            'services' => [
                'baz' => [
                    'isRegionalized' => false,
                    'partitionEndpoint' => 'foo-global',
                    'endpoints' => [
                        'foo-global' => ['signatureVersions' => ['s3v4']],
                    ],
                ],
                'fizz' => [
                    'defaults' => ['signatureVersions' => ['anonymous']],
                    'endpoints' => [
                        'buzz' => [],
                        'pop' => [
                            'signatureVersions' => ['s3v4'],
                        ],
                    ],
                ],
                'quux' => [
                    'endpoints' => [
                        'puff' => [],
                    ],
                ],
                'sdb' => [
                    'defaults' => ['signatureVersions' => ['v2']],
                    'endpoints' => [
                        'us-east-1' => [],
                    ]
                ]
            ],
        ]);

        return [
            // partition endpoint setting
            [$partition, 'us-east-1', 'baz', 's3v4'],
            // service setting
            [$partition, 'buzz', 'fizz', 'anonymous'],
            // service endpoint setting
            [$partition, 'pop', 'fizz', 's3v4'],
            // no overrides
            [$partition, 'puff', 'quux', 'v4'],
            // unknown region
            [$partition, 'us-east-1', 'quux', 'v4'],
            // unknown service
            [$partition, 'us-east-1', 'iot', 'v4'],
            // sdb
            [$partition, 'us-east-1', 'sdb', null]
        ];
    }

    /**
     * @dataProvider signingNameProvider
     *
     * @param Partition $partition
     * @param string $region
     * @param string $service
     * @param string $signingName
     */
    public function testDeterminesSigningName(
        Partition $partition,
        $region,
        $service,
        $signingName
    ) {
        $resolved = $partition([
            'scheme' => 'https',
            'service' => $service,
            'region' => $region,
        ]);

        $this->assertArrayHasKey('signingName', $resolved);
        $this->assertSame($signingName, $resolved['signingName']);
    }

    public function signingNameProvider()
    {
        $partition = new Partition([
            'partition' => 'foo',
            'dnsSuffix' => 'bar',
            'regions' => [],
            'services' => [
                'baz' => [
                    'isRegionalized' => false,
                    'partitionEndpoint' => 'foo-global',
                    'endpoints' => [
                        'foo-global' => [
                            'credentialScope' => ['service' => 'quux']
                        ],
                    ],
                ],
                'fizz' => [
                    'defaults' => [
                        'credentialScope' => ['service' => 'execute-api'],
                    ],
                    'endpoints' => [
                        'buzz' => [
                            'credentialScope' => ['service' => 'pop'],
                        ],
                    ],
                ],
                'quux' => [
                    'endpoints' => [
                        'puff' => [],
                    ],
                ],
            ],
        ]);

        return [
            // partition endpoint setting
            [$partition, 'eu-central-1', 'baz', 'quux'],
            // service setting
            [$partition, 'eu-central-1', 'fizz', 'execute-api'],
            // service endpoint setting
            [$partition, 'buzz', 'fizz', 'pop'],
            // no overrides
            [$partition, 'puff', 'quux', 'quux'],
            // unknown service
            [$partition, 'us-east-2', 's3', 's3'],
        ];
    }

    /**
     * @dataProvider stsEndpointTestCases
     *
     * @param $region
     * @param $configOption
     * @param $expectedEndpoint
     */
    public function testResolvesStsRegionalEndpoints(
        $region,
        $configOption,
        $expectedEndpoint
    ) {
        $data = json_decode(
            file_get_contents(__DIR__ . '/fixtures/sts_regional_endpoints.json'),
            true
        );
        $partition = new Partition($data['partitions'][0]);

        $params = [
            'service' => 'sts',
            'region' => $region
        ];
        if (!empty($configOption)) {
            $params['options'] = [
                'sts_regional_endpoints' => $configOption
            ];
        }

        $data = $partition($params);
        $this->assertEquals($expectedEndpoint, $data['endpoint']);

    }

    public function stsEndpointTestCases()
    {
        return [
            [
                'us-west-2',
                'legacy',
                'https://sts.amazonaws.com'
            ],
            [
                'us-west-2',
                'regional',
                'https://sts.us-west-2.amazonaws.com'
            ],
            [
                'us-west-2',
                null,
                'https://sts.amazonaws.com'
            ],
            [
                'us-west-2-fips',
                'legacy',
                'https://sts-fips.us-west-2.amazonaws.com'
            ],
            [
                'us-west-2-fips',
                'regional',
                'https://sts-fips.us-west-2.amazonaws.com'
            ],
            [
                'us-west-2-fips',
                null,
                'https://sts-fips.us-west-2.amazonaws.com'
            ],
            [
                'ap-east-1',
                'legacy',
                'https://sts.ap-east-1.amazonaws.com'
            ],
            [
                'ap-east-1',
                'regional',
                'https://sts.ap-east-1.amazonaws.com'
            ],
            [
                'ap-east-1',
                null,
                'https://sts.ap-east-1.amazonaws.com'
            ],
            [
                'aws-global',
                'legacy',
                'https://sts.amazonaws.com'
            ],
            [
                'aws-global',
                'regional',
                'https://sts.amazonaws.com'
            ],
            [
                'aws-global',
                null,
                'https://sts.amazonaws.com'
            ],
        ];
    }

    /**
     * @dataProvider s3EndpointTestCases
     *
     * @param $region
     * @param $configOption
     * @param $expectedEndpoint
     */
    public function testResolvesS3RegionalEndpoint(
        $region,
        $configOption,
        $expectedEndpoint
    ) {
        $data = json_decode(
            file_get_contents(__DIR__ . '/fixtures/s3_us_east_1_regional_endpoint.json'),
            true
        );
        $partition = new Partition($data['partitions'][0]);

        $params = [
            'service' => 's3',
            'region' => $region
        ];
        if (!empty($configOption)) {
            $params['options'] = [
                's3_us_east_1_regional_endpoint' => $configOption
            ];
        }

        $data = $partition($params);
        $this->assertEquals($expectedEndpoint, $data['endpoint']);

    }

    public function s3EndpointTestCases()
    {
        return [
            [
                'us-west-2',
                'legacy',
                'https://s3.us-west-2.amazonaws.com'
            ],
            [
                'us-west-2',
                'regional',
                'https://s3.us-west-2.amazonaws.com'
            ],
            [
                'us-west-2',
                null,
                'https://s3.us-west-2.amazonaws.com'
            ],
            [
                'us-east-1',
                'legacy',
                'https://s3.amazonaws.com'
            ],
            [
                'us-east-1',
                'regional',
                'https://s3.us-east-1.amazonaws.com'
            ],
            [
                'us-east-1',
                null,
                'https://s3.amazonaws.com'
            ],
            [
                'aws-global',
                'legacy',
                'https://s3.amazonaws.com'
            ],
            [
                'aws-global',
                'regional',
                'https://s3.amazonaws.com'
            ],
            [
                'aws-global',
                null,
                'https://s3.amazonaws.com'
            ],
        ];
    }

    /**
     * @dataProvider variantTagProvider
     *
     * @param array $definition
     * @param @fipsConfig
     * @param @dualstackConfig
     */
    public function testGetVariantIgnoresVariantTagOrder(
        array $definition,
        $fipsConfig,
        $dualstackConfig
    )
    {
        $partition = new Partition($definition);
        $resolved = $partition([
            'region' => 'us-east-1',
            'service' => 'service',
            'options' => [
                'use_fips_endpoint' => $fipsConfig,
                'use_dual_stack_endpoint' => $dualstackConfig
            ]
        ]);

        $this->assertStringContainsString('testsuffix.com', $resolved['endpoint']);
    }

    public function variantTagProvider()
    {
        $useFipsEndpointConfig = $this->getMockBuilder(UseFipsEndpoint\Configuration::class)
            ->disableOriginalConstructor()
            ->getMock();
        $useFipsEndpointConfig->expects($this->any())
            ->method('isUseFipsEndpoint')
            ->willReturn(true);

        $useDualstackEndpointConfig = $this->getMockBuilder(UseDualstackEndpoint\Configuration::class)
            ->disableOriginalConstructor()
            ->getMock();
        $useDualstackEndpointConfig->expects($this->any())
            ->method('isUseDualstackEndpoint')
            ->willReturn(true);

        return [
            [
                [
                    'partition' => 'aws_test',
                    'dnsSuffix' => 'amazonaws.com',
                    'regions' => [
                        'region' => [
                            'description' => 'A description',
                        ],
                    ],
                    'services' => [
                        'service' => [
                            'endpoints' => [
                                'us-east-1' => [
                                    'variants' => [[
                                        'hostname' => 'service-fips.dualstack.testsuffix.com',
                                        'tags' => ['fips', 'dualstack']
                                    ]]
                                ],
                                'us-west-2' => [],
                            ],
                        ],
                    ],
                ],
                $useFipsEndpointConfig,
                $useDualstackEndpointConfig
            ],
            [
                [
                    'partition' => 'aws_test',
                    'dnsSuffix' => 'amazonaws.com',
                    'regions' => [
                        'region' => [
                            'description' => 'A description',
                        ],
                    ],
                    'services' => [
                        'service' => [
                            'endpoints' => [
                                'us-east-1' => [
                                    'variants' => [[
                                        'hostname' => 'service-fips.dualstack.testsuffix.com',
                                        'tags' => ['dualstack', 'fips']
                                    ]]
                                ],
                                'us-west-2' => [],
                            ],
                        ],
                    ],
                ],
                $useFipsEndpointConfig,
                $useDualstackEndpointConfig
            ],
            [
                [
                    'partition' => 'aws_test',
                    'dnsSuffix' => 'amazonaws.com',
                    'regions' => [
                        'region' => [
                            'description' => 'A description',
                        ],
                    ],
                    'services' => [
                        'service' => [
                            'endpoints' => [
                                'us-east-1' => [
                                    'variants' => [[
                                        'hostname' => 'service-fips.dualstack.testsuffix.com',
                                        'tags' => ['fips']
                                    ]]
                                ],
                                'us-west-2' => [],
                            ],
                        ],
                    ],
                ],
                $useFipsEndpointConfig,
                null
            ],
            [
                [
                    'partition' => 'aws_test',
                    'dnsSuffix' => 'amazonaws.com',
                    'regions' => [
                        'region' => [
                            'description' => 'A description',
                        ],
                    ],
                    'services' => [
                        'service' => [
                            'endpoints' => [
                                'us-east-1' => [
                                    'variants' => [[
                                        'hostname' => 'service-fips.dualstack.testsuffix.com',
                                        'tags' => ['dualstack']
                                    ]]
                                ],
                                'us-west-2' => [],
                            ],
                        ],
                    ],
                ],
                null,
                $useDualstackEndpointConfig
            ]
        ];
    }

    /**
     * @dataProvider variantTagEmptyProvider
     *
     * @param array $definition
     * @param @fipsConfig
     * @param @dualstackConfig
     */
    public function testGetVariantNoVariantSelectedIfTagsAreEmpty(
        array $definition,
        $fipsConfig,
        $dualstackConfig
    )
    {
        $partition = new Partition($definition);
        $resolved = $partition([
            'region' => 'us-east-1',
            'service' => 'service',
            'options' => [
                'use_fips_endpoint' => $fipsConfig,
                'use_dual_stack_endpoint' => $dualstackConfig
            ]
        ]);

        $this->assertStringNotContainsString('testsuffix.com', $resolved['endpoint']);
    }

    public function variantTagEmptyProvider()
    {
        $useFipsEndpointConfig = $this->getMockBuilder(UseFipsEndpoint\Configuration::class)
            ->disableOriginalConstructor()
            ->getMock();
        $useFipsEndpointConfig->expects($this->any())
            ->method('isUseFipsEndpoint')
            ->willReturn(true);

        $useDualstackEndpointConfig = $this->getMockBuilder(UseDualstackEndpoint\Configuration::class)
            ->disableOriginalConstructor()
            ->getMock();
        $useDualstackEndpointConfig->expects($this->any())
            ->method('isUseDualstackEndpoint')
            ->willReturn(true);

        return [
            [
                [
                    'partition' => 'aws_test',
                    'dnsSuffix' => 'amazonaws.com',
                    'regions' => [
                        'region' => [
                            'description' => 'A description',
                        ],
                    ],
                    'services' => [
                        'service' => [
                            'endpoints' => [
                                'us-east-1' => [
                                    'variants' => [[
                                        'hostname' => 'service-fips.dualstack.testsuffix.com',
                                        'tags' => []
                                    ]]
                                ],
                                'us-west-2' => [],
                            ],
                        ],
                    ],
                ],
                $useFipsEndpointConfig,
                $useDualstackEndpointConfig
            ],
            [
                [
                    'partition' => 'aws_test',
                    'dnsSuffix' => 'amazonaws.com',
                    'regions' => [
                        'region' => [
                            'description' => 'A description',
                        ],
                    ],
                    'services' => [
                        'service' => [
                            'endpoints' => [
                                'us-east-1' => [
                                    'variants' => [[
                                        'hostname' => 'service-fips.dualstack.testsuffix.com',
                                        'tags' => []
                                    ]]
                                ],
                                'us-west-2' => [],
                            ],
                        ],
                    ],
                ],
                $useFipsEndpointConfig,
                null
            ],
            [
                [
                    'partition' => 'aws_test',
                    'dnsSuffix' => 'amazonaws.com',
                    'regions' => [
                        'region' => [
                            'description' => 'A description',
                        ],
                    ],
                    'services' => [
                        'service' => [
                            'endpoints' => [
                                'us-east-1' => [
                                    'variants' => [[
                                        'hostname' => 'service-fips.dualstack.testsuffix.com',
                                        'tags' => []
                                    ]]
                                ],
                                'us-west-2' => [],
                            ],
                        ],
                    ],
                ],
                null,
                $useDualstackEndpointConfig
            ],
            [
                [
                    'partition' => 'aws_test',
                    'dnsSuffix' => 'amazonaws.com',
                    'regions' => [
                        'region' => [
                            'description' => 'A description',
                        ],
                    ],
                    'services' => [
                        'service' => [
                            'endpoints' => [
                                'us-east-1' => [
                                    'variants' => [[
                                        'hostname' => 'service-fips.dualstack.testsuffix.com',
                                        'tags' => []
                                    ]]
                                ],
                                'us-west-2' => [],
                            ],
                        ],
                    ],
                ],
                null,
                null
            ]
        ];
    }
}


text:
from django.contrib import admin

from activity_monitor.models import Activity

class ActivityAdmin(admin.ModelAdmin):
    list_display = ('__unicode__', 'actor', 'content_type', 'timestamp')

admin.site.register(Activity, ActivityAdmin)

redpajama_set_name: RedPajamaGithub


text:
App.notify = function(title, options) {
    var _notify = function() {
        new Notification(title, options);
    };
    var Notification = window.Notification || window.mozNotification || window.webkitNotification;
    if (Notification) {
        var permission = Notification.permission;
        if (permission === "granted") {
            _notify();
        }
        else if (permission !== 'denied') {
            Notification.requestPermission(function (permission) {
                if(!('permission' in Notification)) {
                    Notification.permission = permission;
                }
                if (permission === "granted") {
                    _notify();
                }
            });
        }
    }
};

App.bell = (function() {
    // setup the bell
    var audio = new Audio();
    audio.src = 'audio/bong.wav';
    audio.type = 'audio/wave';

    return {
        play: function() {
            audio.play();
        }
    };
})();

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(), 0, 1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
};

Date.prototype.getFirstWeekDay = function(){
    var now = new Date();
    var startDay = 1; // monday
    return new Date(now.valueOf() - (
        now.getDay()<=0 ? 7-startDay:now.getDay()-startDay)*86400000);
};

App.Storage = function(userkey) {
    $.parse.init({
        app_id : "8fzGpo1z0od9jzGRL73tjSycywhXjJ3QdrnRodBI",
        rest_key : "x1GySv7rY8P1eszs2C2ghMcSnmZOVLXmS2Ievjge"
    });

    var store = Ember.A([]);

    var getLocalStorage = function() {
        var store;
        try {
            store = JSON.parse(localStorage.getItem('Pomodoroland')).store;
        }
        catch (e){
            store = [];
        }
        return store;
    };

    var saveToLocalStorage = function(data) {
        localStorage.setItem('Pomodoroland', JSON.stringify({store:data}));
    };

    return {
        userkey: userkey,
        setUserKey: function(userkey) {
            this.userkey = userkey;
        },
        insert: function(type, item) {
            if (this.userkey) {
                item.userKey = App.settings.get('parseKey');
                $.parse.post(type, item);
            } else {
                var data = getLocalStorage();
                data.pushObject(item);
                saveToLocalStorage(data);
            }
        },
        find: function(type) {
            var results = Ember.A([]);
            var promise;
            if (this.userkey) {
                var userKey = App.settings.get('parseKey');
                promise = new Ember.RSVP.Promise(function(resolve) {
                    var query = {where: {userKey: userKey}, order: "-createdAt"};
                    $.parse.get(type, query, function(data){
                        data.results.forEach(function(item){
                            var obj = App[type.capitalize()].create(item);
                            results.pushObject(obj);
                        });
                        resolve(results);
                    });
                });
            } else {
                promise = new Ember.RSVP.Promise(function(resolve) {
                    Ember.run.later(function() {
                        var data = getLocalStorage();
                        data.forEach(function(item){
                            results.push(App.Pomodoro.create(item));
                        });
                        resolve(results);
                    });
                });
            }
            return promise;
        }
    };
};


text:
package org.knowm.xchange.coinegg;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.coinegg.dto.accounts.CoinEggBalance;
import org.knowm.xchange.coinegg.dto.marketdata.CoinEggOrders;
import org.knowm.xchange.coinegg.dto.marketdata.CoinEggOrders.CoinEggOrder;
import org.knowm.xchange.coinegg.dto.marketdata.CoinEggTicker;
import org.knowm.xchange.coinegg.dto.marketdata.CoinEggTrade;
import org.knowm.xchange.coinegg.dto.marketdata.CoinEggTrade.Type;
import org.knowm.xchange.coinegg.dto.trade.CoinEggTradeAdd;
import org.knowm.xchange.coinegg.dto.trade.CoinEggTradeCancel;
import org.knowm.xchange.coinegg.dto.trade.CoinEggTradeView;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.account.AccountInfo;
import org.knowm.xchange.dto.account.Balance;
import org.knowm.xchange.dto.account.Wallet;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.marketdata.Trade;
import org.knowm.xchange.dto.marketdata.Trades;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.dto.trade.UserTrades;

public class CoinEggAdapters {

  public static Ticker adaptTicker(CoinEggTicker coinEggTicker, CurrencyPair currencyPair) {
    BigDecimal last = coinEggTicker.getLast();
    BigDecimal bid = coinEggTicker.getSell();
    BigDecimal ask = coinEggTicker.getBuy();
    BigDecimal high = coinEggTicker.getHigh();
    BigDecimal low = coinEggTicker.getLow();
    BigDecimal volume = coinEggTicker.getVolume();

    Ticker ticker =
        new Ticker.Builder()
            .currencyPair(currencyPair)
            .last(last)
            .bid(bid)
            .ask(ask)
            .high(high)
            .low(low)
            .volume(volume)
            .build();

    return ticker;
  }

  public static LimitOrder adaptOrder(
      CoinEggOrder order, OrderType type, CurrencyPair currencyPair) {
    BigDecimal quantity = order.getQuantity();
    BigDecimal price = order.getPrice();

    LimitOrder limitOrder =
        new LimitOrder.Builder(type, currencyPair)
            .originalAmount(quantity)
            .limitPrice(price)
            .build();

    return limitOrder;
  }

  public static OrderBook adaptOrders(CoinEggOrders coinEggOrders, CurrencyPair currencyPair) {

    List<LimitOrder> asks =
        Stream.of(coinEggOrders.getAsks())
            .map(order -> adaptOrder(order, OrderType.ASK, currencyPair))
            .collect(Collectors.toList());

    List<LimitOrder> bids =
        Stream.of(coinEggOrders.getBids())
            .map(order -> adaptOrder(order, OrderType.BID, currencyPair))
            .collect(Collectors.toList());

    return new OrderBook(null, asks, bids);
  }

  public static Trade adaptTrade(CoinEggTrade coinEggTrade, CurrencyPair currencyPair) {
    return new Trade.Builder()
        .currencyPair(currencyPair)
        .id(String.valueOf(coinEggTrade.getTransactionID()))
        .type(coinEggTrade.getOrderType())
        .price(coinEggTrade.getPrice())
        .originalAmount(coinEggTrade.getAmount())
        .build();
  }

  public static Trades adaptTrades(CoinEggTrade[] coinEggTrades, CurrencyPair currencyPair) {
    List<Trade> trades =
        Stream.of(coinEggTrades).map(t -> adaptTrade(t, currencyPair)).collect(Collectors.toList());

    return new Trades(trades);
  }

  // TODO: Implement XAS Currency
  public static AccountInfo adaptAccountInfo(CoinEggBalance coinEggBalance, Exchange exchange) {

    String userName = exchange.getExchangeSpecification().getUserName();
    Wallet btcWallet =
        new Wallet(
            Currency.BTC.getCurrencyCode(),
            new Balance(Currency.BTC, coinEggBalance.getBTCBalance()));
    Wallet ethWallet =
        new Wallet(
            Currency.ETH.getCurrencyCode(),
            new Balance(Currency.ETH, coinEggBalance.getETHBalance()));
    // Wallet xasWallet = new Wallet(new Balance(Currency.XAS, coinEggBalance.getXASBalance()));

    Set<Wallet> wallets = new HashSet<Wallet>();
    wallets.add(btcWallet);
    wallets.add(ethWallet);
    // wallets.add(xasWallet);

    return new AccountInfo(userName, null, wallets);
  }

  // TODO: Cleanup Code
  // TODO: Make Use Of Adapt Trade
  public static UserTrades adaptTradeHistory(CoinEggTradeView coinEggTradeView) {
    List<UserTrade> trades = new ArrayList<UserTrade>();
    Trade trade =
        new Trade.Builder()
            // .currencyPair(null)
            .id(String.valueOf(coinEggTradeView.getID()))
            .type(coinEggTradeView.getType() == Type.BUY ? OrderType.ASK : OrderType.BID)
            .price(coinEggTradeView.getPrice())
            .originalAmount(coinEggTradeView.getAmountOriginal())
            .timestamp(coinEggTradeView.getDateTime())
            .build();

    trades.add((UserTrade) UserTrade.Builder.from(trade).build());

    return new UserTrades(trades, null);
  }

  public static String adaptTradeAdd(CoinEggTradeAdd coinEggTradeAdd) {
    return String.valueOf(coinEggTradeAdd.getID());
  }

  public static boolean adaptTradeCancel(CoinEggTradeCancel coinEggTradeCancel) {
    return coinEggTradeCancel.getResult();
  }
}


text:
import styles from './TabLinks.css';

import React from 'react';
import ActiveContainer from '../../containers/Active/Active';

const TabLinks = () => {
    return (
        <ul className={styles.root}>
            <ActiveContainer chart="scatterplot" />
            <ActiveContainer chart="map" />
        </ul>
    )
}

export default TabLinks;


text:
/*
 * tlpi_hdr.h
 *
 *  Created on: Oct 31, 2014
 *      Author: mam1
 */

#ifndef TLPI_HDR_H_
#define TLPI_HDR_H_

#include <sys/types.h>  /* Type definitions used by many programs */
#include <stdio.h>      /* Standard I/O functions */
#include <stdlib.h>     /* Prototypes of commonly used library functions,
                           plus EXIT_SUCCESS and EXIT_FAILURE constants */
#include <unistd.h>     /* Prototypes for many system calls */
#include <errno.h>      /* Declares errno and defines error constants */
#include <string.h>     /* Commonly used string-handling functions */

#include "get_num.h"    /* Declares our functions for handling numeric
                           arguments (getInt(), getLong()) */

#include "error_functions.h"  /* Declares our error-handling functions */

/* Unfortunately some UNIX implementations define FALSE and TRUE -
 here we'll undefine them */

#ifdef TRUE
#undef TRUE
#endif

#ifdef FALSE
#undef FALSE
#endif

typedef enum {
	FALSE, TRUE
} Boolean;

#define min(m,n) ((m) < (n) ? (m) : (n))
#define max(m,n) ((m) > (n) ? (m) : (n))

/* Some systems don't define 'socklen_t' */

#if defined(__sgi)
typedef int socklen_t;
#endif

/* The remainder of this file creates various definitions to help
 the example programs run on UNIX implementations other than Linux. */

#include "alt_functions.h"      /* Declares simple replacements for some
                                   functions that are absent on other systems */

#if defined(__sun)
#include <sys/file.h>           /* Has definition of FASYNC */
#endif

#if ! defined(O_ASYNC) && defined(FASYNC)
/* Some systems define FASYNC instead of O_ASYNC */
#define O_ASYNC FASYNC
#endif

#if defined(MAP_ANON) && ! defined(MAP_ANONYMOUS)
/* BSD derivatives usually have MAP_ANON, not MAP_ANONYMOUS */
#define MAP_ANONYMOUS MAP_ANON

#endif

#if ! defined(O_SYNC) && defined(O_FSYNC)
/* Some implementations have O_FSYNC instead of O_SYNC */
#define O_SYNC O_FSYNC
#endif

#if defined(__FreeBSD__)

/* FreeBSD uses these alternate names for fields in the sigval structure */

#define sival_int sigval_int
#define sival_ptr sigval_ptr
#endif

#endif /* TLPI_HDR_H_ */


text:
package com.amazonaws.services.elasticmapreduce.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *

 * The input argument to the AddJobFlowSteps operation.
 *

 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AddJobFlowStepsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * A string that uniquely identifies the job flow. This identifier is returned by RunJobFlow and can also be
     * obtained from ListClusters.
     *

     */
    private String jobFlowId;
    /**
     *

     * A list of StepConfig to be executed by the job flow.
     *

     */
    private com.amazonaws.internal.SdkInternalList<StepConfig> steps;

    /**
     * Default constructor for AddJobFlowStepsRequest object. Callers should use the setter or fluent setter (with...)
     * methods to initialize the object after creating it.
     */
    public AddJobFlowStepsRequest() {
    }

    /**
     * Constructs a new AddJobFlowStepsRequest object. Callers should use the setter or fluent setter (with...) methods
     * to initialize any additional object members.
     *
     * @param jobFlowId
     *        A string that uniquely identifies the job flow. This identifier is returned by RunJobFlow and can
     *        also be obtained from ListClusters.
     */
    public AddJobFlowStepsRequest(String jobFlowId) {
        setJobFlowId(jobFlowId);
    }

    /**
     * Constructs a new AddJobFlowStepsRequest object. Callers should use the setter or fluent setter (with...) methods
     * to initialize any additional object members.
     *
     * @param jobFlowId
     *        A string that uniquely identifies the job flow. This identifier is returned by RunJobFlow and can
     *        also be obtained from ListClusters.
     * @param steps
     *        A list of StepConfig to be executed by the job flow.
     */
    public AddJobFlowStepsRequest(String jobFlowId, java.util.List<StepConfig> steps) {
        setJobFlowId(jobFlowId);
        setSteps(steps);
    }

    /**
     *

     * A string that uniquely identifies the job flow. This identifier is returned by RunJobFlow and can also be
     * obtained from ListClusters.
     *

     *
     * @param jobFlowId
     *        A string that uniquely identifies the job flow. This identifier is returned by RunJobFlow and can
     *        also be obtained from ListClusters.
     */

    public void setJobFlowId(String jobFlowId) {
        this.jobFlowId = jobFlowId;
    }

    /**
     *

     * A string that uniquely identifies the job flow. This identifier is returned by RunJobFlow and can also be
     * obtained from ListClusters.
     *

     *
     * @return A string that uniquely identifies the job flow. This identifier is returned by RunJobFlow and can
     *         also be obtained from ListClusters.
     */

    public String getJobFlowId() {
        return this.jobFlowId;
    }

    /**
     *

     * A string that uniquely identifies the job flow. This identifier is returned by RunJobFlow and can also be
     * obtained from ListClusters.
     *

     *
     * @param jobFlowId
     *        A string that uniquely identifies the job flow. This identifier is returned by RunJobFlow and can
     *        also be obtained from ListClusters.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AddJobFlowStepsRequest withJobFlowId(String jobFlowId) {
        setJobFlowId(jobFlowId);
        return this;
    }

    /**
     *

     * A list of StepConfig to be executed by the job flow.
     *

     *
     * @return A list of StepConfig to be executed by the job flow.
     */

    public java.util.List<StepConfig> getSteps() {
        if (steps == null) {
            steps = new com.amazonaws.internal.SdkInternalList<StepConfig>();
        }
        return steps;
    }

    /**
     *

     * A list of StepConfig to be executed by the job flow.
     *

     *
     * @param steps
     *        A list of StepConfig to be executed by the job flow.
     */

    public void setSteps(java.util.Collection<StepConfig> steps) {
        if (steps == null) {
            this.steps = null;
            return;
        }

        this.steps = new com.amazonaws.internal.SdkInternalList<StepConfig>(steps);
    }

    /**
     *

     * A list of StepConfig to be executed by the job flow.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setSteps(java.util.Collection)} or {@link #withSteps(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param steps
     *        A list of StepConfig to be executed by the job flow.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AddJobFlowStepsRequest withSteps(StepConfig... steps) {
        if (this.steps == null) {
            setSteps(new com.amazonaws.internal.SdkInternalList<StepConfig>(steps.length));
        }
        for (StepConfig ele : steps) {
            this.steps.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of StepConfig to be executed by the job flow.
     *

     *
     * @param steps
     *        A list of StepConfig to be executed by the job flow.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AddJobFlowStepsRequest withSteps(java.util.Collection<StepConfig> steps) {
        setSteps(steps);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getJobFlowId() != null)
            sb.append("JobFlowId: ").append(getJobFlowId()).append(",");
        if (getSteps() != null)
            sb.append("Steps: ").append(getSteps());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof AddJobFlowStepsRequest == false)
            return false;
        AddJobFlowStepsRequest other = (AddJobFlowStepsRequest) obj;
        if (other.getJobFlowId() == null ^ this.getJobFlowId() == null)
            return false;
        if (other.getJobFlowId() != null && other.getJobFlowId().equals(this.getJobFlowId()) == false)
            return false;
        if (other.getSteps() == null ^ this.getSteps() == null)
            return false;
        if (other.getSteps() != null && other.getSteps().equals(this.getSteps()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getJobFlowId() == null) ? 0 : getJobFlowId().hashCode());
        hashCode = prime * hashCode + ((getSteps() == null) ? 0 : getSteps().hashCode());
        return hashCode;
    }

    @Override
    public AddJobFlowStepsRequest clone() {
        return (AddJobFlowStepsRequest) super.clone();
    }

}


text:
namespace clang {
  class ASTContext;
  class Sema;
  class Stmt;

namespace arcmt {

class CapturedDiagList {
  typedef std::list<StoredDiagnostic> ListTy;
  ListTy List;

public:
  void push_back(const StoredDiagnostic &diag) { List.push_back(diag); }

  bool clearDiagnostic(ArrayRef<unsigned> IDs, SourceRange range);
  bool hasDiagnostic(ArrayRef<unsigned> IDs, SourceRange range) const;

  void reportDiagnostics(DiagnosticsEngine &diags) const;

  bool hasErrors() const;

  typedef ListTy::const_iterator iterator;
  iterator begin() const { return List.begin(); }
  iterator end()   const { return List.end();   }
};

void writeARCDiagsToPlist(const std::string &outPath,
                          ArrayRef<StoredDiagnostic> diags,
                          SourceManager &SM, const LangOptions &LangOpts);

class TransformActions {
  DiagnosticsEngine &Diags;
  CapturedDiagList &CapturedDiags;
  void *Impl; // TransformActionsImpl.

public:
  TransformActions(DiagnosticsEngine &diag, CapturedDiagList &capturedDiags,
                   ASTContext &ctx, Preprocessor &PP);
  ~TransformActions();

  void startTransaction();
  bool commitTransaction();
  void abortTransaction();

  void insert(SourceLocation loc, StringRef text);
  void insertAfterToken(SourceLocation loc, StringRef text);
  void remove(SourceRange range);
  void removeStmt(Stmt *S);
  void replace(SourceRange range, StringRef text);
  void replace(SourceRange range, SourceRange replacementRange);
  void replaceStmt(Stmt *S, StringRef text);
  void replaceText(SourceLocation loc, StringRef text,
                   StringRef replacementText);
  void increaseIndentation(SourceRange range,
                           SourceLocation parentIndent);

  bool clearDiagnostic(ArrayRef<unsigned> IDs, SourceRange range);
  bool clearAllDiagnostics(SourceRange range) {
    return clearDiagnostic(None, range);
  }
  bool clearDiagnostic(unsigned ID1, unsigned ID2, SourceRange range) {
    unsigned IDs[] = { ID1, ID2 };
    return clearDiagnostic(IDs, range);
  }
  bool clearDiagnostic(unsigned ID1, unsigned ID2, unsigned ID3,
                       SourceRange range) {
    unsigned IDs[] = { ID1, ID2, ID3 };
    return clearDiagnostic(IDs, range);
  }

  bool hasDiagnostic(unsigned ID, SourceRange range) {
    return CapturedDiags.hasDiagnostic(ID, range);
  }

  bool hasDiagnostic(unsigned ID1, unsigned ID2, SourceRange range) {
    unsigned IDs[] = { ID1, ID2 };
    return CapturedDiags.hasDiagnostic(IDs, range);
  }

  DiagnosticBuilder report(SourceLocation loc, unsigned diagId,
                           SourceRange range = SourceRange());
  void reportError(StringRef error, SourceLocation loc,
                   SourceRange range = SourceRange());
  void reportWarning(StringRef warning, SourceLocation loc,
                   SourceRange range = SourceRange());
  void reportNote(StringRef note, SourceLocation loc,
                  SourceRange range = SourceRange());

  bool hasReportedErrors() const {
    return Diags.hasUnrecoverableErrorOccurred();
  }

  class RewriteReceiver {
  public:
    virtual ~RewriteReceiver();

    virtual void insert(SourceLocation loc, StringRef text) = 0;
    virtual void remove(CharSourceRange range) = 0;
    virtual void increaseIndentation(CharSourceRange range,
                                     SourceLocation parentIndent) = 0;
  };

  void applyRewrites(RewriteReceiver &receiver);
};

class Transaction {
  TransformActions &TA;
  bool Aborted;

public:
  Transaction(TransformActions &TA) : TA(TA), Aborted(false) {
    TA.startTransaction();
  }

  ~Transaction() {
    if (!isAborted())
      TA.commitTransaction();
  }

  void abort() {
    TA.abortTransaction();
    Aborted = true;
  }

  bool isAborted() const { return Aborted; }
};

class MigrationPass {
public:
  ASTContext &Ctx;
  LangOptions::GCMode OrigGCMode;
  MigratorOptions MigOptions;
  Sema &SemaRef;
  TransformActions &TA;
  const CapturedDiagList &CapturedDiags;
  std::vector<SourceLocation> &ARCMTMacroLocs;
  Optional<bool> EnableCFBridgeFns;

  MigrationPass(ASTContext &Ctx, LangOptions::GCMode OrigGCMode,
                Sema &sema, TransformActions &TA,
                const CapturedDiagList &capturedDiags,
                std::vector<SourceLocation> &ARCMTMacroLocs)
    : Ctx(Ctx), OrigGCMode(OrigGCMode), MigOptions(),
      SemaRef(sema), TA(TA), CapturedDiags(capturedDiags),
      ARCMTMacroLocs(ARCMTMacroLocs) { }

  const CapturedDiagList &getDiags() const { return CapturedDiags; }

  bool isGCMigration() const { return OrigGCMode != LangOptions::NonGC; }
  bool noFinalizeRemoval() const { return MigOptions.NoFinalizeRemoval; }
  void setNoFinalizeRemoval(bool val) {MigOptions.NoFinalizeRemoval = val; }

  bool CFBridgingFunctionsDefined();
};

static inline StringRef getARCMTMacroName() {
  return "__IMPL_ARCMT_REMOVED_EXPR__";
}

} // end namespace arcmt

} // end namespace clang

#endif


text:
-- phpMyAdmin SQL Dump
-- version 4.4.10
-- http://www.phpmyadmin.net
--
-- Host: localhost:8889
-- Generation Time: Oct 13, 2016 at 06:32 PM
-- Server version: 5.5.42
-- PHP Version: 5.6.10

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `robotCalendar`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_requests`
--

CREATE TABLE `tbl_requests` (
  `id` int(11) NOT NULL,
  `requestor` varchar(500) NOT NULL,
  `email` varchar(100) NOT NULL,
  `gradeLevel` varchar(2) NOT NULL,
  `district` varchar(250) NOT NULL,
  `start_date` datetime NOT NULL,
  `end_date` datetime NOT NULL,
  `robotID` int(11) NOT NULL,
  `approved` tinyint(4) NOT NULL COMMENT 'boolean - if the event is approved or not.'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `tbl_robots`
--

CREATE TABLE `tbl_robots` (
  `ID` int(11) NOT NULL,
  `title` varchar(250) NOT NULL,
  `description` varchar(1000) NOT NULL,
  `color` varchar(7) NOT NULL COMMENT 'hex code for the color'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `tbl_users`
--

CREATE TABLE `tbl_users` (
  `id` int(11) NOT NULL,
  `username` varchar(100) NOT NULL,
  `password` varchar(50) NOT NULL,
  `name` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_requests`
--
ALTER TABLE `tbl_requests`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `tbl_robots`
--
ALTER TABLE `tbl_robots`
  ADD PRIMARY KEY (`ID`);

--
-- Indexes for table `tbl_users`
--
ALTER TABLE `tbl_users`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_requests`
--
ALTER TABLE `tbl_requests`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `tbl_robots`
--
ALTER TABLE `tbl_robots`
  MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `tbl_users`
--
ALTER TABLE `tbl_users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
<?php
namespace SPHERE\Common\Window;

use MOC\V\Component\Template\Component\IBridgeInterface;
use SPHERE\Common\Frontend\ITemplateInterface;
use SPHERE\Common\Frontend\Link\ILinkInterface;
use SPHERE\Common\Frontend\Text\Repository\Muted;
use SPHERE\System\Extension\Extension;

/**
 * Class Stage
 *
 * @package SPHERE\Common\Window
 */
class Stage extends Extension implements ITemplateInterface
{

    /** @var IBridgeInterface $Template */
    private $Template = null;

    /** @var string $Title */
    private $Title = '';
    /** @var string $Description */
    private $Description = '';
    /** @var string $Message */
    private $Message = '';
    /** @var string $Content */
    private $Content = '';
    /** @var array $Menu */
    private $Menu = array();

    /**
     * @param null|string $Title
     * @param null|string $Description
     */
    function __construct($Title = null, $Description = null)
    {

        $this->Template = $this->getTemplate(__DIR__.'/Stage.twig');
        if (null !== $Title) {
            $this->setTitle($Title);
        }
        if (null !== $Description) {
            $this->setDescription($Description);
        }
    }

    /**
     * @param string $Value
     *
     * @return Stage
     */
    public function setTitle($Value)
    {

        $this->Title = $Value;
        return $this;
    }

    /**
     * @param string $Value
     *
     * @return Stage
     */
    public function setDescription($Value)
    {

        $this->Description = $Value;
        return $this;
    }

    /**
     * @param string $Message
     *
     * @return Stage
     */
    public function setMessage($Message)
    {

        $this->Message = new Muted($Message);
        return $this;
    }

    /**
     * @param ILinkInterface $Button
     *
     * @return Stage
     */
    public function addButton(ILinkInterface $Button)
    {

        $this->Menu[] = $Button->__toString();
        return $this;
    }

    /**
     * @return string
     */
    public function __toString()
    {

        return $this->getContent();
    }

    /**
     * @return string
     */
    public function getContent()
    {

        $this->Template->setVariable('StageTitle', $this->Title);
        $this->Template->setVariable('StageDescription', $this->Description);
        $this->Template->setVariable('StageMessage', $this->Message);
        $this->Template->setVariable('StageContent', $this->Content);
        $this->Template->setVariable('StageMenu', $this->Menu);

        return $this->Template->getContent();
    }

    /**
     * @param string $Content
     *
     * @return Stage
     */
    public function setContent($Content)
    {

        $this->Content = $Content;
        return $this;
    }
}


text:
module.exports = Backbone.Model.extend({
  initialize: function ( bucket, sizeLimit ) {
    this.bucket    = bucket;
    this.sizeLimit = sizeLimit;

    // Populate/create initial cache bucket
    var cache  = localStorage.getItem( 'cache_' + bucket );

    // Likewise with internal added array (keeps track of when items were added
    // to the cache)
    var added  = localStorage.getItem( 'cache_added_' + bucket );

    try {
      this.cache = JSON.parse( cache );
    } catch ( err ) {
      console.error( 'Error parsing cache bucket: ', err );
    }

    try {
      this.cacheAdded = JSON.parse( added );
    } catch ( err ) {
      console.error( 'Error parsing cache added array: ', err );
    }

    // If it doesn't exist, create a blank object (but don't bother storing it
    // yet until something is actually pushed to it)
    if ( ! this.cache ) { this.cache = {}; }
    if ( ! this.cacheAdded ) { this.cacheAdded = []; }
  },

  /**
   * Retrieve the entire bucket.
   *
   * @return {Object} Returns the entire cache bucket
   */
  getAll: function () {
    return this.cache;
  },

  /**
   * Attempt to retrieve a value from the bucket based on a specific key.
   *
   * @param {String} key Key to search cache for
   *
   * @return {Mixed} Returns cached value if found or null
   */
  getValue: function ( key ) {
    return this.cache[ key ];
  },

  /**
   * Set a new cache value based on a specific key and persist it to local
   * storage.
   *
   * @param {String} key   Key to set new value under
   * @param {Mixed} value Value to set with key
   */
  setValue: function ( key, value ) {
    // First thing, check if there's room in the cache.  If there's not, remove
    // the oldest item added to make room, then proceed.
    this.clearCacheSpace();

    // Then move on to adding this item
    this.cache[ key ] = value;
    this.cacheAdded.push( key );

    // Then save the current cache
    this.saveCache();
  },

  /**
   * Replace the current contents of the cache with passed contents (as opposed
   * to setting only a single key with setValue).
   *
   * @param {Mixed} contents Contents to set cache to
   */
  setCache: function ( contents ) {
    this.cache = contents;

    this.saveCache();
  },

  /**
   * Save the current cache contents (persist the contents to localStorage).
   */
  saveCache: function () {
    try {
      var update = JSON.stringify( this.cache );

      // Save the current version of the cache
      localStorage.setItem( 'cache_' + this.bucket, update );

      // Update the added array as well (but only if adding the actual item
      // works)
      try {
        var addedUpdate = JSON.stringify( this.cacheAdded );

        localStorage.setItem( 'cache_added_' + this.bucket, addedUpdate );
      } catch ( err ) {
        console.error( 'Unable to save cache added array: ', err );
      }
    } catch ( err ) {
      console.error( 'Unable to save cache bucket: ', err );
    }
  },

  /**
   * Make sure localStorage is not full and clear junk out if it is.  Will
   * remove oldest added item if necessary to make room for new incoming item.
   */
  clearCacheSpace: function () {
    // The default for this is based on the fact that localStorage stores
    // approximately 2.5 million UTF-16 characters.
    var sizeLimit = this.sizeLimit || 2500000;

    // First check the cache size.
    var used = ( JSON.stringify( localStorage ).length / sizeLimit );

    if ( used >= 1 ) {
      // Blam the oldest item in the added queue.
      var key = this.cacheAdded.shift();

      if ( key ) {
        delete this.cache[ key ];

        // And save the updated cache
        this.saveCache();
      }
    }
  },

  /**
   * Flush the cache completely.  Kills both the cache itself as well as the
   * added array.
   */
  flush: function () {
    localStorage.removeItem( 'cache_' + this.bucket );
    localStorage.removeItem( 'cache_added_' + this.bucket );
  }
});


text:
package kubeconfig

import (
	"k8s.io/client-go/rest"
	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)

// CreateKubeConfig converts a [rest.Config] into a [clientcmdapi.Config]
// which then can be written to a file with [clientcmd.WriteToFile].
func CreateKubeConfig(clientCfg *rest.Config) *clientcmdapi.Config {
	clusterNick := "cluster"
	userNick := "user"
	contextNick := "context"

	config := clientcmdapi.NewConfig()

	credentials := clientcmdapi.NewAuthInfo()
	credentials.Token = clientCfg.BearerToken
	credentials.TokenFile = clientCfg.BearerTokenFile
	credentials.ClientCertificate = clientCfg.TLSClientConfig.CertFile
	if len(credentials.ClientCertificate) == 0 {
		credentials.ClientCertificateData = clientCfg.TLSClientConfig.CertData
	}
	credentials.ClientKey = clientCfg.TLSClientConfig.KeyFile
	if len(credentials.ClientKey) == 0 {
		credentials.ClientKeyData = clientCfg.TLSClientConfig.KeyData
	}
	config.AuthInfos[userNick] = credentials

	cluster := clientcmdapi.NewCluster()
	cluster.Server = clientCfg.Host
	cluster.CertificateAuthority = clientCfg.CAFile
	if len(cluster.CertificateAuthority) == 0 {
		cluster.CertificateAuthorityData = clientCfg.CAData
	}
	cluster.InsecureSkipTLSVerify = clientCfg.Insecure
	config.Clusters[clusterNick] = cluster

	context := clientcmdapi.NewContext()
	context.Cluster = clusterNick
	context.AuthInfo = userNick
	config.Contexts[contextNick] = context
	config.CurrentContext = contextNick

	return config
}


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2008 J. Erik Radmall

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

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

/*! \file commoditypricinghelpers.hpp
    \brief Commodity pricing helpers
*/

#ifndef quantlib_commodity_pricing_helpers_hpp
#define quantlib_commodity_pricing_helpers_hpp

#include <ql/experimental/commodities/energycommodity.hpp>
#include <ql/experimental/commodities/paymentterm.hpp>
#include <ql/experimental/commodities/pricingperiod.hpp>
#include <ql/experimental/commodities/unitofmeasureconversionmanager.hpp>
#include <ql/currencies/exchangeratemanager.hpp>

namespace QuantLib {

    //! commodity index helper
    class CommodityPricingHelper {
      public:
        CommodityPricingHelper();

        static Real calculateFxConversionFactor(const Currency& fromCurrency,
                                                const Currency& toCurrency,
                                                const Date& evaluationDate);

        static Real calculateUomConversionFactor(
                                       const CommodityType& commodityType,
                                       const UnitOfMeasure& fromUnitOfMeasure,
                                       const UnitOfMeasure& toUnitOfMeasure);

        static Real calculateUnitCost(const CommodityType& commodityType,
                                      const CommodityUnitCost& unitCost,
                                      const Currency& baseCurrency,
                                      const UnitOfMeasure& baseUnitOfMeasure,
                                      const Date& evaluationDate);

        static void createPricingPeriods(
                          Date startDate, Date endDate,
                          const Quantity& quantity,
                          EnergyCommodity::DeliverySchedule deliverySchedule,
                          EnergyCommodity::QuantityPeriodicity qtyPeriodicity,
                          const PaymentTerm& paymentTerm,
                          PricingPeriods& pricingPeriods);
    };

    inline Real CommodityPricingHelper::calculateUomConversionFactor(
                                       const CommodityType& commodityType,
                                       const UnitOfMeasure& fromUnitOfMeasure,
                                       const UnitOfMeasure& toUnitOfMeasure) {
        if (toUnitOfMeasure != fromUnitOfMeasure) {
            UnitOfMeasureConversion uomConv =
                UnitOfMeasureConversionManager::instance().lookup(
                           commodityType, fromUnitOfMeasure, toUnitOfMeasure);
            return uomConv.conversionFactor();
        }

        return 1;
    }

    inline Real CommodityPricingHelper::calculateFxConversionFactor(
                                                 const Currency& fromCurrency,
                                                 const Currency& toCurrency,
                                                 const Date& evaluationDate) {
        if (fromCurrency != toCurrency) {
            ExchangeRate exchRate =
                ExchangeRateManager::instance().lookup(fromCurrency,
                                                       toCurrency,
                                                       evaluationDate,
                                                       ExchangeRate::Direct);
            if (fromCurrency != exchRate.source())
                return (Real)1 / exchRate.rate();
            return exchRate.rate();
        }
        return 1;
    }

    inline Real CommodityPricingHelper::calculateUnitCost(
                                       const CommodityType& commodityType,
                                       const CommodityUnitCost& unitCost,
                                       const Currency& baseCurrency,
                                       const UnitOfMeasure& baseUnitOfMeasure,
                                       const Date& evaluationDate) {
        if (unitCost.amount().value() != 0) {
            Real unitCostUomConversionFactor =
                calculateUomConversionFactor(commodityType,
                                             unitCost.unitOfMeasure(),
                                             baseUnitOfMeasure);
            Real unitCostFxConversionFactor =
                calculateFxConversionFactor(unitCost.amount().currency(),
                                            baseCurrency, evaluationDate);
            return unitCost.amount().value() * unitCostUomConversionFactor
                 * unitCostFxConversionFactor;
        }
        return 0;
    }

}

#endif