text:
<?php

namespace Laravel\Dusk\Concerns;

use Illuminate\Support\Arr;
use PHPUnit\Framework\Assert as PHPUnit;
use PHPUnit\Framework\Constraint\RegularExpression;

trait MakesUrlAssertions
{
    /**
     * Assert that the current URL (without the query string) matches the given string.
     *
     * @param  string  $url
     * @return $this
     */
    public function assertUrlIs($url)
    {
        $pattern = str_replace('\*', '.*', preg_quote($url, '/'));

        $segments = parse_url($this->driver->getCurrentURL());

        $currentUrl = sprintf(
            '%s://%s%s%s',
            $segments['scheme'],
            $segments['host'],
            Arr::get($segments, 'port', '') ? ':'.$segments['port'] : '',
            Arr::get($segments, 'path', '')
        );

        PHPUnit::assertThat(
            $currentUrl, new RegularExpression('/^'.$pattern.'$/u'),
            "Actual URL [{$this->driver->getCurrentURL()}] does not equal expected URL [{$url}]."
        );

        return $this;
    }

    /**
     * Assert that the current URL scheme matches the given scheme.
     *
     * @param  string  $scheme
     * @return $this
     */
    public function assertSchemeIs($scheme)
    {
        $pattern = str_replace('\*', '.*', preg_quote($scheme, '/'));

        $actual = parse_url($this->driver->getCurrentURL(), PHP_URL_SCHEME) ?? '';

        PHPUnit::assertThat(
            $actual, new RegularExpression('/^'.$pattern.'$/u'),
            "Actual scheme [{$actual}] does not equal expected scheme [{$pattern}]."
        );

        return $this;
    }

    /**
     * Assert that the current URL scheme does not match the given scheme.
     *
     * @param  string  $scheme
     * @return $this
     */
    public function assertSchemeIsNot($scheme)
    {
        $actual = parse_url($this->driver->getCurrentURL(), PHP_URL_SCHEME) ?? '';

        PHPUnit::assertNotEquals(
            $scheme, $actual,
            "Scheme [{$scheme}] should not equal the actual value."
        );

        return $this;
    }

    /**
     * Assert that the current URL host matches the given host.
     *
     * @param  string  $host
     * @return $this
     */
    public function assertHostIs($host)
    {
        $pattern = str_replace('\*', '.*', preg_quote($host, '/'));

        $actual = parse_url($this->driver->getCurrentURL(), PHP_URL_HOST) ?? '';

        PHPUnit::assertThat(
            $actual, new RegularExpression('/^'.$pattern.'$/u'),
            "Actual host [{$actual}] does not equal expected host [{$pattern}]."
        );

        return $this;
    }

    /**
     * Assert that the current URL host does not match the given host.
     *
     * @param  string  $host
     * @return $this
     */
    public function assertHostIsNot($host)
    {
        $actual = parse_url($this->driver->getCurrentURL(), PHP_URL_HOST) ?? '';

        PHPUnit::assertNotEquals(
            $host, $actual,
            "Host [{$host}] should not equal the actual value."
        );

        return $this;
    }

    /**
     * Assert that the current URL port matches the given port.
     *
     * @param  string  $port
     * @return $this
     */
    public function assertPortIs($port)
    {
        $pattern = str_replace('\*', '.*', preg_quote($port, '/'));

        $actual = (string) parse_url($this->driver->getCurrentURL(), PHP_URL_PORT) ?? '';

        PHPUnit::assertThat(
            $actual, new RegularExpression('/^'.$pattern.'$/u'),
            "Actual port [{$actual}] does not equal expected port [{$pattern}]."
        );

        return $this;
    }

    /**
     * Assert that the current URL port does not match the given port.
     *
     * @param  string  $port
     * @return $this
     */
    public function assertPortIsNot($port)
    {
        $actual = parse_url($this->driver->getCurrentURL(), PHP_URL_PORT) ?? '';

        PHPUnit::assertNotEquals(
            $port, $actual,
            "Port [{$port}] should not equal the actual value."
        );

        return $this;
    }

    /**
     * Assert that the current URL path begins with the given path.
     *
     * @param  string  $path
     * @return $this
     */
    public function assertPathBeginsWith($path)
    {
        $actualPath = parse_url($this->driver->getCurrentURL(), PHP_URL_PATH) ?? '';

        PHPUnit::assertStringStartsWith(
            $path, $actualPath,
            "Actual path [{$actualPath}] does not begin with expected path [{$path}]."
        );

        return $this;
    }

    /**
     * Assert that the current path matches the given path.
     *
     * @param  string  $path
     * @return $this
     */
    public function assertPathIs($path)
    {
        $pattern = str_replace('\*', '.*', preg_quote($path, '/'));

        $actualPath = parse_url($this->driver->getCurrentURL(), PHP_URL_PATH) ?? '';

        PHPUnit::assertThat(
            $actualPath, new RegularExpression('/^'.$pattern.'$/u'),
            "Actual path [{$actualPath}] does not equal expected path [{$path}]."
        );

        return $this;
    }

    /**
     * Assert that the current path does not match the given path.
     *
     * @param  string  $path
     * @return $this
     */
    public function assertPathIsNot($path)
    {
        $actualPath = parse_url($this->driver->getCurrentURL(), PHP_URL_PATH) ?? '';

        PHPUnit::assertNotEquals(
            $path, $actualPath,
            "Path [{$path}] should not equal the actual value."
        );

        return $this;
    }

    /**
     * Assert that the current URL matches the given named route's URL.
     *
     * @param  string  $route
     * @param  array  $parameters
     * @return $this
     */
    public function assertRouteIs($route, $parameters = [])
    {
        return $this->assertPathIs(route($route, $parameters, false));
    }

    /**
     * Assert that the given query string parameter is present and has a given value.
     *
     * @param  string  $name
     * @param  string|null  $value
     * @return $this
     */
    public function assertQueryStringHas($name, $value = null)
    {
        $output = $this->assertHasQueryStringParameter($name);

        if (is_null($value)) {
            return $this;
        }

        $parsedOutputName = is_array($output[$name]) ? implode(',', $output[$name]) : $output[$name];

        $parsedValue = is_array($value) ? implode(',', $value) : $value;

        PHPUnit::assertEquals(
            $value, $output[$name],
            "Query string parameter [{$name}] had value [{$parsedOutputName}], but expected [{$parsedValue}]."
        );

        return $this;
    }

    /**
     * Assert that the given query string parameter is missing.
     *
     * @param  string  $name
     * @return $this
     */
    public function assertQueryStringMissing($name)
    {
        $parsedUrl = parse_url($this->driver->getCurrentURL());

        if (! array_key_exists('query', $parsedUrl)) {
            PHPUnit::assertTrue(true);

            return $this;
        }

        parse_str($parsedUrl['query'], $output);

        PHPUnit::assertArrayNotHasKey(
            $name, $output,
            "Found unexpected query string parameter [{$name}] in [".$this->driver->getCurrentURL().'].'
        );

        return $this;
    }

    /**
     * Assert that the URL's current hash fragment matches the given fragment.
     *
     * @param  string  $fragment
     * @return $this
     */
    public function assertFragmentIs($fragment)
    {
        $pattern = preg_quote($fragment, '/');

        $actualFragment = (string) parse_url($this->driver->executeScript('return window.location.href;'), PHP_URL_FRAGMENT);

        PHPUnit::assertThat(
            $actualFragment, new RegularExpression('/^'.str_replace('\*', '.*', $pattern).'$/u'),
            "Actual fragment [{$actualFragment}] does not equal expected fragment [{$fragment}]."
        );

        return $this;
    }

    /**
     * Assert that the URL's current hash fragment begins with the given fragment.
     *
     * @param  string  $fragment
     * @return $this
     */
    public function assertFragmentBeginsWith($fragment)
    {
        $actualFragment = (string) parse_url($this->driver->executeScript('return window.location.href;'), PHP_URL_FRAGMENT);

        PHPUnit::assertStringStartsWith(
            $fragment, $actualFragment,
            "Actual fragment [$actualFragment] does not begin with expected fragment [$fragment]."
        );

        return $this;
    }

    /**
     * Assert that the URL's current hash fragment does not match the given fragment.
     *
     * @param  string  $fragment
     * @return $this
     */
    public function assertFragmentIsNot($fragment)
    {
        $actualFragment = (string) parse_url($this->driver->executeScript('return window.location.href;'), PHP_URL_FRAGMENT);

        PHPUnit::assertNotEquals(
            $fragment, $actualFragment,
            "Fragment [{$fragment}] should not equal the actual value."
        );

        return $this;
    }

    /**
     * Assert that the given query string parameter is present.
     *
     * @param  string  $name
     * @return array
     */
    protected function assertHasQueryStringParameter($name)
    {
        $parsedUrl = parse_url($this->driver->getCurrentURL());

        PHPUnit::assertArrayHasKey(
            'query', $parsedUrl,
            'Did not see expected query string in ['.$this->driver->getCurrentURL().'].'
        );

        parse_str($parsedUrl['query'], $output);

        PHPUnit::assertArrayHasKey(
            $name, $output,
            "Did not see expected query string parameter [{$name}] in [".$this->driver->getCurrentURL().'].'
        );

        return $output;
    }
}


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p275;

import org.junit.Test;
import static org.junit.Assert.*;

public class Test5517 {
    Production5517 objectUnderTest = new Production5517();

    @Test
    public void testProperty0() {
        Production5514 value = new Production5514();
        objectUnderTest.setProperty0(value);
        assertEquals(value, objectUnderTest.getProperty0());
    }

    @Test
    public void testProperty1() {
        Production5515 value = new Production5515();
        objectUnderTest.setProperty1(value);
        assertEquals(value, objectUnderTest.getProperty1());
    }

    @Test
    public void testProperty2() {
        Production5516 value = new Production5516();
        objectUnderTest.setProperty2(value);
        assertEquals(value, objectUnderTest.getProperty2());
    }

    @Test
    public void testProperty3() {
        String value = "value";
        objectUnderTest.setProperty3(value);
        assertEquals(value, objectUnderTest.getProperty3());
    }

    @Test
    public void testProperty4() {
        String value = "value";
        objectUnderTest.setProperty4(value);
        assertEquals(value, objectUnderTest.getProperty4());
    }

    @Test
    public void testProperty5() {
        String value = "value";
        objectUnderTest.setProperty5(value);
        assertEquals(value, objectUnderTest.getProperty5());
    }

    @Test
    public void testProperty6() {
        String value = "value";
        objectUnderTest.setProperty6(value);
        assertEquals(value, objectUnderTest.getProperty6());
    }

    @Test
    public void testProperty7() {
        String value = "value";
        objectUnderTest.setProperty7(value);
        assertEquals(value, objectUnderTest.getProperty7());
    }

    @Test
    public void testProperty8() {
        String value = "value";
        objectUnderTest.setProperty8(value);
        assertEquals(value, objectUnderTest.getProperty8());
    }

    @Test
    public void testProperty9() {
        String value = "value";
        objectUnderTest.setProperty9(value);
        assertEquals(value, objectUnderTest.getProperty9());
    }

}

redpajama_set_name: RedPajamaGithub


text:
import { IFileWrapper, FileWrapper } from './file.model';

export enum ArchiveType {
    REPOSITORY,
    URL,
    FILE_UPLOAD
}

export interface IArchive {
    type?: ArchiveType;
    version?: string;
    url?: string;
    fileUpload?: IFileWrapper;
}

export class Archive implements IArchive {
    type?: ArchiveType;
    version?: string;
    url?: string;
    fileUpload?: IFileWrapper;
}


text:
worker_processes 3
timeout 30
preload_app true

before_fork do |server, worker|
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.connection.disconnect!
    Rails.logger.info("Disconnected from ActiveRecord")
  end
end

after_fork do |server, worker|
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection
    Rails.logger.info("Connected to ActiveRecord")
  end
end


text:
<?php
namespace Keboola\Test\Common;

use Keboola\StorageApi\Client;
use Keboola\StorageApi\ClientException;
use Keboola\StorageApi\Options\Components\Configuration;
use Keboola\StorageApi\Options\Components\ConfigurationRow;
use Keboola\StorageApi\Options\Components\ConfigurationRowState;
use Keboola\StorageApi\Options\Components\ListComponentConfigurationsOptions;
use Keboola\StorageApi\Options\Components\ListComponentsOptions;
use Keboola\Test\ClientProvider\ClientProvider;
use Keboola\Test\StorageApiTestCase;

class ConfigurationRowStateTest extends StorageApiTestCase
{
    /**
     * @var Client
     */
    private $client;

    public function setUp(): void
    {
        parent::setUp();

        $components = new \Keboola\StorageApi\Components($this->_client);
        foreach ($components->listComponents() as $component) {
            foreach ($component['configurations'] as $configuration) {
                $components->deleteConfiguration($component['id'], $configuration['id']);
            }
        }

        // erase all deleted configurations
        foreach ($components->listComponents((new ListComponentsOptions())->setIsDeleted(true)) as $component) {
            foreach ($component['configurations'] as $configuration) {
                $components->deleteConfiguration($component['id'], $configuration['id']);
            }
        }

        $clientProvider = new ClientProvider($this);
        $this->client = $clientProvider->createClientForCurrentTest();
    }

    /**
     * @dataProvider provideComponentsClientType
     */
    public function testAttributeExists(): void
    {
        $components = new \Keboola\StorageApi\Components($this->client);
        $configuration = (new \Keboola\StorageApi\Options\Components\Configuration())
                    ->setComponentId('wr-db')
                    ->setConfigurationId('main-1')
                    ->setName('Main');
        $components->addConfiguration($configuration);

        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-1');
        $components->addConfigurationRow($configurationRow);

        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertArrayHasKey('state', $configurationResponse['rows'][0]);
        $this->assertEmpty($configurationResponse['rows'][0]['state']);
        $this->assertIsArray($configurationResponse['rows'][0]['state']);
    }

    /**
     * @dataProvider provideComponentsClientType
     */
    public function testAttributeValueCreate(): void
    {
        $components = new \Keboola\StorageApi\Components($this->client);
        $configuration = new \Keboola\StorageApi\Options\Components\Configuration();
        $configuration
            ->setComponentId('wr-db')
            ->setConfigurationId('main-1')
            ->setName('Main');
        $components->addConfiguration($configuration);

        $state = [
            'key' => 'val',
        ];

        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-1')
            ->setState($state);
        $components->addConfigurationRow($configurationRow);

        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertEquals($state, $configurationResponse['rows'][0]['state']);
    }

    /**
     * @dataProvider provideComponentsClientType
     */
    public function testAttributeValueUpdate(): void
    {
        $components = new \Keboola\StorageApi\Components($this->client);
        $configuration = new \Keboola\StorageApi\Options\Components\Configuration();
        $configuration
            ->setComponentId('wr-db')
            ->setConfigurationId('main-1')
            ->setName('Main');
        $components->addConfiguration($configuration);

        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-1');
        $configurationRowResponse = $components->addConfigurationRow($configurationRow);

        $state = [
            'key' => 'val',
        ];
        $components->updateConfigurationRowState((new ConfigurationRowState($configuration))
            ->setRowId($configurationRowResponse['id'])
            ->setState($state));

        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertEquals($state, $configurationResponse['rows'][0]['state']);
    }

    /**
     * @dataProvider provideComponentsClientType
     */
    public function testVersionUnchangedAfterSettingAttribute(): void
    {
        $components = new \Keboola\StorageApi\Components($this->client);
        $configuration = new \Keboola\StorageApi\Options\Components\Configuration();
        $configuration
            ->setComponentId('wr-db')
            ->setConfigurationId('main-1')
            ->setName('Main');
        $components->addConfiguration($configuration);

        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-1');
        $configurationRowResponse = $components->addConfigurationRow($configurationRow);

        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertEquals(2, $configurationResponse['version']);

        $state = [
            'key' => 'val',
        ];
        $components->updateConfigurationRowState((new ConfigurationRowState($configuration))
            ->setRowId($configurationRowResponse['id'])
            ->setState($state));

        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertEquals(2, $configurationResponse['version']);
    }

    /**
     * @dataProvider provideComponentsClientType
     */
    public function testAttributeNotPresentInVersions(): void
    {
        $components = new \Keboola\StorageApi\Components($this->client);
        $configuration = new \Keboola\StorageApi\Options\Components\Configuration();
        $configuration
            ->setComponentId('wr-db')
            ->setConfigurationId('main-1')
            ->setName('Main');
        $components->addConfiguration($configuration);

        $state = ['key' => 'val'];
        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-1')
            ->setState($state);
        $components->addConfigurationRow($configurationRow);

        $this->assertArrayNotHasKey('state', $components->getConfigurationVersion('wr-db', 'main-1', 2)['rows'][0]);
        $this->assertArrayNotHasKey('state', $components->getConfigurationRowVersion('wr-db', 'main-1', 'main-1-1', 1));
    }

    /**
     * @dataProvider provideComponentsClientType
     */
    public function testRollbackPreservesState(): void
    {

        $components = new \Keboola\StorageApi\Components($this->client);
        $configuration = new \Keboola\StorageApi\Options\Components\Configuration();
        $configuration
            ->setComponentId('wr-db')
            ->setConfigurationId('main-1')
            ->setName('Main');
        $components->addConfiguration($configuration);

        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-1')
            ->setState(['unknown' => 'undefined']);
        $components->addConfigurationRow($configurationRow);

        $updateConfig = new ConfigurationRow($configuration);
        $updateConfig
            ->setRowId('main-1-1')
            ->setName('changed name');
        $components->updateConfigurationRow($updateConfig);

        $state = ['key' => 'val'];
        $components->updateConfigurationRowState((new ConfigurationRowState($configuration))
            ->setRowId('main-1-1')
            ->setState($state));

        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertEquals(3, $configurationResponse['version']);
        $this->assertEquals($state, $configurationResponse['rows'][0]['state']);

        $components->rollbackConfiguration('wr-db', 'main-1', 2);
        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertEquals(4, $configurationResponse['version']);
        $this->assertEquals($state, $configurationResponse['rows'][0]['state']);

        $components->rollbackConfiguration('wr-db', 'main-1', 3);
        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertEquals(5, $configurationResponse['version']);
        $this->assertEquals($state, $configurationResponse['rows'][0]['state']);
    }

    /**
     * @dataProvider provideComponentsClientType
     */
    public function testCopyPreservesState(): void
    {
        $components = new \Keboola\StorageApi\Components($this->client);
        $configuration = new \Keboola\StorageApi\Options\Components\Configuration();
        $configuration
            ->setComponentId('wr-db')
            ->setConfigurationId('main-1')
            ->setName('Main');
        $components->addConfiguration($configuration);

        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-1')
            ->setState(['unknown' => 'undefined']);
        $components->addConfigurationRow($configurationRow);

        $updateConfig = new ConfigurationRow($configuration);
        $updateConfig
            ->setRowId('main-1-1')
            ->setName('changed name');
        $components->updateConfigurationRow($updateConfig);

        $state = ['key' => 'val'];
        $components->updateConfigurationRow($updateConfig);
        $components->updateConfigurationRowState((new ConfigurationRowState($configuration))
            ->setRowId('main-1-1')
            ->setState($state));

        $newConfig = $components->createConfigurationFromVersion('wr-db', 'main-1', 3, 'main-2');
        $configurationResponse = $components->getConfiguration('wr-db', $newConfig['id']);
        $this->assertEquals($state, $configurationResponse['rows'][0]['state']);

        $newConfig = $components->createConfigurationFromVersion('wr-db', 'main-1', 2, 'main-2');
        $configurationResponse = $components->getConfiguration('wr-db', $newConfig['id']);
        $this->assertEquals($state, $configurationResponse['rows'][0]['state']);
    }

    /**
     * @dataProvider provideComponentsClientType
     */
    public function testRowRollbackPreservesState(): void
    {
        $components = new \Keboola\StorageApi\Components($this->client);
        $configuration = new \Keboola\StorageApi\Options\Components\Configuration();
        $configuration
            ->setComponentId('wr-db')
            ->setConfigurationId('main-1')
            ->setName('Main');
        $components->addConfiguration($configuration);

        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-1')
            ->setState(['unknown' => 'undefined']);
        $components->addConfigurationRow($configurationRow);

        $updateConfig = new ConfigurationRow($configuration);
        $updateConfig
            ->setRowId('main-1-1')
            ->setName('changed name');
        $components->updateConfigurationRow($updateConfig);

        $state = ['key' => 'val'];
        $components->updateConfigurationRowState((new ConfigurationRowState($configuration))
            ->setRowId('main-1-1')
            ->setState($state));
        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertCount(1, $configurationResponse['rows']);
        $this->assertEquals(3, $configurationResponse['version']);
        $this->assertEquals($state, $configurationResponse['rows'][0]['state']);

        $components->rollbackConfigurationRow('wr-db', 'main-1', 'main-1-1', 1);
        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertCount(1, $configurationResponse['rows']);
        $this->assertEquals(3, $configurationResponse['rows'][0]['version']);
        $this->assertEquals($state, $configurationResponse['rows'][0]['state']);

        $components->rollbackConfigurationRow('wr-db', 'main-1', 'main-1-1', 2);
        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertEquals(4, $configurationResponse['rows'][0]['version']);
        $this->assertEquals($state, $configurationResponse['rows'][0]['state']);
    }

    /**
     * @dataProvider provideComponentsClientType
     */
    public function testRowCopyResetsState(): void
    {
        $components = new \Keboola\StorageApi\Components($this->client);

        $configuration = new \Keboola\StorageApi\Options\Components\Configuration();
        $configuration
            ->setComponentId('wr-db')
            ->setConfigurationId('main-2')
            ->setName('Copy 1');
        $components->addConfiguration($configuration);

        $configuration = new \Keboola\StorageApi\Options\Components\Configuration();
        $configuration
            ->setComponentId('wr-db')
            ->setConfigurationId('main-3')
            ->setName('Copy 2');
        $components->addConfiguration($configuration);

        $configuration = new \Keboola\StorageApi\Options\Components\Configuration();
        $configuration
            ->setComponentId('wr-db')
            ->setConfigurationId('main-1')
            ->setName('Main');
        $components->addConfiguration($configuration);

        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-1')
            ->setState(['unknown' => 'undefined']);
        $components->addConfigurationRow($configurationRow);

        $updateConfig = new ConfigurationRow($configuration);
        $updateConfig
            ->setRowId('main-1-1')
            ->setName('changed name');
        $components->updateConfigurationRow($updateConfig);

        $state = ['key' => 'val'];
        $components->updateConfigurationRowState((new ConfigurationRowState($configuration))
            ->setRowId('main-1-1')
            ->setState($state));
        $components->createConfigurationRowFromVersion('wr-db', 'main-1', 'main-1-1', 1, 'main-2');
        $configurationResponse = $components->getConfiguration('wr-db', 'main-2');
        $this->assertEmpty($configurationResponse['rows'][0]['state']);

        $components->createConfigurationRowFromVersion('wr-db', 'main-1', 'main-1-1', 2, 'main-3');
        $configurationResponse = $components->getConfiguration('wr-db', 'main-3');
        $this->assertEmpty($configurationResponse['rows'][0]['state']);
    }

    /**
     * @dataProvider provideComponentsClientType
     */
    public function testDeletedRowRollbackPreservesState(): void
    {
        $components = new \Keboola\StorageApi\Components($this->client);
        $configuration = new \Keboola\StorageApi\Options\Components\Configuration();
        $configuration
            ->setComponentId('wr-db')
            ->setConfigurationId('main-1')
            ->setName('Main');
        $components->addConfiguration($configuration);

        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-1')
            ->setState(['unknown' => 'undefined']);
        $components->addConfigurationRow($configurationRow);

        $state2 = ['key' => 'val2'];
        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-2')
            ->setState($state2);
        $components->addConfigurationRow($configurationRow);

        $updateConfig = new ConfigurationRow($configuration);
        $updateConfig
            ->setRowId('main-1-1')
            ->setName('changed name');
        $components->updateConfigurationRow($updateConfig);

        $state1 = ['key' => 'val'];
        $components->updateConfigurationRowState((new ConfigurationRowState($configuration))
            ->setRowId('main-1-1')
            ->setState($state1));

        $components->deleteConfigurationRow('wr-db', 'main-1', 'main-1-1');

        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertEquals(5, $configurationResponse['version']);

        $components->rollbackConfiguration('wr-db', 'main-1', 4);
        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertEquals(6, $configurationResponse['version']);
        $this->assertEquals($state1, $configurationResponse['rows'][0]['state']);
        $this->assertEquals($state2, $configurationResponse['rows'][1]['state']);

        $components->rollbackConfiguration('wr-db', 'main-1', 3);
        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertEquals(7, $configurationResponse['version']);
        $this->assertEquals($state1, $configurationResponse['rows'][0]['state']);
        $this->assertEquals($state2, $configurationResponse['rows'][1]['state']);
    }

    /**
     * @dataProvider provideComponentsClientType
     */
    public function testDeletedRowCopyPreservesState(): void
    {
        $components = new \Keboola\StorageApi\Components($this->client);
        $configuration = new \Keboola\StorageApi\Options\Components\Configuration();
        $configuration
            ->setComponentId('wr-db')
            ->setConfigurationId('main-1')
            ->setName('Main');
        $components->addConfiguration($configuration);

        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-1')
            ->setState(['unknown' => 'undefined']);
        $components->addConfigurationRow($configurationRow);

        $state2 = ['key' => 'val2'];
        $configurationRow = new \Keboola\StorageApi\Options\Components\ConfigurationRow($configuration);
        $configurationRow->setRowId('main-1-2')
            ->setState($state2);
        $components->addConfigurationRow($configurationRow);

        $updateConfig = new ConfigurationRow($configuration);
        $updateConfig
            ->setRowId('main-1-1')
            ->setName('changed name');
        $components->updateConfigurationRow($updateConfig);

        $state1 = ['key' => 'val'];
        $components->updateConfigurationRowState((new ConfigurationRowState($configuration))->setRowId('main-1-1')->setState($state1));

        $components->deleteConfigurationRow('wr-db', 'main-1', 'main-1-1');

        $configurationResponse = $components->getConfiguration('wr-db', 'main-1');
        $this->assertEquals(5, $configurationResponse['version']);

        $newConfig = $components->createConfigurationFromVersion('wr-db', 'main-1', 4, 'New Config');

        $configurationResponse = $components->getConfiguration('wr-db', $newConfig['id']);
        $this->assertEquals(1, $configurationResponse['version']);
        $this->assertEquals($state1, $configurationResponse['rows'][0]['state']);
        $this->assertEquals($state2, $configurationResponse['rows'][1]['state']);
    }
}


text:
    <meta charset="UTF-8">
    <title>MTMathColor.
        <init> -
    </title>
    <link rel="stylesheet" href="../../style.css">

com.agog.mathdisplay.parse / MTMathColor / <init>

<init>

MTMathColor()


text:
"""try to find more bugs in the code using astng inference capabilities
"""

import re
import shlex

from logilab import astng
from logilab.astng import InferenceError, NotFoundError, YES, Instance

from pylint.interfaces import IASTNGChecker
from pylint.checkers import BaseChecker
from pylint.checkers.utils import safe_infer, is_super, check_messages

MSGS = {
    'E1101': ('%s %r has no %r member',
              'Used when a variable is accessed for an unexistent member.'),
    'E1102': ('%s is not callable',
              'Used when an object being called has been inferred to a non \
              callable object'),
    'E1103': ('%s %r has no %r member (but some types could not be inferred)',
              'Used when a variable is accessed for an unexistent member, but \
              astng was not able to interpret all possible types of this \
              variable.'),
    'E1111': ('Assigning to function call which doesn\'t return',
              'Used when an assignment is done on a function call but the \
              inferred function doesn\'t return anything.'),
    'W1111': ('Assigning to function call which only returns None',
              'Used when an assignment is done on a function call but the \
              inferred function returns nothing but None.'),

    'E1120': ('No value passed for parameter %s in function call',
              'Used when a function call passes too few arguments.'),
    'E1121': ('Too many positional arguments for function call',
              'Used when a function call passes too many positional \
              arguments.'),
    'E1122': ('Duplicate keyword argument %r in function call',
              'Used when a function call passes the same keyword argument \
              multiple times.'),
    'E1123': ('Passing unexpected keyword argument %r in function call',
              'Used when a function call passes a keyword argument that \
              doesn\'t correspond to one of the function\'s parameter names.'),
    'E1124': ('Multiple values passed for parameter %r in function call',
              'Used when a function call would result in assigning multiple \
              values to a function parameter, one value from a positional \
              argument and one from a keyword argument.'),
    }

class TypeChecker(BaseChecker):
    """try to find bugs in the code using type inference
    """

    __implements__ = (IASTNGChecker,)

    # configuration section name
    name = 'typecheck'
    # messages
    msgs = MSGS
    priority = -1
    # configuration options
    options = (('ignore-mixin-members',
                {'default' : True, 'type' : 'yn', 'metavar': '<y_or_n>',
                 'help' : 'Tells whether missing members accessed in mixin \
class should be ignored. A mixin class is detected if its name ends with \
"mixin" (case insensitive).'}
                ),

               ('ignored-classes',
                {'default' : ('SQLObject',),
                 'type' : 'csv',
                 'metavar' : '<members names>',
                 'help' : 'List of classes names for which member attributes \
should not be checked (useful for classes with attributes dynamically set).'}
                 ),

               ('zope',
                {'default' : False, 'type' : 'yn', 'metavar': '<y_or_n>',
                 'help' : 'When zope mode is activated, add a predefined set \
of Zope acquired attributes to generated-members.'}
                ),
               ('generated-members',
                {'default' : (
        'REQUEST', 'acl_users', 'aq_parent'),
                 'type' : 'string',
                 'metavar' : '<members names>',
                 'help' : 'List of members which are set dynamically and \
missed by pylint inference system, and so shouldn\'t trigger E0201 when \
accessed. Python regular expressions are accepted.'}
                ),
        )

    def open(self):
        # do this in open since config not fully initialized in __init__
        self.generated_members = list(self.config.generated_members)
        if self.config.zope:
            self.generated_members.extend(('REQUEST', 'acl_users', 'aq_parent'))

    def visit_assattr(self, node):
        if isinstance(node.ass_type(), astng.AugAssign):
            self.visit_getattr(node)

    def visit_delattr(self, node):
        self.visit_getattr(node)

    @check_messages('E1101', 'E1103')
    def visit_getattr(self, node):
        """check that the accessed attribute exists

        to avoid to much false positives for now, we'll consider the code as
        correct if a single of the inferred nodes has the accessed attribute.

        function/method, super call and metaclasses are ignored
        """
        # generated_members may containt regular expressions
        # (surrounded by quote `"` and followed by a comma `,`)
        # REQUEST,aq_parent,"[a-zA-Z]+_set{1,2}"' =>
        # ('REQUEST', 'aq_parent', '[a-zA-Z]+_set{1,2}')
        if isinstance(self.config.generated_members, str):
            gen = shlex.shlex(self.config.generated_members)
            gen.whitespace += ','
            gen.wordchars += '[]-+'
            self.config.generated_members = tuple(tok.strip('"') for tok in gen)
        for pattern in self.config.generated_members:
            # attribute is marked as generated, stop here
            if re.match(pattern, node.attrname):
                return
        try:
            infered = list(node.expr.infer())
        except InferenceError:
            return
        # list of (node, nodename) which are missing the attribute
        missingattr = set()
        ignoremim = self.config.ignore_mixin_members
        inference_failure = False
        for owner in infered:
            # skip yes object
            if owner is YES:
                inference_failure = True
                continue
            # skip None anyway
            if isinstance(owner, astng.Const) and owner.value is None:
                continue
            # XXX "super" / metaclass call
            if is_super(owner) or getattr(owner, 'type', None) == 'metaclass':
                continue
            name = getattr(owner, 'name', 'None')
            if name in self.config.ignored_classes:
                continue
            if ignoremim and name[-5:].lower() == 'mixin':
                continue
            try:
                if not [n for n in owner.getattr(node.attrname)
                        if not isinstance(n.statement(), astng.AugAssign)]:
                    missingattr.add((owner, name))
                    continue
            except AttributeError:
                # XXX method / function
                continue
            except NotFoundError:
                if isinstance(owner, astng.Function) and owner.decorators:
                   continue
                if isinstance(owner, Instance) and owner.has_dynamic_getattr():
                    continue
                # explicit skipping of optparse'Values class
                if owner.name == 'Values' and owner.root().name == 'optparse':
                    continue
                missingattr.add((owner, name))
                continue
            # stop on the first found
            break
        else:
            # we have not found any node with the attributes, display the
            # message for infered nodes
            done = set()
            for owner, name in missingattr:
                if isinstance(owner, Instance):
                    actual = owner._proxied
                else:
                    actual = owner
                if actual in done:
                    continue
                done.add(actual)
                if inference_failure:
                    msgid = 'E1103'
                else:
                    msgid = 'E1101'
                self.add_message(msgid, node=node,
                                 args=(owner.display_type(), name,
                                       node.attrname))

    def visit_assign(self, node):
        """check that if assigning to a function call, the function is
        possibly returning something valuable
        """
        if not isinstance(node.value, astng.CallFunc):
            return
        function_node = safe_infer(node.value.func)
        # skip class, generator and incomplete function definition
        if not (isinstance(function_node, astng.Function) and
                function_node.root().fully_defined()):
            return
        if function_node.is_generator() \
               or function_node.is_abstract(pass_is_abstract=False):
            return
        returns = list(function_node.nodes_of_class(astng.Return,
                                                    skip_klass=astng.Function))
        if len(returns) == 0:
            self.add_message('E1111', node=node)
        else:
            for rnode in returns:
                if not (isinstance(rnode.value, astng.Const)
                        and rnode.value.value is None):
                    break
            else:
                self.add_message('W1111', node=node)

    def visit_callfunc(self, node):
        """check that called functions/methods are inferred to callable objects,
        and that the arguments passed to the function match the parameters in
        the inferred function's definition
        """

        # Build the set of keyword arguments, checking for duplicate keywords,
        # and count the positional arguments.
        keyword_args = set()
        num_positional_args = 0
        for arg in node.args:
            if isinstance(arg, astng.Keyword):
                keyword = arg.arg
                if keyword in keyword_args:
                    self.add_message('E1122', node=node, args=keyword)
                keyword_args.add(keyword)
            else:
                num_positional_args += 1

        called = safe_infer(node.func)
        # only function, generator and object defining __call__ are allowed
        if called is not None and not called.callable():
            self.add_message('E1102', node=node, args=node.func.as_string())

        # Note that BoundMethod is a subclass of UnboundMethod (huh?), so must
        # come first in this 'if..else'.
        if isinstance(called, astng.BoundMethod):
            # Bound methods have an extra implicit 'self' argument.
            num_positional_args += 1
        elif isinstance(called, astng.UnboundMethod):
            if called.decorators is not None:
                for d in called.decorators.nodes:
                    if isinstance(d, astng.Name) and (d.name == 'classmethod'):
                        # Class methods have an extra implicit 'cls' argument.
                        num_positional_args += 1
                        break
        elif (isinstance(called, astng.Function) or
              isinstance(called, astng.Lambda)):
            pass
        else:
            return

        if called.args.args is None:
            # Built-in functions have no argument information.
            return

        if len( called.argnames() ) != len( set( called.argnames() ) ):
            # Duplicate parameter name (see E9801).  We can't really make sense
            # of the function call in this case, so just return.
            return

        # Analyze the list of formal parameters.
        num_mandatory_parameters = len(called.args.args) - len(called.args.defaults)
        parameters = []
        parameter_name_to_index = {}
        for i, arg in enumerate(called.args.args):
            if isinstance(arg, astng.Tuple):
                name = None
                # Don't store any parameter names within the tuple, since those
                # are not assignable from keyword arguments.
            else:
                if isinstance(arg, astng.Keyword):
                    name = arg.arg
                else:
                    assert isinstance(arg, astng.AssName)
                    # This occurs with:
                    #    def f( (a), (b) ): pass
                    name = arg.name
                parameter_name_to_index[name] = i
            if i >= num_mandatory_parameters:
                defval = called.args.defaults[i - num_mandatory_parameters]
            else:
                defval = None
            parameters.append([(name, defval), False])

        # Match the supplied arguments against the function parameters.

        # 1. Match the positional arguments.
        for i in range(num_positional_args):
            if i < len(parameters):
                parameters[i][1] = True
            elif called.args.vararg is not None:
                # The remaining positional arguments get assigned to the *args
                # parameter.
                break
            else:
                # Too many positional arguments.
                self.add_message('E1121', node=node)
                break

        # 2. Match the keyword arguments.
        for keyword in keyword_args:
            if keyword in parameter_name_to_index:
                i = parameter_name_to_index[keyword]
                if parameters[i][1]:
                    # Duplicate definition of function parameter.
                    self.add_message('E1124', node=node, args=keyword)
                else:
                    parameters[i][1] = True
            elif called.args.kwarg is not None:
                # The keyword argument gets assigned to the **kwargs parameter.
                pass
            else:
                # Unexpected keyword argument.
                self.add_message('E1123', node=node, args=keyword)

        # 3. Match the *args, if any.  Note that Python actually processes
        #    *args _before_ any keyword arguments, but we wait until after
        #    looking at the keyword arguments so as to make a more conservative
        #    guess at how many values are in the *args sequence.
        if node.starargs is not None:
            for i in range(num_positional_args, len(parameters)):
                [(name, defval), assigned] = parameters[i]
                # Assume that *args provides just enough values for all
                # non-default parameters after the last parameter assigned by
                # the positional arguments but before the first parameter
                # assigned by the keyword arguments.  This is the best we can
                # get without generating any false positives.
                if (defval is not None) or assigned:
                    break
                parameters[i][1] = True

        # 4. Match the **kwargs, if any.
        if node.kwargs is not None:
            for i, [(name, defval), assigned] in enumerate(parameters):
                # Assume that *kwargs provides values for all remaining
                # unassigned named parameters.
                if name is not None:
                    parameters[i][1] = True
                else:
                    # **kwargs can't assign to tuples.
                    pass

        # Check that any parameters without a default have been assigned
        # values.
        for [(name, defval), assigned] in parameters:
            if (defval is None) and not assigned:
                if name is None:
                    display = '<tuple>'
                else:
                    display_name = repr(name)
                self.add_message('E1120', node=node, args=display_name)

def register(linter):
    """required method to auto register this checker """
    linter.register_checker(TypeChecker(linter))


text:
<?php

namespace Intervention\Image\Exception;

class InvalidImageResourceException extends \RuntimeException
{
    # nothing to override
}


text:
package com.talis.platform.sequencing.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

public class NullWatcher implements Watcher {
    public void process(WatchedEvent event) {
    	/* nada */
    }
}


text:
package com.iktwo.qtdevdays14;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import com.iktwo.qtdevdays14.R;

public class DevDays extends org.qtproject.qt5.android.bindings.QtActivity
{
    private static final String TAG = "DevDays";
    private static DevDays m_instance;

    public DevDays()
    {
        m_instance = this;
    }

    @Override
    protected void onStart()
    {
        super.onStart();
        m_instance = this;
    }

    public static void toast(final String message)
    {
        m_instance.runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(m_instance.getApplicationContext(), message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public static boolean isTablet()
    {
        return m_instance.getResources().getBoolean(R.bool.isTablet);
    }
}


text:
module com.azure.communication.networktraversal {

    requires transitive com.azure.communication.common;

    // public API surface area
    exports com.azure.communication.networktraversal;
    exports com.azure.communication.networktraversal.models;

    opens com.azure.communication.networktraversal.models
        to com.fasterxml.jackson.databind;
    opens com.azure.communication.networktraversal.implementation.models
        to com.fasterxml.jackson.databind, com.azure.core;
}


text:
package edu.jhuapl.dorset.http;

public interface HttpResponse {
    public String asString();

    public byte[] asBytes();

    public int getStatusCode();

    public String getReasonPhrase();

    /**
     * Was there a client error (such as a 404)?
     *
     * @return boolean
     */
    public boolean isClientError();

    /**
     * Was there a server error?
     *
     * @return boolean
     */
    public boolean isServerError();

    /**
     * Was there any kind of error?
     *
     * @return boolean
     */
    public boolean isError();

    /**
     * Was the request a success?
     *
     * @return boolean
     */
    public boolean isSuccess();
}


text:
import { CALL_API } from 'redux-api-middleware';

/*
 * 登录 -------------------------------------------------------
 */
export const LOGIN_REQUEST = 'LOGIN_REQUEST';
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGIN_FAILURE = 'LOGIN_FAILURE';

export function login(username, password) {

  var loginFormData = new FormData();
  loginFormData.append("username", username);
  loginFormData.append("password", password);

  return {
    [CALL_API]: {
      endpoint:'http://eswjdg.com/index.php?m=mmapi&c=member&a=login',
      method:'POST',
      body:loginFormData,
      types: [
        {type :LOGIN_REQUEST},
        {type :LOGIN_SUCCESS, payload: (action, state, res) => res.json()},
        {type :LOGIN_FAILURE}
      ]
    }
  }
}


text:
import asyncio
import gc
import itertools
import logging
import os
import subprocess
import sys
import weakref

import click
import daemonocle.cli

from . import od_repo
from . import od_task
from . import od_threads
from . import od_webhook
from .od_tasks import start_repo, merge_dir, update_subscriptions
from .od_auth import get_authenticator_and_drives
from .od_context import load_context
from .od_watcher import LocalRepositoryWatcher

context = load_context(asyncio.get_event_loop())
pidfile = context.config_dir + '/onedrived.pid'
task_workers = weakref.WeakSet()
task_pool = None
webhook_server = None
webhook_worker = None

def init_task_pool_and_workers():
    global task_pool
    task_pool = od_task.TaskPool()
    for _ in range(context.config['num_workers']):
        w = od_threads.TaskWorkerThread(name='Worker-%d' % len(task_workers), task_pool=task_pool)
        w.start()
        task_workers.add(w)

def shutdown_workers():
    for w in task_workers:
        if w:
            w.stop()
    if task_pool:
        task_pool.close(len(task_workers))
    for w in task_workers:
        if w:
            w.join()

def init_webhook():
    global webhook_server, webhook_worker
    try:
        webhook_server = od_webhook.get_webhook_server(context)
    except RuntimeError as e:
        logging.critical('Error initializing webhook: %s', e)
        raise SystemExit()
    webhook_worker = od_webhook.WebhookWorkerThread(webhook_url=webhook_server.webhook_url,
                                                    callback_func=repo_updated_callback,
                                                    action_delay_sec=context.config['webhook_action_delay_sec'])
    webhook_server.set_worker(webhook_worker)
    webhook_worker.start()
    webhook_server.start()

def shutdown_webhook():
    global webhook_server
    if webhook_server:
        webhook_server.stop()
        webhook_server.join()
        webhook_server = None

# noinspection PyUnusedLocal
def shutdown_callback(code, _):
    logging.info('Shutting down. Code: %s.', str(code))
    asyncio.gather(*asyncio.Task.all_tasks()).cancel()
    context.loop.stop()
    shutdown_webhook()
    shutdown_workers()
    if context and context.watcher:
        context.watcher.close()
        context.watcher = None
    logging.shutdown()
    logging.info('Shut down complete.')

def get_repo_table(ctx):
    """
    :param onedrived.od_context.UserContext ctx:
    :return dict[str, [onedrived.od_repo.OneDriveLocalRepository]]:
    """
    all_accounts = {}
    all_account_ids = ctx.all_accounts()
    if len(all_account_ids) == 0:
        logging.critical('onedrived is not linked with any OneDrive account. Please configure onedrived first.')
        sys.exit(1)
    for account_id in all_account_ids:
        authenticator, drives = get_authenticator_and_drives(ctx, account_id)
        local_repos = [od_repo.OneDriveLocalRepository(ctx, authenticator, d, ctx.get_drive(d.id))
                       for d in drives if d.id in ctx.config['drives']]
        if len(local_repos) > 0:
            all_accounts[account_id] = local_repos
        else:
            profile = ctx.get_account(account_id)
            logging.info('No Drive associated with account "%s" (%s).', profile.account_email, account_id)
    return all_accounts

def update_subscription_for_repo(repo, subscription_id=None):
    """
    :param onedrived.od_repo.OneDriveLocalRepository repo:
    :param str | None subscription_id:
    :return onedrivesdk.Subscription | None:
    """
    if webhook_server and webhook_worker:
        task = update_subscriptions.UpdateSubscriptionTask(repo, task_pool, webhook_worker, subscription_id)
        subscription = task.handle()
        if subscription:
            context.loop.call_later(int(context.config['webhook_renew_interval_sec'] * 0.75),
                                    update_subscription_for_repo, repo, subscription.id)
            gc.collect()
        return subscription
    return None

def gen_start_repo_tasks(all_accounts):
    """
    :param dict[str, [onedrived.od_repo.OneDriveLocalRepository]] all_accounts:
    """
    if task_pool.outstanding_task_count == 0:
        for repo in itertools.chain.from_iterable(all_accounts.values()):
            task_pool.add_task(start_repo.StartRepositoryTask(repo, task_pool))
            logging.info('Scheduled sync task for Drive %s of account %s.', repo.drive.id, repo.account_id)
            if update_subscription_for_repo(repo) is None:
                logging.warning('Failed to create webhook. Will deep sync again in %d sec.',
                                context.config['scan_interval_sec'])
                context.loop.call_later(context.config['scan_interval_sec'],
                                        gen_start_repo_tasks, all_accounts)
            else:
                logging.info('Will use webhook to trigger sync events.')

def delete_temp_files(all_accounts):
    """
    Delete all onedrived temporary files from repository.
    :param dict[str, [onedrived.od_repo.OneDriveLocalRepository]] all_accounts:
    :return:
    """
    logging.info('Sweeping onedrived temporary files from local repositories.')
    for repo in itertools.chain.from_iterable(all_accounts.values()):
        if os.path.isdir(repo.local_root):
            subprocess.call(('find', repo.local_root, '-type', 'f',
                             '-name',repo.path_filter.get_temp_name('*'), '-delete'))

def repo_updated_callback(repo):
    if task_pool and task_pool.outstanding_task_count == 0:
        item_request = repo.authenticator.client.item(drive=repo.drive.id, path='/')
        task_pool.add_task(merge_dir.MergeDirectoryTask(
            repo=repo, task_pool=task_pool, rel_path='', item_request=item_request,
            assume_remote_unchanged=True, parent_remote_unchanged=False))
        logging.info('Added task to check delta update for Drive %s.', repo.drive.id)
    else:
        logging.error('Uninitialized task pool reference.')

@click.command(cls=daemonocle.cli.DaemonCLI,
               daemon_params={
                   'uid': context.user_uid,
                   'pidfile': pidfile,
                   # 'detach': False,
                   'shutdown_callback': shutdown_callback,
                   'workdir': os.getcwd(),
                   'stop_timeout': 60,
               })
def main():
    gc.enable()

    # When debugging, print to stdout.
    if '--debug' in sys.argv:
        context.loop.set_debug(True)
        context.set_logger(min_level=logging.DEBUG, path=None)
    else:
        context.set_logger(min_level=logging.INFO, path=context.config['logfile_path'])

    if context.config['start_delay_sec'] > 0:
        logging.info('Wait for %d seconds before starting.', context.config['start_delay_sec'])
        import time
        time.sleep(context.config['start_delay_sec'])

    # Initialize account information.
    all_accounts = get_repo_table(context)
    delete_temp_files(all_accounts)

    # Start task pool and task worker.
    init_task_pool_and_workers()

    # Start webhook.
    init_webhook()

    context.watcher = LocalRepositoryWatcher(task_pool=task_pool, loop=context.loop)

    try:
        context.loop.call_soon(gen_start_repo_tasks, all_accounts)
        context.loop.run_forever()
    finally:
        context.loop.close()

if __name__ == '__main__':
    main()


text:
package processors

import (
	"fmt"
	"io"
	"log"
	"strings"

	"github.com/linuxerwang/goats-html/symbolmgr"
	"github.com/linuxerwang/goats-html/util"
)

type GoForProcessor struct {
	BaseProcessor
	varName        string
	collectionName string
}

func (f *GoForProcessor) Process(writer io.Writer, ctx *TagContext) {
	// Start of a local scope
	io.WriteString(writer, "{\n")

	loopVarName := ""
	itemVar1 := ""
	itemVar2 := ""
	if strings.Contains(f.varName, ",") {
		parts := strings.Split(f.varName, ",")
		for _, val := range parts {
			if strings.Index(val, "@") > -1 {
				if loopVarName != "" {
					log.Fatalf("Only one @ loop var can be defined in go:for, found two \"@%s\" and \"%s\"\n",
						loopVarName, val)
				}
				loopVarName = util.TrimWhiteSpaces(val[1:])
			} else {
				if itemVar1 == "" {
					itemVar1 = util.TrimWhiteSpaces(val)
				} else if itemVar2 == "" {
					itemVar2 = util.TrimWhiteSpaces(val)
				} else {
					log.Fatalf("Only two loop var can be defined in go:for, found three \"@%s\", \"@%s\" and \"%s\"\n",
						itemVar1, itemVar2, val)
				}
			}
		}
	} else {
		itemVar1 = "_"
		itemVar2 = util.TrimWhiteSpaces(f.varName)
	}

	if itemVar1 == "" {
		log.Fatalf("Loop var is required for go:for but none was found.\n")
	}
	if itemVar2 == "" {
		itemVar2 = itemVar1
		itemVar1 = "_"
	}

	expr, err := ctx.RewriteExpression(f.collectionName)
	if err != nil {
		panic(err)
	}

	// Create a new symbol map.
	sm := make(map[string]*symbolmgr.Symbol)
	if itemVar1 != "" && itemVar1 != "_" {
		isPb := false
		if strings.HasSuffix(itemVar1, "[pb]") {
			isPb = true
			itemVar1 = util.TrimWhiteSpaces(itemVar1[:len(itemVar1)-4])
		}
		s := &symbolmgr.Symbol{
			Name: itemVar1,
			Type: symbolmgr.TypeFor,
			IsPb: isPb,
		}
		sm[itemVar1] = s
	}
	if itemVar2 != "" && itemVar2 != "_" {
		isPb := false
		if strings.HasSuffix(itemVar2, "[pb]") {
			isPb = true
			itemVar2 = util.TrimWhiteSpaces(itemVar2[:len(itemVar2)-4])
		}
		s := &symbolmgr.Symbol{
			Name: itemVar2,
			Type: symbolmgr.TypeFor,
			IsPb: isPb,
		}
		sm[itemVar2] = s
	}
	if loopVarName != "" && loopVarName != "_" {
		s := &symbolmgr.Symbol{
			Name: loopVarName,
			Type: symbolmgr.TypeFor,
			IsPb: false, // loop var is always not PB.
		}
		sm[loopVarName] = s
	}
	ctx.symMgr.Push(sm)

	switch ctx.OutputFormat {
	case "go":
		io.WriteString(writer, fmt.Sprintf("__loopItems := %s\n", expr))
		if loopVarName != "" {
			io.WriteString(writer, fmt.Sprintf("__loopTotal := len(__loopItems)\n"))
			io.WriteString(writer,
				fmt.Sprintf("%s := &runtime.LoopVar{\n"+
					"Total: __loopTotal,\n"+
					"Counter0: -1,\n"+
					"RevCounter: __loopTotal + 1,\n"+
					"RevCounter0: __loopTotal,\n"+
					"First: __loopTotal > 1,\n"+
					"}\n", loopVarName))
		}

		// Start of for loop.
		io.WriteString(writer,
			fmt.Sprintf("for %s, %s := range __loopItems {\n", util.TrimWhiteSpaces(itemVar1), util.TrimWhiteSpaces(itemVar2)))

		if loopVarName != "" {
			io.WriteString(writer, fmt.Sprintf("%s.Counter++\n", loopVarName))
			io.WriteString(writer, fmt.Sprintf("%s.Counter0++\n", loopVarName))
			io.WriteString(writer, fmt.Sprintf("%s.RevCounter--\n", loopVarName))
			io.WriteString(writer, fmt.Sprintf("%s.RevCounter0--\n", loopVarName))
			io.WriteString(writer, fmt.Sprintf("%s.Last = (%s.Total == %s.Counter)\n", loopVarName, loopVarName, loopVarName))
		}
	case "closure":
		if itemVar1 == "_" {
			itemVar1 = "__index"
		}
		io.WriteString(writer, fmt.Sprintf("var __loopItems = %s;\n", expr))
		io.WriteString(writer, "if (__loopItems) {\n")

		if loopVarName != "" {
			io.WriteString(writer, fmt.Sprintf("var __loopTotal = __loopItems.length;\n"))
			io.WriteString(writer,
				fmt.Sprintf("var %s = {\n"+
					"total: __loopTotal,\n"+
					"counter: 0,\n"+
					"counter0: -1,\n"+
					"revCounter: __loopTotal + 1,\n"+
					"revCounter0: __loopTotal,\n"+
					"first: __loopTotal > 1,\n"+
					"last: false\n"+
					"};\n", loopVarName))
		}

		// Start of for loop.
		ctx.pkgRefs.RefClosureRequire("goog.array")
		io.WriteString(writer, fmt.Sprintf("goog.array.forEach(__loopItems, function(%s, %s) {\n", util.TrimWhiteSpaces(itemVar2), util.TrimWhiteSpaces(itemVar1)))

		if loopVarName != "" {
			io.WriteString(writer, fmt.Sprintf("%s.counter++;\n", loopVarName))
			io.WriteString(writer, fmt.Sprintf("%s.counter0++;\n", loopVarName))
			io.WriteString(writer, fmt.Sprintf("%s.revCounter--;\n", loopVarName))
			io.WriteString(writer, fmt.Sprintf("%s.revCounter0--;\n", loopVarName))
			io.WriteString(writer, fmt.Sprintf("%s.last = (%s.total == %s.counter);\n", loopVarName, loopVarName, loopVarName))
		}
	}

	if f.next != nil {
		f.next.Process(writer, ctx)
	}

	if loopVarName != "" {
		switch ctx.OutputFormat {
		case "go":
			io.WriteString(writer, fmt.Sprintf("\n%s.First = false\n", loopVarName))
		case "closure":
			io.WriteString(writer, fmt.Sprintf("\n%s.first = false;\n", loopVarName))
		}
	}

	// End of for loop.
	switch ctx.OutputFormat {
	case "go":
		io.WriteString(writer, "}\n")
	case "closure":
		io.WriteString(writer, "}, this);\n")
		io.WriteString(writer, "}\n")
	}

	ctx.symMgr.Pop()

	// End of the local scope
	io.WriteString(writer, "}\n")
}

func NewForProcessor(forLine string) *GoForProcessor {
	varName, varVal := util.SplitVarDef(forLine)
	processor := &GoForProcessor{
		varName:        util.TrimWhiteSpaces(varName),
		collectionName: util.TrimWhiteSpaces(varVal),
	}
	return processor
}


text:
@interface iPadNavigationController : UINavigationController<FlipViewControllerDelegate>

- (id)init;

@end


text:
package us.gov.dod.standard.ssrf._3_1.metadata;

import java.math.BigInteger;
import java.util.Locale;
import java.util.Objects;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.*;
import us.gov.dod.standard.ssrf.EDatasetType;
import us.gov.dod.standard.ssrf._3_1.Common;
import us.gov.dod.standard.ssrf._3_1.metadata.lists.ListCCL;
import us.gov.dod.standard.ssrf._3_1.metadata.lists.ListCCY;

/**
 * A SSRF SERIAL number container with SSRF Standard Metadata Attributes.
 *

 * This data type handles SSRF serial number generation.
 *

 * Serial is composed of four parts separated by colons (":"). The maximum total
 * length is 29 characters (5+1+4+1+2+1+15).
 *

 *
Part 1 is the Country and is always REQUIRED. It contains one to five
 * alphabetic uppercase characters representing either the ITU country code or
 * the NATO Command code identifying the originator or organisation responsible
 * for maintaining the dataset, as listed in Code List CCY.

 *
Part 2 is the orgCode and is OPTIONAL. It may contain one to four
 * alphanumeric characters (no spaces nor special characters) representing a
 * code for an Organisation within the country or command. It will normally
 * indicate the organisation responsible for maintaining the dataset. Domain
 * naming is left at the discretion of each country, but should be managed by a
 * central authority in the country to allow deconfliction and uniqueness. It
 * should enable the location in the data repository where this dataset
 * information is stored.

 *
Part 3 is the Dataset Type and MUST contain a two-character code from the
 * table in the Introduction section identifying the type of dataset (LO for a
 * Location, etc).

 *
Part 4 is a Serial Identifier and is always REQUIRED. It contains one to
 * fifteen alphanumeric characters (including spaces and special characters),
 * whose meaning is left at the discretion of each domain manager.

 *

 *

 * Format is pattern (S29) with validation type SERIAL
 *

 * [XSD ERR REGEX] This data item MUST comply to the regular expression:
 * "[A-Z0-9-]{1,5}:\w{0,4}:[A-Z]{2}: \S{1,15}"
 *

 * @author Jesse Caulfield
 * @version SSRF 3.1.0, 10/02/14
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TSerial", propOrder = {"value"})
public class TSerial extends AMetadata<TSerial> implements IMetadataType, Comparable<TSerial> {

  /**
   * The SERIAL number string pattern.
   */
  private static final String PATTERN = "^([A-Z0-9-]{1,5}):(\\w{0,4}):([A-Z]{2}):(\\S{1,15})$";

  /**
   * The value to which the metadata attributes are associated.
   */
  @XmlValue
  protected String value;

  /**
   * The Serial number Country part (REQUIRED).
   *

   * Format is S5
   *

   * It contains one to five alphabetic uppercase characters representing either
   * the ITU country code or the NATO Command code identifying the originator or
   * organisation responsible for maintaining the dataset, as listed in Code
   * List CCY.
   */
  @XmlTransient
  private ListCCY country;
  /**
   * The instantiating class type (REQUIRED)
   *

   * Format is S2
   *

   * This determines the third part of the serial number
   */
  @XmlTransient
  private EDatasetType datasetType;
  /**
   * The serial number Organization code (OPTIONAL).
   *

   * It may contain one to four alphanumeric characters (no spaces nor special
   * characters) representing a code for an Organisation within the country or
   * command. It will normally indicate the organisation responsible for
   * maintaining the dataset. Domain naming is left at the discretion of each
   * country, but should be managed by a central authority in the country to
   * allow deconfliction and uniqueness. It should enable the location in the
   * data repository where this dataset information is stored.
   *

   * Format is S4
   */
  @XmlTransient
  private String organisation;
  /**
   * The serial number Serial identifier (REQUIRED).
   *

   * It contains one to fifteen alphanumeric characters (including spaces and
   * special characters), whose meaning is left at the discretion of each domain
   * manager.
   *

   * Format is S15
   *

   * Developer note: If the serial is set to NULL then a random serial
   * number is assigned.
   */
  @XmlTransient
  private String serial;

  /**
   * Construct a new data type instance with the indicated value.
   *

   * @param ssrfSerial a valid SSRF SERIAL string. Format is pattern (S29) with
   *                   validation type SERIAL: "[A-Z0-9-]{1,5}:\w{0,4}:[A-Z]{2}:
   *                   \S{1,15}"
   * @throws IllegalArgumentException if the value does not conform to the
   *                                  SERIAL format
   */
  public TSerial(String ssrfSerial) throws IllegalArgumentException {
    this.value = ssrfSerial;
    parse();
  }

  /**
   * Default no-arg constructor.
   */
  private TSerial() {
  }

  /**
   * Get a TSerial instance for the indicated class instance.
   *

   * The local is set to the current system default. The serial is
   * programmatically set to a time-sequenced, UUID-based 15-character snippet.
   * The organisation is left blank and may be set by th user.
   *

   * @param clazz a SSRF class type that extends Common
   * @return a TSerial instance
   * @throws IllegalArgumentException if the object instance does not extend
   *                                  Common
   */
  public static TSerial getInstance(Class<? extends Common<?>> clazz) {
    return new TSerial()
            .withLocale(Locale.getDefault())
            .withDatasetType(clazz)
            .withSerial(uuidSnippet());
  }

  /**
   * Internal helper method to generate a 15-character UUID-based alphanumeric
   * snippet.
   *

   * @return a 15-character UUID-based alphanumeric String
   */
  private static String uuidSnippet() {
    return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 14);
  }

  /**
   * Internal method to build the internal SERIAL number value.
   */
  private void format() {
    StringBuilder sb = new StringBuilder();
    sb.append(country != null ? country.name() : "")
            .append(":")
            .append(organisation != null ? organisation : "")
            .append(":")
            .append(datasetType != null ? datasetType.name() : "")
            .append(":")
            .append(serial != null ? serial : uuidSnippet());
    this.value = sb.toString();
  }

  /**
   * Internal method to parse a SERIAL number value and set the internal
   * components.
   *

   * @throws IllegalArgumentException if the value does not conform to the
   *                                  SERIAL format
   */
  private void parse() throws IllegalArgumentException {
    if (value != null && !value.isEmpty()) {
      Matcher m = Pattern.compile(PATTERN).matcher(value);
      if (m.find()) {
        setCountry(ListCCY.valueOf(m.group(1)));
        setOrganisation(m.group(2));
        setDatasetType(EDatasetType.valueOf(m.group(3)));
        setSerial(m.group(4));
      } else {
        throw new IllegalArgumentException("SERIAL format error " + PATTERN + " for \"" + value + "\"");
      }
    }
  }

  /**
   * Update the serial number with the component configurations.
   *

   * This method should typically be called after the serial number fields are
   * configured and (optionally) before exporting an SSRF message.
   *

   * @since 3.1.0
   */
  public void prepare() {
    format();
  }

  /**
   * Update the serial number to write the component configurations.
   *

   * This method should typically be called after the Common is imported from
   * XML.
   *

   * @since 3.1.0
   */
  public void postLoad() {
    parse();
  }

  /**
   * Set the data set class type. (Private)
   *

   * Developer note: The datasetType field is REQUIRED and MUST be set upon
   * TSerial object instantiation.
   *

   * @param datasetType an enumerated dataset class type
   */
  private void setDatasetType(EDatasetType datasetType) {
    this.datasetType = datasetType;
    format();
  }

  /**
   * Set the Serial number Country part (REQUIRED).
   *

   * @param country the data source country
   */
  public void setCountry(ListCCY country) {
    this.country = country;
    format();
  }

  /**
   * Set the Serial number Country part (REQUIRED).
   *

   * @param locale the data source country
   */
  public void setLocale(Locale locale) {
    this.country = ListCCY.valueOf(locale.getISO3Country());
    format();
  }

  /**
   * Set the serial number Organization code (OPTIONAL).
   *

   * @param organisation the organisation serial value to set
   */
  public void setOrganisation(String organisation) {
    if (organisation.length() > 4) {
      throw new IllegalArgumentException("String length violation S4 [0, 4]. Length is " + value.length() + " for \"" + value + "\"");
    }
    this.organisation = organisation;
    format();
  }

  /**
   * Set the serial number Serial identifier component. This returns part 4 of
   * the SSRF SERIAL number.
   *

   * It contains one to fifteen alphanumeric characters (including spaces and
   * special characters), whose meaning is left at the discretion of each domain
   * manager.
   *

   * @return serial the serial number Serial identifier.
   */
  public String getSerial() {
    return serial;
  }

  /**
   * Set the serial number Serial identifier component. This returns part 4 of
   * the SSRF SERIAL number.
   *

   * It contains one to fifteen alphanumeric characters (including spaces and
   * special characters), whose meaning is left at the discretion of each domain
   * manager.
   *

   * @return serial the serial number Serial identifier converted to a Long.
   *         NULL if not set.
   */
  public Long getSerialAsNumber() {
    return serial != null ? new BigInteger(serial).longValue() : null;
  }

  /**
   * Set the serial number Serial identifier.
   *

   * It contains one to fifteen alphanumeric characters (including spaces and
   * special characters), whose meaning is left at the discretion of each domain
   * manager.
   *

   * @param serial the serial number Serial identifier.
   */
  public void setSerial(String serial) {
    if (serial.length() > 15) {
      throw new IllegalArgumentException("String length violation S15 [1, 15]. Length is " + value.length() + " for \"" + value + "\"");
    }
    this.serial = serial;
    format();
  }

  /**
   * Set the serial number Serial identifier as a Long Number instance.
   *

   * It contains one to fifteen alphanumeric characters (including spaces and
   * special characters), whose meaning is left at the discretion of each domain
   * manager.
   *

   * Developer note: The maximum number value is 15 digits (1E15). This should
   * accommodate most everyday instances including millisecond time stamps (12
   * digits).
   *

   * @param number the serial number Serial identifier as an unsigned number up
   *               to 1E15.
   */
  public void setSerial(Long number) {
    BigInteger bi = new BigInteger(String.valueOf(number));
    if (getDigitCount(bi) > 15) {
      throw new IllegalArgumentException("Serial value violation. Maximum " + value.length() + " digits for \"" + value + "\"");
    } else if (number < 0) {
      throw new IllegalArgumentException("Serial value violation S15 [1, 15]. Numeric serial numbers must be unsigned.");
    }
    this.serial = bi.toString();
    format();
  }

  /**
   * Gets the SSRF SERIAL number value.
   *

   * Calls {@link #format()} first to ensure the returned value reflects the
   * most recent changes to the serial components.
   *

   * @return the value of the value property.
   */
  @Override
  public String getValue() {
    format();
    return value;
  }

  /**
   * Sets the SSRF SERIAL number value.
   *

   * If the input value is not null this method attempts to parse the serial
   * number into its component parts and set the internal fields accordingly.
   *

   * @param value a valid SSRF SERIAL string. Format is pattern (S29) with
   *              validation type SERIAL: "[A-Z0-9-]{1,5}:\w{0,4}:[A-Z]{2}:
   *              \S{1,15}"
   * @throws IllegalArgumentException if the value does not conform to the
   *                                  SERIAL format
   */
  public void setValue(String value) {
    this.value = value;
    parse();
  }

  /**
   * Determine if the Value is configured.
   *

   * @return TRUE if the field is set, FALSE if the field is null
   */
  public boolean isSetValue() {
    return (this.value != null);
  }

  /**
   * Sets the SSRF SERIAL number value.
   *

   * @param value a valid SSRF SERIAL string. Format is pattern (S29) with
   *              validation type SERIAL: "[A-Z0-9-]{1,5}:\w{0,4}:[A-Z]{2}:
   *              \S{1,15}"
   * @return this TSerial instance
   */
  public TSerial withValue(String value) {
    setValue(value);
    return this;
  }

  /**
   * Set the Serial number Country part (REQUIRED).
   *

   * Format is S5
   *

   * @param value the data source country
   * @return The current TSerial object instance
   */
  public TSerial withCountry(ListCCY value) {
    setCountry(value);
    return this;
  }

  /**
   * Set the Serial number Country part (REQUIRED).
   *

   * Format is S5
   *

   * @param value the data source country
   * @return The current TSerial object instance
   */
  public TSerial withLocale(Locale value) {
    setLocale(value);
    return this;
  }

  /**
   * Set the class type. (Private)
   *

   * Developer note: The datasetType field is REQUIRED and MUST be set upon
   * TSerial object instantiation.
   *

   * @param value a SSRF class type or instance
   * @return the current serial instance
   */
  private TSerial withDatasetType(Class<? extends Common<?>> value) {
    setDatasetType(EDatasetType.fromInstance(value));
    return this;
  }

  /**
   * Set the serial number Organization code (OPTIONAL).
   *

   * Format is S4
   *

   * @param value the serial number Organization
   * @return The current TSerial object instance
   */
  public TSerial withOrganisation(String value) {
    setOrganisation(value != null ? value.toUpperCase(Locale.getDefault()) : "");
    return this;
  }

  /**
   * Set the serial number Serial identifier (REQUIRED).
   *

   * Format is S15
   *

   * @param value the serial number Serial identifier
   * @return The current TSerial object instance
   * @throws IllegalArgumentException if the input value is too long (> 15
   *                                  characters)
   */
  public TSerial withSerial(String value) {
    setSerial(value);
    return this;
  }

  /**
   * Set the serial number Serial identifier (REQUIRED) as a Long Number
   * instance.
   *

   * @param value the serial number Serial identifier
   * @return The current TSerial object instance
   */
  public TSerial withSerial(Long value) {
    setSerial(value);
    return this;
  }

  /**
   * Internal helper method to get the number of digits from a BigInteger
   * instance.
   *

   * @param number a BigInteger number instance.
   * @return the total number of digits in the number.
   */
  private int getDigitCount(BigInteger number) {
    double factor = Math.log(2) / Math.log(10);
    int digitCount = (int) (factor * number.bitLength() + 1);
    if (BigInteger.TEN.pow(digitCount - 1).compareTo(number) > 0) {
      return digitCount - 1;
    }
    return digitCount;
  }

  /**
   * Determine if the required fields in this SSRF data type instance are set.
   *

   * {@link TSerial} requires {@link ListCCL cls} and {@link String value}
   *

   * Note that this method only checks for the presence of required information;
   * this method does not validate the information format.
   *

   * @return TRUE if required fields are set, otherwise FALSE
   */
  @Override
  public boolean isSet() {
    return super.isSet() && isSetValue();
  }

  /**
   * Gets the SSRF SERIAL number value.
   *

   * Calls {@link #format()} first to ensure the returned value reflects the
   * most recent changes to the serial components.
   *

   * This is a shortcut to {@link #getValue()}.
   *

   * @return the formatted SSRF SERIAL number value.
   */
  @Override
  public String toString() {
    return getValue();
  }

  //<editor-fold defaultstate="collapsed" desc="Hashcode Equals and Comparable">
  /**
   * Hash code is based upon the user-configured serial number portion of the
   * value.
   *

   * @return a hash code of the user-configured serial number portion
   */
  @Override
  public int hashCode() {
    if (this.serial == null) {
      return super.hashCode();
    }
    int hash = 5;
    hash = 47 * hash + Objects.hashCode(this.value);
    hash = 47 * hash + Objects.hashCode(this.serial);
    return hash;
  }

  /**
   * Equality is based upon the user-configured serial number portion of the
   * value.
   *

   * @param obj the other object to compare
   * @return TRUE if the serial number components are equal
   */
  @Override
  public boolean equals(Object obj) {
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    /**
     * If the whole value matches then confirm equality. This is triggered when
     * unmarshaling from XML.
     */
    if (Objects.equals(this.value, ((TSerial) obj).getValue())) {
      return true;
    }
    /**
     * If the serial-component matches then also confirm equality. This is
     * triggered when marshaling TO xml AND also accommodates resetting the
     * country code.
     */
    return Objects.equals(this.serial, ((TSerial) obj).getSerial());
  }

  /**
   * Comparison and sorting is alphabetical based upon the String value.
   *

   * @param o the other TString value
   * @return alphabetical sort order
   */
  @Override
  public int compareTo(TSerial o) {
    if (o == null) {
      return 1;
    }
    if (value == null) {
      return -1;
    }
    return value.compareTo(o.getValue());
  }//</editor-fold>
}


text:
package project.type1.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class BaseViewController {

	@RequestMapping(value = { "", "/" }, method = RequestMethod.GET)
    public ModelAndView indexPage() {
		ModelAndView	mav	= new ModelAndView("layouts/main");
        mav.addObject("greeting", "Hi, Welcome to mysite. ");
        return mav;
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(ModelMap model) {
    	model.addAttribute("user", getPrincipal());
    	return "layouts/login1";
    }

    @RequestMapping(value="/logout", method = RequestMethod.GET)
       public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
          Authentication auth = SecurityContextHolder.getContext().getAuthentication();
          if (auth != null){
             new SecurityContextLogoutHandler().logout(request, response, auth);
          }
          return "redirect:/login?logout";
       }

    @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
    public String accessDeniedPage(ModelMap model) {
        model.addAttribute("user", getPrincipal());
        return "accessDenied";
    }

//	// Login form with error
//	@RequestMapping("/login-error")
//	public String loginError(Model model) {
//		model.addAttribute("loginError", true);
//		return "login";
//	}

    private String getPrincipal(){
        String userName = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            userName = ((UserDetails)principal).getUsername();
        } else {
            userName = principal.toString();
        }
        return userName;
    }

}


text:
@interface YALOrderStepperSupplementaryView : YALBaseSupplementaryView

@property (nonatomic, assign) IBInspectable CGSize stepperSize;
@property (nonatomic, assign) IBInspectable NSUInteger value;
@property (nonatomic, assign) IBInspectable NSUInteger minimumValue;
@property (nonatomic, assign) IBInspectable NSUInteger maximumValue;

@end


text:
import UrlSchema from '../schemas/urlSchema';

export default class ShortUrlRepository {
  /**
   * @name getShortUrlById
   * @param shortUrlId {int}
   * @return {Promise}
   */
  getShortUrlById(shortUrlId, referer) {
    return UrlSchema.findOneAndUpdate({
      shortUrl: shortUrlId
    }, {
      $inc: {'hits.count': 1},
      $set: {'hits.lastHit': new Date()},
      $push: {requests: referer}
    });
  }

  /**
   * @name persist
   * @param ShortUrl {Object} Short URL schema
   * @return {Promise} Persist a Short URL and returns a promise
   */
  persist(ShortUrl) {
    return ShortUrl.save();
  }

  /**
   * @name dataTransferObject
   * @return {Object} Format response to be exposed
   */
  dataTransferObject(data) {
    return {
      id: data.id,
      url: data.url,
      shortUrl: `${data.shortUrl}`,
      hits: data.hits
    };
  }
}


text:
<?php

namespace Sebastienheyd\Boilerplate\Events;

use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Sebastienheyd\Boilerplate\Models\User;

class UserSaved
{
    use Dispatchable;
    use InteractsWithSockets;
    use SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        RefreshDatatable::broadcast('users')->toOthers();
    }
}


text:
Ansible Logstash Role
##########################
:tags: rackspace, rpc, cloud, ansible, logstash
:category: \*nix

Role for the deployment of Logstash within Rackspace Private Cloud.

.. code-block:: yaml

    - name: Setup Logstash host
      hosts: logstash_all
      user: root
      roles:
        - { role: "logstash" }


text:
package com.github.protobufel.grammar;

import java.io.File;

import org.antlr.v4.gui.TestRig;

public class GUITestRig1 {
  private static final int ARGS_INPUT_FILE_INDEX = 0;
  private static final int ARGS_GRAMMAR_NAME_INDEX = 1;
  private static final int ARGS_START_RULE_INDEX = 2;

  public static void main(final String[] args) throws Exception {
    String grammarName = "Proto";
    String startRule = "proto";
    String inputFile = "test0.proto";

    if (args.length > ARGS_INPUT_FILE_INDEX) {
      inputFile = args[ARGS_INPUT_FILE_INDEX];
    } else if (args.length > ARGS_GRAMMAR_NAME_INDEX) {
      grammarName = args[ARGS_GRAMMAR_NAME_INDEX];
    } else if (args.length > ARGS_START_RULE_INDEX) {
      startRule = args[ARGS_START_RULE_INDEX];
    }

    final GUITestRig1 testRig = new GUITestRig1();
    final String[] argsuments = testRig.setUp(grammarName, startRule, inputFile);
    TestRig.main(argsuments);
  }

  public String[] setUp(final String grammarName, final String startRule, final String inputFile)
      throws Exception {
    return new String[] {getClass().getPackage().getName() + "." + grammarName, startRule,
        "-tokens", "-tree", "-gui", "-trace", "-diagnostics", "-SLL",
        getResourceFileName(inputFile)};
  }

  private String getResourceFileName(final String resource) {
    final File file = new File(resource);

    try {
      if (file.isAbsolute()) {
        return file.getCanonicalPath();
      } else {
        return getClass().getResource(resource).toURI().toURL().toString();
      }
    } catch (final Exception e) {
      throw new RuntimeException(e);
    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Fusarium osiliense Bres. & Vestergr.

### Remarks
null


text:
'use strict';

var chai   = require('chai');
var expect = chai.expect;

var constants = require('test/unit/fixtures/constants');

var elements = require('lib/common/elements')(constants);

var Stats = require('lib/common/components/stats')(constants);

var elems = {
  directory: elements.directory(parseInt('777', 8)),
  file:      elements.file(parseInt('777', 8), 'Hello'),
  symlink:   elements.symlink(parseInt('777', 8), '/')
};

describe('common/components/stats', function () {

  it('should expose a constructor', function () {
    expect(Stats).to.be.a('function');
    expect(new Stats(elems.file)).to.be.an.instanceOf(Stats);
  });

  it('should create stats from element', function () {
    Object.keys(elems).forEach(function (key) {
      var element = elems[key];

      var stats = new Stats(element);

      expect(stats).to.be.an.instanceOf(Stats);

      expect(stats.dev).to.equal(1);
      expect(stats.ino).to.equal(element.get('inode'));
      expect(stats.mode).to.equal(element.get('mode') + element.get('type'));
      expect(stats.nlink).to.equal(element.get('nlink'));
      expect(stats.uid).to.equal(element.get('uid'));
      expect(stats.gid).to.equal(element.get('gid'));
      expect(stats.rdev).to.equal(0);
      expect(stats.size).to.equal(0);
      expect(stats.blksize).to.equal(512);
      expect(stats.blocks).to.equal(0);
      expect(stats.atime).to.equal(element.get('atime'));
      expect(stats.mtime).to.equal(element.get('mtime'));
      expect(stats.ctime).to.equal(element.get('ctime'));

      expect(stats.birthtime).to.be.an('undefined');
      expect(stats.atimeMs).to.be.an('undefined');
      expect(stats.mtimeMs).to.be.an('undefined');
      expect(stats.ctimeMs).to.be.an('undefined');
      expect(stats.birthtimeMs).to.be.an('undefined');
    });
  });

  it('should optionally expose birthtime', function () {
    var StatsB = require('lib/common/components/stats')(constants, {
      birthtime: true
    });

    Object.keys(elems).forEach(function (key) {
      var element = elems[key];

      var stats = new StatsB(element);

      expect(stats).to.be.an.instanceOf(StatsB);

      expect(stats.birthtime).to.equal(element.get('birthtime'));
    });
  });

  it('should optionally expose times in milliseconds', function () {
    var StatsB = require('lib/common/components/stats')(constants, {
      milliseconds: true
    });

    Object.keys(elems).forEach(function (key) {
      var element = elems[key];

      var stats = new StatsB(element);

      expect(stats).to.be.an.instanceOf(StatsB);

      expect(stats.atimeMs).to.equal(element.get('atime').getTime());
      expect(stats.mtimeMs).to.equal(element.get('mtime').getTime());
      expect(stats.ctimeMs).to.equal(element.get('ctime').getTime());

      expect(stats.birthtimeMs).to.be.an('undefined');
    });
  });

  it('should optionally expose birthtime in milliseconds', function () {
    var StatsB = require('lib/common/components/stats')(constants, {
      birthtime:    true,
      milliseconds: true
    });

    Object.keys(elems).forEach(function (key) {
      var element = elems[key];

      var stats = new StatsB(element);

      expect(stats).to.be.an.instanceOf(StatsB);

      expect(stats.birthtimeMs).to.equal(element.get('birthtime').getTime());
    });
  });

  describe('isDirectory()', function () {

    it('should return true on directory', function () {
      expect(new Stats(elems.directory).isDirectory()).to.equal(true);
    });

    it('should return false on other types', function () {
      expect(new Stats(elems.file).isDirectory()).to.equal(false);
      expect(new Stats(elems.symlink).isDirectory()).to.equal(false);
    });

  });

  describe('isFile()', function () {

    it('should return true on file', function () {
      expect(new Stats(elems.file).isFile()).to.equal(true);
    });

    it('should return false on other types', function () {
      expect(new Stats(elems.directory).isFile()).to.equal(false);
      expect(new Stats(elems.symlink).isFile()).to.equal(false);
    });

  });

  describe('isBlockDevice()', function () {

    it('should return false on all types', function () {
      expect(new Stats(elems.directory).isBlockDevice()).to.equal(false);
      expect(new Stats(elems.file).isBlockDevice()).to.equal(false);
      expect(new Stats(elems.symlink).isBlockDevice()).to.equal(false);
    });

  });

  describe('isCharacterDevice()', function () {

    it('should return false on all types', function () {
      expect(new Stats(elems.directory).isCharacterDevice()).to.equal(false);
      expect(new Stats(elems.file).isCharacterDevice()).to.equal(false);
      expect(new Stats(elems.symlink).isCharacterDevice()).to.equal(false);
    });

  });

  describe('isSymbolicLink()', function () {

    it('should return true on symlink', function () {
      expect(new Stats(elems.symlink).isSymbolicLink()).to.equal(true);
    });

    it('should return false on other types', function () {
      expect(new Stats(elems.directory).isSymbolicLink()).to.equal(false);
      expect(new Stats(elems.file).isSymbolicLink()).to.equal(false);
    });

  });

  describe('isFIFO()', function () {

    it('should return false on all types', function () {
      expect(new Stats(elems.directory).isFIFO()).to.equal(false);
      expect(new Stats(elems.file).isFIFO()).to.equal(false);
      expect(new Stats(elems.symlink).isFIFO()).to.equal(false);
    });

  });

  describe('isSocket()', function () {

    it('should return false on all types', function () {
      expect(new Stats(elems.directory).isSocket()).to.equal(false);
      expect(new Stats(elems.file).isSocket()).to.equal(false);
      expect(new Stats(elems.symlink).isSocket()).to.equal(false);
    });

  });

});


text:
PODCAST AMIGOS

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>

Home

Temáticas

Países

Agrega Tu Podcast

Unión Podcastera

      <form action="/search/index.html" method="get">
          <input type="text" id="search-box" name="query" t><input type="submit" value="Buscar">

      </form>


text:
#ifndef HTMLMetaCharsetParser_h
#define HTMLMetaCharsetParser_h

#include "core/html/parser/HTMLToken.h"
#include "platform/text/SegmentedString.h"
#include "wtf/Noncopyable.h"
#include "wtf/text/TextCodec.h"
#include "wtf/text/TextEncoding.h"

namespace WebCore {

class HTMLTokenizer;

class HTMLMetaCharsetParser {
    WTF_MAKE_NONCOPYABLE(HTMLMetaCharsetParser); WTF_MAKE_FAST_ALLOCATED;
public:
    static PassOwnPtr<HTMLMetaCharsetParser> create() { return adoptPtr(new HTMLMetaCharsetParser()); }

    ~HTMLMetaCharsetParser();

    // Returns true if done checking, regardless whether an encoding is found.
    bool checkForMetaCharset(const char*, size_t);

    const WTF::TextEncoding& encoding() { return m_encoding; }

private:
    HTMLMetaCharsetParser();

    bool processMeta();

    OwnPtr<HTMLTokenizer> m_tokenizer;
    OwnPtr<TextCodec> m_assumedCodec;
    SegmentedString m_input;
    HTMLToken m_token;
    bool m_inHeadSection;

    bool m_doneChecking;
    WTF::TextEncoding m_encoding;
};

}
#endif


text:
module AttributedObjectHelpers
  class HashUtil
    def self.symbolize_keys(hash)
      new_hash = {}

      hash.each { |k, v|
        if k.respond_to?(:to_sym)
          new_hash[k.to_sym] = v
        else
          new_hash[k] = v
        end
      }

      return new_hash
    end

    def self.slice(hash, keys)
      selected_keys = keys & hash.keys
      Hash[ [selected_keys, hash.values_at(*selected_keys)].transpose]
    end
  end
end


text:
import argparse
import sys
from typing import Any

from kafka.errors import UnknownMemberIdError

from .offset_manager import OffsetWriter
from kafka_utils.util.client import KafkaToolClient
from kafka_utils.util.config import ClusterConfig
from kafka_utils.util.offsets import advance_consumer_offsets

class OffsetAdvance(OffsetWriter):

    @classmethod
    def setup_subparser(cls, subparsers: Any) -> None:
        parser_offset_advance = subparsers.add_parser(
            "offset_advance",
            description="Advance consumer offsets for the specified consumer "
            "group to the latest message in the topic partition",
            add_help=False
        )
        parser_offset_advance.add_argument(
            "-h", "--help", action="help",
            help="Show this help message and exit."
        )
        parser_offset_advance.add_argument(
            'groupid',
            help="Consumer Group ID whose consumer offsets shall be advanced."
        )
        parser_offset_advance.add_argument(
            "--topic",
            help="Kafka topic whose offsets shall be manipulated. If no topic "
            "is specified, offsets from all topics that the consumer is "
            "subscribed to, shall be advanced."
        )
        parser_offset_advance.add_argument(
            "--partitions", nargs='+', type=int,
            help="List of partitions within the topic. If no partitions are "
            "specified, offsets from all partitions of the topic shall "
            "be advanced."
        )
        parser_offset_advance.add_argument(
            '--force',
            action='store_true',
            help="Force the offset of the group to be committed even if "
            "it does not already exist."
        )
        parser_offset_advance.set_defaults(command=cls.run)

    @classmethod
    def run(cls, args: argparse.Namespace, cluster_config: ClusterConfig) -> None:
        # Setup the Kafka client
        client = KafkaToolClient(cluster_config.broker_list)
        client.load_metadata_for_topics()

        topics_dict = cls.preprocess_args(
            args.groupid,
            args.topic,
            args.partitions,
            cluster_config,
            client,
            force=args.force,
            use_admin_client=args.use_admin_client,
        )
        try:
            advance_consumer_offsets(
                client,
                args.groupid,
                topics_dict,
            )
        except TypeError:
            print(
                "Error: Badly formatted input, please re-run command ",
                "with --help option.", file=sys.stderr
            )
            raise
        except UnknownMemberIdError:
            print(
                "Unable to advance offsets for group '{group_name}' from topic '{topic_name}'. \
                    You must ensure none of the consumers with this consumer group id are running before \
                    trying to advance the offsets stored in Kafka for this consumer group. Try stopping all \
                    of your consumers.".format(group_name=args.groupid, topic_name=args.topic),
            )
            raise

        client.close()