text:
<?php

namespace Oro\Bundle\ActionBundle\Tests\Unit\Model;

use Doctrine\Common\Collections\ArrayCollection;

use Oro\Bundle\ActionBundle\Model\ActionData;
use Oro\Bundle\ActionBundle\Model\Assembler\AttributeAssembler;
use Oro\Bundle\ActionBundle\Model\Assembler\FormOptionsAssembler;
use Oro\Bundle\ActionBundle\Model\Attribute;
use Oro\Bundle\ActionBundle\Model\Operation;
use Oro\Bundle\ActionBundle\Model\OperationDefinition;

use Oro\Component\Action\Action\ActionFactory;
use Oro\Component\Action\Action\ActionInterface;
use Oro\Component\Action\Condition\Configurable as ConfigurableCondition;
use Oro\Component\ConfigExpression\ExpressionFactory;

/**
 * @SuppressWarnings(PHPMD.TooManyMethods)
 */
class OperationTest extends \PHPUnit_Framework_TestCase
{
    /** @var \PHPUnit_Framework_MockObject_MockObject|OperationDefinition */
    protected $definition;

    /** @var \PHPUnit_Framework_MockObject_MockObject|ActionFactory */
    protected $actionFactory;

    /** @var \PHPUnit_Framework_MockObject_MockObject|ExpressionFactory */
    protected $conditionFactory;

    /** @var \PHPUnit_Framework_MockObject_MockObject|AttributeAssembler */
    protected $attributeAssembler;

    /** @var \PHPUnit_Framework_MockObject_MockObject|FormOptionsAssembler */
    protected $formOptionsAssembler;

    /** @var Operation */
    protected $operation;

    /** @var ActionData */
    protected $data;

    protected function setUp()
    {
        $this->definition = $this->getMockBuilder('Oro\Bundle\ActionBundle\Model\OperationDefinition')
            ->disableOriginalConstructor()
            ->getMock();

        $this->actionFactory = $this->getMockBuilder('Oro\Component\Action\Action\ActionFactory')
            ->disableOriginalConstructor()
            ->getMock();

        $this->conditionFactory = $this->getMockBuilder('Oro\Component\ConfigExpression\ExpressionFactory')
            ->disableOriginalConstructor()
            ->getMock();

        $this->attributeAssembler = $this->getMockBuilder('Oro\Bundle\ActionBundle\Model\Assembler\AttributeAssembler')
            ->disableOriginalConstructor()
            ->getMock();

        $this->formOptionsAssembler = $this->getMockBuilder(
            'Oro\Bundle\ActionBundle\Model\Assembler\FormOptionsAssembler'
        )->disableOriginalConstructor()->getMock();

        $this->operation = new Operation(
            $this->actionFactory,
            $this->conditionFactory,
            $this->attributeAssembler,
            $this->formOptionsAssembler,
            $this->definition
        );

        $this->data = new ActionData();
    }

    public function testGetName()
    {
        $this->definition->expects($this->once())
            ->method('getName')
            ->willReturn('test name');

        $this->assertEquals('test name', $this->operation->getName());
    }

    public function testIsEnabled()
    {
        $this->definition->expects($this->once())
            ->method('isEnabled')
            ->willReturn(true);

        $this->assertEquals(true, $this->operation->isEnabled());
    }

    public function testGetDefinition()
    {
        $this->assertInstanceOf('Oro\Bundle\ActionBundle\Model\OperationDefinition', $this->operation->getDefinition());
    }

    public function testInit()
    {
        $config = [
            ['form_init', ['form_init']],
        ];

        $actions = [
            'form_init' => $this->createAction($this->once(), $this->data),
        ];

        $this->definition->expects($this->any())
            ->method('getActions')
            ->willReturnMap($config);

        $this->actionFactory->expects($this->any())
            ->method('create')
            ->willReturnCallback(function ($type, $config) use ($actions) {
                return $actions[$config[0]];
            });

        $this->operation->init($this->data);
    }

    /**
     * @param ActionData $data
     * @param array $config
     * @param array $actions
     * @param array $conditions
     * @param string $operationName
     * @param string $exceptionMessage
     *
     * @dataProvider executeProvider
     */
    public function testExecute(
        ActionData $data,
        array $config,
        array $actions,
        array $conditions,
        $operationName,
        $exceptionMessage = ''
    ) {
        $this->definition->expects($this->any())->method('getName')->willReturn($operationName);
        $this->definition->expects($this->any())->method('getConditions')->will($this->returnValueMap($config));

        $this->definition->expects($this->any())
            ->method('getActions')
            ->willReturnCallback(function ($name) {
                return [$name];
            });

        $this->actionFactory->expects($this->any())
            ->method('create')
            ->willReturnCallback(function ($type, $config) use ($actions) {
                return $actions[$config[0]];
            });

        $this->conditionFactory->expects($this->any())
            ->method('create')
            ->willReturnCallback(function ($type, $config) use ($conditions) {
                return $conditions[$config[0]];
            });

        if ($exceptionMessage) {
            $this->setExpectedException(
                'Oro\Bundle\ActionBundle\Exception\ForbiddenOperationException',
                $exceptionMessage
            );
        }

        $errors = new ArrayCollection();

        $this->assertArrayNotHasKey('errors', $data);

        $this->operation->execute($data, $errors);

        $this->assertEmpty($errors->toArray());

        if ($exceptionMessage) {
            $this->assertArrayHasKey('errors', $data);
            $this->assertSame($errors, $data['errors']);
        }
    }

    /**
     * @return array
     */
    public function executeProvider()
    {
        $data = new ActionData();

        $config = [
            ['preactions', ['preactions']],
            ['actions', ['actions']],
            ['preconditions', ['preconditions']],
            ['conditions', ['conditions']],
        ];

        return [
            '!isPreConditionAllowed' => [
                'data' => $data,
                'config' => $config,
                'actions' => [
                    'preactions' => $this->createAction($this->once(), $data),
                    'actions' => $this->createAction($this->never(), $data),
                ],
                'conditions' => [
                    'preconditions' => $this->createCondition($this->once(), $data, false),
                    'conditions' => $this->createCondition($this->never(), $data, true),
                ],
                'operationName' => 'TestName1',
                'exception' => 'Operation "TestName1" is not allowed.'
            ],
            '!isConditionAllowed' => [
                'data' => $data,
                'config' => $config,
                'actions' => [
                    'preactions' => $this->createAction($this->once(), $data),
                    'actions' => $this->createAction($this->never(), $data),
                ],
                'conditions' => [
                    'preconditions' => $this->createCondition($this->once(), $data, true),
                    'conditions' => $this->createCondition($this->once(), $data, false),
                ],
                'operationName' => 'TestName2',
                'exception' => 'Operation "TestName2" is not allowed.'
            ],
            'isAllowed' => [
                'data' => $data,
                'config' => $config,
                'actions' => [
                    'preactions' => $this->createAction($this->once(), $data),
                    'actions' => $this->createAction($this->once(), $data),
                ],
                'conditions' => [
                    'preconditions' => $this->createCondition($this->once(), $data, true),
                    'conditions' => $this->createCondition($this->once(), $data, true),
                ],
                'operationName' => 'TestName3',
            ],
        ];
    }

    /**
     * @param array $inputData
     * @param array $expectedData
     *
     * @dataProvider isAvailableProvider
     */
    public function testIsAvailable(array $inputData, array $expectedData)
    {
        $this->definition->expects($this->any())
            ->method('getConditions')
            ->will($this->returnValueMap($inputData['config']['conditions']));

        $this->definition->expects($this->any())
            ->method('getFormOptions')
            ->willReturn($inputData['config']['form_options']);

        $this->conditionFactory->expects($expectedData['conditionFactory'])
            ->method('create')
            ->willReturnCallback(function ($type, $config) use ($inputData) {
                return $inputData['conditions'][$config[0]];
            });

        $this->assertEquals($expectedData['available'], $this->operation->isAvailable($inputData['data']));
    }

    /**
     * @return array
     *
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function isAvailableProvider()
    {
        $data = new ActionData();

        return [
            'no conditions' => [
                'input' => [
                    'data' => $data,
                    'config' => [
                        'conditions' => [],
                        'form_options' => [],
                    ],
                ],
                'expected' => [
                    'conditionFactory' => $this->never(),
                    'available' => true,
                    'errors' => [],
                ],
            ],
            '!isPreConditionAllowed' => [
                'input' => [
                    'data' => $data,
                    'config' => [
                        'conditions' => [
                            ['preconditions', ['preconditions']],
                            ['conditions', ['conditions']],
                        ],
                        'form_options' => [],
                    ],
                    'conditions' => [
                        'preconditions' => $this->createCondition($this->once(), $data, false),
                        'conditions' => $this->createCondition($this->never(), $data, true),
                    ],
                ],
                'expected' => [
                    'conditionFactory' => $this->exactly(1),
                    'available' => false,
                ],
            ],
            '!isConditionAllowed' => [
                'input' => [
                    'data' => $data,
                    'config' => [
                        'conditions' => [
                            ['preconditions', ['preconditions']],
                            ['conditions', ['conditions']],
                        ],
                        'form_options' => [],
                    ],
                    'conditions' => [
                        'preconditions' => $this->createCondition($this->once(), $data, true),
                        'conditions' => $this->createCondition($this->once(), $data, false),
                    ],
                ],
                'expected' => [
                    'conditionFactory' => $this->exactly(2),
                    'available' => false,
                    'errors' => ['error3', 'error4'],
                ],
            ],
            'allowed' => [
                'input' => [
                    'data' => $data,
                    'config' => [
                        'conditions' => [
                            ['preconditions', ['preconditions']],
                            ['conditions', ['conditions']],
                        ],
                        'form_options' => [],
                    ],
                    'conditions' => [
                        'preconditions' => $this->createCondition($this->once(), $data, true),
                        'conditions' => $this->createCondition($this->once(), $data, true),
                    ],
                ],
                'expected' => [
                    'conditionFactory' => $this->exactly(2),
                    'available' => true,
                    'errors' => [],
                ],
            ],
            'hasForm and no conditions' => [
                'input' => [
                    'data' => $data,
                    'config' => [
                        'conditions' => [],
                        'form_options' => [
                            'attribute_fields' => [
                                'attribute1' => [],
                            ],
                        ],
                    ],
                ],
                'expected' => [
                    'conditionFactory' => $this->never(),
                    'available' => true,
                    'errors' => [],
                ],
            ],
            'hasForm and !isPreConditionAllowed' => [
                'input' => [
                    'data' => $data,
                    'config' => [
                        'conditions' => [
                            ['preconditions', ['preconditions']],
                            ['conditions', ['conditions']],
                        ],
                        'form_options' => [
                            'attribute_fields' => [
                                'attribute2' => [],
                            ],
                        ],
                    ],
                    'conditions' => [
                        'preconditions' => $this->createCondition($this->once(), $data, false),
                        'conditions' => $this->createCondition($this->never(), $data, true),
                    ],
                ],
                'expected' => [
                    'conditionFactory' => $this->exactly(1),
                    'available' => false,
                ],
            ],
            'hasForm and allowed' => [
                'input' => [
                    'data' => $data,
                    'config' => [
                        'conditions' => [
                            ['preconditions', ['preconditions']],
                            ['conditions', ['conditions']],
                        ],
                        'form_options' => [
                            'attribute_fields' => [
                                'attribute3' => [],
                            ],
                        ],
                    ],
                    'conditions' => [
                        'preconditions' => $this->createCondition($this->once(), $data, true),
                        'conditions' => $this->createCondition($this->never(), $data, true),
                    ],
                ],
                'expected' => [
                    'conditionFactory' => $this->exactly(1),
                    'available' => true,
                    'errors' => [],
                ],
            ],
        ];
    }

    /**
     * @param array $input
     * @param array $expected
     *
     * @dataProvider getFormOptionsDataProvider
     */
    public function testGetFormOptions(array $input, array $expected)
    {
        $this->definition->expects($this->once())
            ->method('getFormOptions')
            ->willReturn($input);

        if ($input) {
            $attributes = ['attribute' => ['label' => 'attr_label']];

            $this->definition->expects($this->once())
                ->method('getAttributes')
                ->willReturn($attributes);

            $attribute = new Attribute();
            $attribute->setName('test_attr');

            $this->attributeAssembler->expects($this->once())
                ->method('assemble')
                ->with($this->data, $attributes)
                ->willReturn(new ArrayCollection(['test_attr' => $attribute]));

            $this->formOptionsAssembler->expects($this->once())
                ->method('assemble')
                ->with($input, new ArrayCollection(['test_attr' => $attribute]))
                ->willReturn($expected);
        }

        $this->assertEquals($expected, $this->operation->getFormOptions($this->data));
    }

    /**
     * @param array $input
     * @param bool $expected
     *
     * @dataProvider hasFormProvider
     */
    public function testHasForm(array $input, $expected)
    {
        $this->definition->expects($this->once())
            ->method('getFormOptions')
            ->willReturn($input);
        $this->assertEquals($expected, $this->operation->hasForm());
    }

    /**
     * @return array
     */
    public function hasFormProvider()
    {
        return [
            'empty' => [
                'input' => [],
                'expected' => false,
            ],
            'empty attribute_fields' => [
                'input' => ['attribute_fields' => []],
                'expected' => false,
            ],
            'filled' => [
                'input' => ['attribute_fields' => ['attribute' => []]],
                'expected' => true,
            ],
        ];
    }

    /**
     * @return array
     */
    public function getFormOptionsDataProvider()
    {
        return [
            'empty' => [
                'input' => [],
                'expected' => [],
            ],
            'filled' => [
                'input' => ['attribute_fields' => ['attribute' => []]],
                'expected' => ['attribute_fields' => ['attribute' => []]],
            ],
        ];
    }

    /**
     * @param \PHPUnit_Framework_MockObject_Matcher_InvokedCount $expects
     * @param ActionData $data
     * @return ActionInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected function createAction(
        \PHPUnit_Framework_MockObject_Matcher_InvokedCount $expects,
        ActionData $data
    ) {
        /* @var $action ActionInterface|\PHPUnit_Framework_MockObject_MockObject */
        $action = $this->getMockBuilder('Oro\Component\Action\Action\ActionInterface')
            ->disableOriginalConstructor()
            ->getMock();

        $action->expects($expects)
            ->method('execute')
            ->with($data);

        return $action;
    }

    /**
     * @param \PHPUnit_Framework_MockObject_Matcher_InvokedCount $expects
     * @param ActionData $data
     * @param bool $returnValue
     * @return ConfigurableCondition|\PHPUnit_Framework_MockObject_MockObject
     */
    protected function createCondition(
        \PHPUnit_Framework_MockObject_Matcher_InvokedCount $expects,
        ActionData $data,
        $returnValue
    ) {
        /* @var $condition ConfigurableCondition|\PHPUnit_Framework_MockObject_MockObject */
        $condition = $this->getMockBuilder('Oro\Component\Action\Condition\Configurable')
            ->disableOriginalConstructor()
            ->getMock();

        $condition->expects($expects)
            ->method('evaluate')
            ->with($data)
            ->willReturn($returnValue);

        return $condition;
    }

    public function testGetAttributeManager()
    {
        $attributes = ['attribute' => ['label' => 'attr_label']];

        $this->definition->expects($this->once())
            ->method('getAttributes')
            ->willReturn($attributes);

        $this->data['data'] = new \stdClass();

        $attribute = new Attribute();
        $attribute->setName('test_attr');

        $this->attributeAssembler->expects($this->once())
            ->method('assemble')
            ->with($this->data, $attributes)
            ->willReturn(new ArrayCollection([$attribute]));

        $attributeManager = $this->operation->getAttributeManager($this->data);

        $this->assertInstanceOf('Oro\Bundle\ActionBundle\Model\AttributeManager', $attributeManager);
        $this->assertEquals(new ArrayCollection(['test_attr' => $attribute]), $attributeManager->getAttributes());
    }
}


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

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

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

    /**
     *

     * The number of findings that failed to import.
     *

     */
    private Integer failedCount;
    /**
     *

     * The number of findings that were successfully imported.
     *

     */
    private Integer successCount;
    /**
     *

     * The list of findings that failed to import.
     *

     */
    private java.util.List<ImportFindingsError> failedFindings;

    /**
     *

     * The number of findings that failed to import.
     *

     *
     * @param failedCount
     *        The number of findings that failed to import.
     */

    public void setFailedCount(Integer failedCount) {
        this.failedCount = failedCount;
    }

    /**
     *

     * The number of findings that failed to import.
     *

     *
     * @return The number of findings that failed to import.
     */

    public Integer getFailedCount() {
        return this.failedCount;
    }

    /**
     *

     * The number of findings that failed to import.
     *

     *
     * @param failedCount
     *        The number of findings that failed to import.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BatchImportFindingsResult withFailedCount(Integer failedCount) {
        setFailedCount(failedCount);
        return this;
    }

    /**
     *

     * The number of findings that were successfully imported.
     *

     *
     * @param successCount
     *        The number of findings that were successfully imported.
     */

    public void setSuccessCount(Integer successCount) {
        this.successCount = successCount;
    }

    /**
     *

     * The number of findings that were successfully imported.
     *

     *
     * @return The number of findings that were successfully imported.
     */

    public Integer getSuccessCount() {
        return this.successCount;
    }

    /**
     *

     * The number of findings that were successfully imported.
     *

     *
     * @param successCount
     *        The number of findings that were successfully imported.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BatchImportFindingsResult withSuccessCount(Integer successCount) {
        setSuccessCount(successCount);
        return this;
    }

    /**
     *

     * The list of findings that failed to import.
     *

     *
     * @return The list of findings that failed to import.
     */

    public java.util.List<ImportFindingsError> getFailedFindings() {
        return failedFindings;
    }

    /**
     *

     * The list of findings that failed to import.
     *

     *
     * @param failedFindings
     *        The list of findings that failed to import.
     */

    public void setFailedFindings(java.util.Collection<ImportFindingsError> failedFindings) {
        if (failedFindings == null) {
            this.failedFindings = null;
            return;
        }

        this.failedFindings = new java.util.ArrayList<ImportFindingsError>(failedFindings);
    }

    /**
     *

     * The list of findings that failed to import.
     *

     *

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

     *
     * @param failedFindings
     *        The list of findings that failed to import.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BatchImportFindingsResult withFailedFindings(ImportFindingsError... failedFindings) {
        if (this.failedFindings == null) {
            setFailedFindings(new java.util.ArrayList<ImportFindingsError>(failedFindings.length));
        }
        for (ImportFindingsError ele : failedFindings) {
            this.failedFindings.add(ele);
        }
        return this;
    }

    /**
     *

     * The list of findings that failed to import.
     *

     *
     * @param failedFindings
     *        The list of findings that failed to import.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BatchImportFindingsResult withFailedFindings(java.util.Collection<ImportFindingsError> failedFindings) {
        setFailedFindings(failedFindings);
        return this;
    }

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

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

        if (obj instanceof BatchImportFindingsResult == false)
            return false;
        BatchImportFindingsResult other = (BatchImportFindingsResult) obj;
        if (other.getFailedCount() == null ^ this.getFailedCount() == null)
            return false;
        if (other.getFailedCount() != null && other.getFailedCount().equals(this.getFailedCount()) == false)
            return false;
        if (other.getSuccessCount() == null ^ this.getSuccessCount() == null)
            return false;
        if (other.getSuccessCount() != null && other.getSuccessCount().equals(this.getSuccessCount()) == false)
            return false;
        if (other.getFailedFindings() == null ^ this.getFailedFindings() == null)
            return false;
        if (other.getFailedFindings() != null && other.getFailedFindings().equals(this.getFailedFindings()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getFailedCount() == null) ? 0 : getFailedCount().hashCode());
        hashCode = prime * hashCode + ((getSuccessCount() == null) ? 0 : getSuccessCount().hashCode());
        hashCode = prime * hashCode + ((getFailedFindings() == null) ? 0 : getFailedFindings().hashCode());
        return hashCode;
    }

    @Override
    public BatchImportFindingsResult clone() {
        try {
            return (BatchImportFindingsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
namespace gecrawler {

ArchiveWriter::ArchiveWriter(geFilePool &file_pool,
                             const std::string &archive_name)
    : qtp_writer_(file_pool, khComposePath(archive_name, "qtp")),
      qtp2_writer_(file_pool, khComposePath(archive_name, "qtp2")),
      img_writer_(file_pool, khComposePath(archive_name, "img")),
      ter_writer_(file_pool, khComposePath(archive_name, "ter")),
      vec_writer_(file_pool, khComposePath(archive_name, "vec")) {
}

ArchiveWriter::~ArchiveWriter() {
}

void ArchiveWriter::WriteQuadtreePacket(
    const qtpacket::KhQuadtreeDataReference &qt_ref,
    const std::string &buffer) {
  WritePacket(qtp_writer_, qt_ref, buffer);
}

void ArchiveWriter::WriteQuadtreePacket2(
    const qtpacket::KhQuadtreeDataReference &qt_ref,
    const std::string &buffer) {
  WritePacket(qtp2_writer_, qt_ref, buffer);
}

void ArchiveWriter::WriteImagePacket(
    const qtpacket::KhQuadtreeDataReference &qt_ref,
    const std::string &buffer) {
  WritePacket(img_writer_, qt_ref, buffer);
}

void ArchiveWriter::WriteTerrainPacket(
    const qtpacket::KhQuadtreeDataReference &qt_ref,
    const std::string &buffer) {
  WritePacket(ter_writer_, qt_ref, buffer);
}

void ArchiveWriter::WriteVectorPacket(
    const qtpacket::KhQuadtreeDataReference &qt_ref,
    const std::string &buffer) {
  WritePacket(vec_writer_, qt_ref, buffer);
}

void ArchiveWriter::WritePacket(
    FileBundleWriter &writer,
    const qtpacket::KhQuadtreeDataReference &qt_ref,
    const std::string &buffer) {
  // Header info with its own CRC
  write_buffer_.reset();
  uint32 buffer_size = buffer.size();   // force size to 32 bits on all platforms
  write_buffer_ << buffer_size;
  write_buffer_ << qt_ref;
  write_buffer_ << Crc32(write_buffer_.data(), write_buffer_.size());

  // Packet data with CRC
  write_buffer_.rawwrite(buffer.data(), buffer.size());
  write_buffer_ << Crc32(buffer.data(), buffer.size());

  writer.WriteAppend(write_buffer_.data(), write_buffer_.size());
}

void ArchiveWriter::Close() {
  qtp_writer_.Close();
  qtp2_writer_.Close();
  img_writer_.Close();
  ter_writer_.Close();
  vec_writer_.Close();
}

} // namespace gecrawler


text:
<?php

//pgsql connector

class sql_sync extends __sql_sync  {

  static protected $sql_bin;
  static protected $sql_dump;

  static function init(){
    self::$sql_bin  = trim(`which psql`);
    self::$sql_dump = trim(`which pg_dump`);
  }

  protected function bin_dump($coord, $tables){
    $args          = "-a";

    $tables_str = '';
    foreach($tables as $table) $tables_str .= ' -t '.$table['safe'];

    $from_cmd      = sprintf("%s %s %s %s", self::$sql_dump, $args, $tables_str, $coord['database']);
    return $from_cmd;
  }

  protected function bin_raw($coord){
    $bin_args = "-tA";
    $cmd = sprintf("%s %s", $this->bin($coords), $bin_args);
    return $cmd;
  }

  protected function bin($coords){
    return self::$sql_bin;
  }

  public static function triggers_off($tables){
    return mask_join(LF, array_extract($tables, 'safe'),
        "ALTER TABLE %s DISABLE TRIGGER ALL;");
  }

  public static function triggers_on($tables){
    return mask_join(LF, array_extract($tables, 'safe'),
        "ALTER TABLE %s ENABLE TRIGGER ALL;");
  }

}


text:
if (Meteor.isServer) {
  Meteor.publish('count_from_field_fn_shallow', function (testId) {
    Counts.publish(this, 'posts' + testId, Posts.find({testId: testId}),
        {countFromField: function (doc) { return doc.number; }});
  });

  Meteor.methods({
    setup_shallow_countFromField_fn: function (testId) {
      H.insert(testId, 0, {number: 2});
      H.insert(testId, 1, {number: 3});
    },
    addDoc_shallow_countFromField_fn: function (testId) {
      H.insert(testId, 2, {number: 4});
    },
    updateDoc_shallow_countFromField_fn: function (testId) {
      H.update(testId, 0, {$set: {number: 1}});
    },
    removeDoc_shallow_countFromField_fn: function (testId) {
      H.remove(testId, 0);
    },
    addField_shallow_countFromField_fn: function (testId) {
      H.update(testId, 0, {number: 4});
    },
    removeField_shallow_countFromField_fn: function (testId) {
      H.update(testId, 0, {});
    },
  });
}

if (Meteor.isClient) {
  Tinytest.addAsync("countFromField: (fn shallow) - upon subscribe with no records, return zero", function (test, done) {
    Meteor.subscribe('count_from_field_fn_shallow', test.id, function () {
      test.equal(H.getCount(test.id), 0);
      done();
    });
  });

  Tinytest.addAsync("countFromField: (fn shallow) - upon subscribe with records, return sum of count fields", function (test, done) {
    Meteor.call('setup_shallow_countFromField_fn', test.id, function () {
      Meteor.subscribe('count_from_field_fn_shallow', test.id, function () {
        test.equal(H.getCount(test.id), 5);
        done();
      });
    });
  });

  Tinytest.addAsync("countFromField: (fn shallow) - after adding a doc, increment sum by new count field", function (test, done) {
    Meteor.call('setup_shallow_countFromField_fn', test.id, function () {
      Meteor.subscribe('count_from_field_fn_shallow', test.id, function () {
        var before = H.getCount(test.id);
        Meteor.call('addDoc_shallow_countFromField_fn', test.id, function () {
          var delta = H.getCount(test.id) - before;
          test.equal(delta, +4);
          done();
        });
      });
    });
  });

  Tinytest.addAsync("countFromField: (fn shallow) - after updating the count field of a doc, adjust sum by change in count field", function (test, done) {
    Meteor.call('setup_shallow_countFromField_fn', test.id, function () {
      Meteor.subscribe('count_from_field_fn_shallow', test.id, function () {
        var before = H.getCount(test.id);
        Meteor.call('updateDoc_shallow_countFromField_fn', test.id, function () {
          var delta = H.getCount(test.id) - before;
          test.equal(delta, -1);
          done();
        });
      });
    });
  });

  Tinytest.addAsync("countFromField: (fn shallow) - after removing a doc, decrement sum by previous count value", function (test, done) {
    Meteor.call('setup_shallow_countFromField_fn', test.id, function () {
      Meteor.subscribe('count_from_field_fn_shallow', test.id, function () {
        var before = H.getCount(test.id);
        Meteor.call('removeDoc_shallow_countFromField_fn', test.id, function () {
          var delta = H.getCount(test.id) - before;
          test.equal(delta, -2);
          done();
        });
      });
    });
  });

  Tinytest.addAsync("countFromField: (fn shallow) - after 1) removing count field, 2) readding count field, adjust count by gain minus loss", function (test, done) {
    Meteor.call('setup_shallow_countFromField_fn', test.id, function () {
      Meteor.subscribe('count_from_field_fn_shallow', test.id, function () {
        var before = H.getCount(test.id);
        Meteor.call('removeField_shallow_countFromField_fn', test.id, function () {
          var delta = H.getCount(test.id) - before;
          test.equal(delta, -2, 'removing field did not update count');

          Meteor.call('addField_shallow_countFromField_fn', test.id, function () {
            var delta = H.getCount(test.id) - before;
            test.equal(delta, +2, 'adding field did not update count');
            done();
          });
        });
      });
    });
  });
}


text:
FROM debian:wheezy
MAINTAINER Ahmet Demir <ahmet2mir+github@gmail.com>

ENV RELEASE wheezy
ENV DEBIAN_FRONTEND noninteractive
ENV SHELL /bin/bash

RUN echo "deb http://ftp.fr.debian.org/debian $RELEASE main contrib non-free" > /etc/apt/sources.list \
    && echo "deb http://ftp.debian.org/debian/ $RELEASE-updates main contrib non-free" >> /etc/apt/sources.list \
    && echo "deb http://security.debian.org/ $RELEASE/updates main contrib non-free" >> /etc/apt/sources.list \
    && apt-get update

RUN apt-get install -y --no-install-recommends python python-pip git gunicorn ca-certificates

RUN mkdir -p /webapps/logs/puppetboard \
    && git clone https://github.com/puppet-community/puppetboard.git /webapps/puppetboard \
    && cd /webapps/puppetboard \
    && pip install -r requirements.txt

COPY assets/conf/settings.py /webapps/puppetboard/settings.py
COPY assets/scripts/run.sh /run.sh

RUN chmod +x /run.sh

EXPOSE 9090

CMD ["/run.sh"]


text:
/*
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.github.mysql.protocol.model;

import com.github.mysql.constant.MysqlConstants;
import com.github.mysql.io.MysqlBinlogByteArrayOutputStream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class QueryCmdPacket implements CmdPacket {
    private final String sql;

    public QueryCmdPacket(String command) {
        this.sql = command;
    }

    @Override
    public byte[] getBody() throws IOException {
        MysqlBinlogByteArrayOutputStream os = new MysqlBinlogByteArrayOutputStream(new ByteArrayOutputStream());

        os.writeInteger(MysqlConstants.COM_QUERY, 1);
        os.writeString(this.sql);
        os.close();

        return ((ByteArrayOutputStream)(os.getOutputStream())).toByteArray();
    }

    public String getSql() {
        return sql;
    }

    @Override
    public String toString() {
        return "QueryCmdPacket [sql=" + sql + "]";
    }
}


text:
function trans = createRotation(varargin)
%CREATEROTATION Create the 3*3 matrix of a rotation.
%
%   TRANS = createRotation(THETA);
%   Returns the rotation corresponding to angle THETA (in radians)
%   The returned matrix has the form :
%   [cos(theta) -sin(theta)  0]
%   [sin(theta)  cos(theta)  0]
%   [0           0           1]
%
%   TRANS = createRotation(POINT, THETA);
%   TRANS = createRotation(X0, Y0, THETA);
%   Also specifies origin of rotation. The result is similar as performing
%   translation(-X0, -Y0), rotation(THETA), and translation(X0, Y0).
%
%   Example
%     % apply a rotation on a polygon
%     poly = [0 0; 30 0;30 10;10 10;10 20;0 20];
%     trans = createRotation([10 20], pi/6);
%     polyT = transformPoint(poly, trans);
%     % display the original and the rotated polygons
%     figure; hold on; axis equal; axis([-10 40 -10 40]);
%     drawPolygon(poly, 'k');
%     drawPolygon(polyT, 'b');
%
%   See also:
%   transforms2d, transformPoint, createRotation90, createTranslation
%

%   ---------
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 06/04/2004.
%

%   HISTORY
%   22/04/2009: rename as createRotation

% default values
cx = 0;
cy = 0;
theta = 0;

% get input values
if length(varargin)==1
    % only angle
    theta = varargin{1};
elseif length(varargin)==2
    % origin point (as array) and angle
    var = varargin{1};
    cx = var(1);
    cy = var(2);
    theta = varargin{2};
elseif length(varargin)==3
    % origin (x and y) and angle
    cx = varargin{1};
    cy = varargin{2};
    theta = varargin{3};
end

% compute coefs
cot = cos(theta);
sit = sin(theta);
tx =  cy*sit - cx*cot + cx;
ty = -cy*cot - cx*sit + cy;

% create transformation matrix
trans = [cot -sit tx; sit cot ty; 0 0 1];


text:
<?php
/**
 * Display the post content in "aside" format.
 * This will be use in the loop and full page display.
 *
 * @package bootstrap-basic4
 */

$Bsb4Design = new \BootstrapBasic4\Bsb4Design();
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

        <?php the_content($Bsb4Design->continueReading(true)); ?>

        <?php
        /**
         * This wp_link_pages option adapt to use bootstrap pagination style.
         */
        wp_link_pages(array(
            'before' => '
' . __('Pages:', 'bootstrap-basic4') . '
',
            'after'  => '

',
            'separator' => ''
        ));
        ?>

        <?php
        if (is_single()) {
            ?>
            <?php if ('post' == get_post_type()) { // Hide category and tag text for pages on Search ?>

                <?php
                    /* translators: used between list items, there is a space after the comma */
                    $categories_list = get_the_category_list(__(', ', 'bootstrap-basic4'));
                    if (!empty($categories_list)) {
                ?>

                    <?php $Bsb4Design->categoriesList($categories_list); ?>

                <?php } // End if categories ?>

                <?php
                    /* translators: used between list items, there is a space after the comma */
                    $tags_list = get_the_tag_list('', __(', ', 'bootstrap-basic4'));
                    if ($tags_list) {
                ?>

                    <?php $Bsb4Design->tagsList($tags_list); ?>

                <?php } // End if $tags_list ?>

            <?php } // End if 'post' == get_post_type() ?>

                <?php if (! post_password_required() && (comments_open() || '0' != get_comments_number())) { ?>
                <?php $Bsb4Design->commentsLink(); ?>
                <?php } //endif; ?>

                <?php $Bsb4Design->editPostLink(); ?>

            <?php
        } else {
            $Bsb4Design->postOn();
        } // is_single()
        ?>

<?php unset($Bsb4Design); ?>


text:
*Deprecated*: This has been ported to Go: [git-duet](https://github.com/git-duet/git-duet).

All new development and issues should be directed there.

See README.md.old for the README.md that is old.


text:
/* eslint-disable import/no-unresolved, import/extensions */
import { View } from 'react-native';
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
/* eslint-enable import/no-unresolved, import/extensions */
import RippleFeedback from '../RippleFeedback';

import Title from './Title.react';
import Content from './Content.react';
import Actions from './Actions.react';

const propTypes = {
    onPress: PropTypes.func,
    children: PropTypes.node.isRequired,
    style: PropTypes.object,
};
const defaultProps = {
    onPress: null,
    style: {},
};
const contextTypes = {
    uiTheme: PropTypes.object.isRequired,
};

function getStyles(props, context) {
    const { dialog } = context.uiTheme;

    return {
        container: [
            dialog.container,
            props.style.container,
        ],
    };
}

class Dialog extends PureComponent {
    render() {
        const { onPress, children } = this.props;

        const styles = getStyles(this.props, this.context);

        return (
            <RippleFeedback onPress={onPress} >
                <View style={styles.container} pointerEvents="box-only">
                    {children}
                </View>
            </RippleFeedback>
        );
    }
}

Dialog.propTypes = propTypes;
Dialog.defaultProps = defaultProps;
Dialog.contextTypes = contextTypes;

Dialog.Title = Title;
Dialog.Content = Content;
Dialog.Actions = Actions;

export default Dialog;


text:
from util import manhattanDistance
from game import Directions
import math
import random, util, mazeUtils
from game import Agent

_a = _b = _c = _d = _e = _f = 0.0
def storeConstants(a, b, c, d, e, f):
  global _a, _b, _c, _d, _e, _f
  _a = float(a)
  _b = float(b)
  _c = float(c)
  _d = float(d)
  _e = float(e)
  _f = float(f)

_walls = None
distanceInMaze = {}
def computeMazeDistances(walls):
  global _walls
  if walls == _walls:
    return
  else:
    _walls = walls
    mazeUtils.distancesInMaze(walls, distanceInMaze)

def getDistanceInMaze(start, goal):

  def floor(pos):
    return (math.floor(pos[0]), math.floor(pos[1]))

  start = floor(start)
  goal = floor(goal)
  sg = (start, goal)
  gs = (goal, start)
  if distanceInMaze.has_key(sg):
    return distanceInMaze[sg]
  elif distanceInMaze.has_key(gs):
    return distanceInMaze[gs]
  else:
    raise Exception("no distance stored for that pair")

class ReflexAgent(Agent):
  """
    A reflex agent chooses an action at each choice point by examining
    its alternatives via a state evaluation function.

    The code below is provided as a guide.  You are welcome to change
    it in any way you see fit, so long as you don't touch our method
    headers.
  """

  def getAction(self, gameState):
    """
    You do not need to change this method, but you're welcome to.

    getAction chooses among the best options according to the evaluation function.

    Just like in the previous project, getAction takes a GameState and returns
    some Directions.X for some X in the set {North, South, West, East, Stop}
    """
    # Collect legal moves and successor states
    legalMoves = gameState.getLegalActions()

    # Choose one of the best actions
    scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
    bestScore = max(scores)
    bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
    chosenIndex = random.choice(bestIndices) # Pick randomly among the best

    "Add more of your code here if you want to"

    return legalMoves[chosenIndex]

  def evaluationFunction(self, currentGameState, action):
    """
    Design a better evaluation function here.

    The evaluation function takes in the current and proposed successor
    GameStates (pacman.py) and returns a number, where higher numbers are better.

    The code below extracts some useful information from the state, like the
    remaining food (oldFood) and Pacman position after moving (newPos).
    newScaredTimes holds the number of moves that each ghost will remain
    scared because of Pacman having eaten a power pellet.

    Print out these variables to see what you're getting, then combine them
    to create a masterful evaluation function.
    """
    # Useful information you can extract from a GameState (pacman.py)
    successorGameState = currentGameState.generatePacmanSuccessor(action)
    walls = currentGameState.getWalls()
    newPos = successorGameState.getPacmanPosition()
    oldFood = currentGameState.getFood()
    newGhostStates = successorGameState.getGhostStates()
    ghostPositions = map(lambda g: g.getPosition(), newGhostStates)
#    computeMazeDistances(walls)

    # getting closer to food is good
    # getting closer to ghosts is bad

    foodScore = 0
#    distanceToClosestFood = min(map(lambda x: getDistanceInMaze(newPos, x), oldFood.asList()))
    distanceToClosestFood = min(map(lambda x: util.manhattanDistance(newPos, x), oldFood.asList()))

    distanceToClosestGhost = min(map(lambda x: util.manhattanDistance(newPos, x),
                                     ghostPositions))

    ghostScore = 0
    foodScore = 0
    if distanceToClosestGhost == 0:
      return -99
    elif distanceToClosestGhost < 6:
      ghostScore = (1./distanceToClosestGhost) * -2

    if distanceToClosestFood == 0:
      foodScore = 0
      ghostScore += 2
    else:
      foodScore = 1./distanceToClosestFood

    return foodScore + ghostScore

def scoreEvaluationFunction(currentGameState):
  """
    This default evaluation function just returns the score of the state.
    The score is the same one displayed in the Pacman GUI.

    This evaluation function is meant for use with adversarial search agents
    (not reflex agents).
  """
  return currentGameState.getScore()

class MultiAgentSearchAgent(Agent):
  """
    This class provides some common elements to all of your
    multi-agent searchers.  Any methods defined here will be available
    to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.

    You *do not* need to make any changes here, but you can if you want to
    add functionality to all your adversarial search agents.  Please do not
    remove anything, however.

    Note: this is an abstract class: one that should not be instantiated.  It's
    only partially specified, and designed to be extended.  Agent (game.py)
    is another abstract class.
  """

  def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2', a=0,b=0,c=0,d=0,e=0,f=0):
    self.index = 0 # Pacman is always agent index 0
    self.depth = int(depth)
    storeConstants(a, b, c, d, e, f)
    # self.a = a
    # print "a: ", a
    # b = b
    # c = c
    # d = d
    # e = e
    # f = f
    self.evaluationFunction = util.lookup(evalFn, globals())

class MinimaxAgent(MultiAgentSearchAgent):
  """
    Your minimax agent (question 2)
  """

  def gameOver(self, gameState, d):
    return gameState.isLose() or gameState.isWin() or d == 0

  def minimax(self, gameState, agentIndex, depth):
    "produces the min or max value for some game state and depth; depends on what agent."
    successorStates = map(lambda a: gameState.generateSuccessor(agentIndex, a),
                         gameState.getLegalActions(agentIndex))
    if self.gameOver(gameState, depth): # at an end
      return self.evaluationFunction(gameState)
    else:
      # use modulo so we can wrap around, get vals of leaves
      nextAgent = (agentIndex + 1) % gameState.getNumAgents()
      vals = map(lambda s: self.minimax(s, nextAgent, depth - 1),
                successorStates)
      if nextAgent == 0: # pacman
        return max(vals)
      else:
        return min(vals)

  def getAction(self, gameState):
    """
      Returns the minimax action from the current gameState using self.depth
      and self.evaluationFunction.
    """
    depth = gameState.getNumAgents()*self.depth

    legalActions = gameState.getLegalActions(0)
    legalActions.remove(Directions.STOP)
    successorStates = map(lambda a: gameState.generateSuccessor(0,a),
                          legalActions)
    # compute the best possible values for each successorState
    vals = map(lambda s: self.minimax(s, 1, depth - 1),
               successorStates)
    # return the action that corresponds to the largest value
    return legalActions[vals.index(max(vals))]

class AlphaBetaAgent(MultiAgentSearchAgent):
  """
    Your minimax agent with alpha-beta pruning (question 3)
  """
  def gameOver(self, gameState, d):
    return gameState.isLose() or gameState.isWin() or d == 0

  def alphabeta(self, agentIndex, gameState, depth, alpha, beta):
    "alpha-beta search. pretty similar to minimax, but it prunes the tree etc."
    legalActions = gameState.getLegalActions(agentIndex)
    if agentIndex == 0 and Directions.STOP in legalActions:
      legalActions.remove(Directions.STOP)

    successorStates = map(lambda a: gameState.generateSuccessor(agentIndex, a),
                          gameState.getLegalActions(agentIndex))

    if self.gameOver(gameState, depth):
      return self.evaluationFunction(gameState)

    else:
      if agentIndex == 0: # pacman
        v = float("inf") #alpha beta was weird without doing the infinity part of the algorithm
        for successor in successorStates:
          v = max(self.alphabeta((agentIndex + 1) % gameState.getNumAgents(),
                                 successor, depth-1, alpha, beta), v)
          if v >= beta:
            return v
          alpha = max(alpha, v)
        return v

      else: # ghost
        v = float("inf")
        for successor in successorStates:
          v = min(self.alphabeta((agentIndex + 1) % gameState.getNumAgents(),
                                 successor, depth-1, alpha, beta), v)
          if v <= alpha:
            return v
          beta = min(beta, v)
        return v

  def getAction(self, gameState):
    depth = gameState.getNumAgents() * self.depth

    legalActions = gameState.getLegalActions(0)
    legalActions.remove(Directions.STOP)

    successorStates = map(lambda a: gameState.generateSuccessor(0,a),
                          legalActions)

    vals = map(lambda s: self.alphabeta(1, s, depth - 1, -1e308, 1e308),
               successorStates)

    return legalActions[vals.index(max(vals))]

class ExpectimaxAgent(MultiAgentSearchAgent):
  """
    Your expectimax agent (question 4)
  """

  def gameOver(self, gameState, d):
    return gameState.isLose() or gameState.isWin() or d == 0

  def expectimax(self, gameState, agentIndex,  depth):
    """
    Same as minimax, except we do an average of min.
    We do an average because the ghost behavior is expected to be
    'uniformly at random'. If that's the case, then the expected
    value of a node's children is the average of their values.
    """
    successorStates = map(lambda a: gameState.generateSuccessor(agentIndex, a),
                         gameState.getLegalActions(agentIndex))

    if self.gameOver(gameState, depth): # at an end
      return self.evaluationFunction(gameState)
    else:

      newIndex = (agentIndex + 1) % gameState.getNumAgents()
      vals = map(lambda s: self.expectimax(s, newIndex, depth - 1),
                successorStates)

      if agentIndex == 0: # pacman
        return max(vals)
      else: # ghost, here's the expectimax part.
        return sum(vals)/len(vals)

  def getAction(self, gameState):
    """
      Returns the expectimax action using self.depth and self.evaluationFunction

      All ghosts should be modeled as choosing uniformly at random from their
      legal moves.
    """
    depth = gameState.getNumAgents() * self.depth

    legalActions = gameState.getLegalActions(0)
    legalActions.remove(Directions.STOP)

    successorStates = map(lambda a: gameState.generateSuccessor(0,a),
                         legalActions)
    vals = map(lambda s: self.expectimax(s, 1, depth - 1),
    successorStates)
    return legalActions[vals.index(max(vals))]

def testEval(currentGameState):

  pos = currentGameState.getPacmanPosition()
  currentScore = scoreEvaluationFunction(currentGameState)

  if currentGameState.isLose():
    return -float("inf")
  elif currentGameState.isWin():
    return float("inf")

  # food distance
  foodlist = currentGameState.getFood().asList()
  manhattanDistanceToClosestFood = min(map(lambda x: util.manhattanDistance(pos, x), foodlist))
  distanceToClosestFood = manhattanDistanceToClosestFood

  # number of big dots
  numberOfCapsulesLeft = len(currentGameState.getCapsules())

  # number of foods left
  numberOfFoodsLeft = len(foodlist)

  # ghost distance

  # active ghosts are ghosts that aren't scared.
  scaredGhosts, activeGhosts = [], []
  for ghost in currentGameState.getGhostStates():
    if not ghost.scaredTimer:
      activeGhosts.append(ghost)
    else:
      scaredGhosts.append(ghost)

  def getManhattanDistances(ghosts):
    return map(lambda g: util.manhattanDistance(pos, g.getPosition()), ghosts)

  distanceToClosestActiveGhost = distanceToClosestScaredGhost = 0

  if activeGhosts:
    distanceToClosestActiveGhost = min(getManhattanDistances(activeGhosts))
  else:
    distanceToClosestActiveGhost = float("inf")
  distanceToClosestActiveGhost = max(distanceToClosestActiveGhost, 5)

  if scaredGhosts:
    distanceToClosestScaredGhost = min(getManhattanDistances(scaredGhosts))
  else:
    distanceToClosestScaredGhost = 0 # I don't want it to count if there aren't any scared ghosts

  outputTable = [["dist to closest food", -1.5*distanceToClosestFood],
                 ["dist to closest active ghost", 2*(1./distanceToClosestActiveGhost)],
                 ["dist to closest scared ghost", 2*distanceToClosestScaredGhost],
                 ["number of capsules left", -3.5*numberOfCapsulesLeft],
                 ["number of total foods left", 2*(1./numberOfFoodsLeft)]]

  # a, b, c, d, e, and f are all constants given through the command line.
  # they're set/declared as global variables in a method at the top of this file
  # and through the expectimax constructor.
  #print _a, ", ", _b, ", ", _c, ", ", _d, ", ", _e, ", ", _f
  # print(type(float(_a)))
  # print(type(float(_b)))
  # print(type(float(_c)))
  # print(type(float(_d)))
  # print(type(_e))
  # print(type(float(_f)))

  score = _a   * currentScore + \
          _b   * distanceToClosestFood + \
          _c   * (1./distanceToClosestActiveGhost) + \
          _d   * distanceToClosestScaredGhost + \
          _e   * numberOfCapsulesLeft + \
          _f   * numberOfFoodsLeft

  # score = 1    * currentScore + \
  #         -1.5 * distanceToClosestFood + \
  #         2    * (1./distanceToClosestActiveGhost) + \
  #         2    * distanceToClosestScaredGhost + \
  #         -3.5 * numberOfCapsulesLeft + \
  #         -4    * numberOfFoodsLeft
  return score

def betterEvaluationFunction(currentGameState):
  """
    Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
    evaluation function (question 5).

    DESCRIPTION: <write something here so we know what you did>
  """
  return testEval(currentGameState)

# Abbreviation
better = betterEvaluationFunction

class ContestAgent(MultiAgentSearchAgent):
  """
    Your agent for the mini-contest
  """

  def getAction(self, gameState):
    """
      Returns an action.  You can use any method you want and search to any depth you want.
      Just remember that the mini-contest is timed, so you have to trade off speed and computation.

      Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually
      just make a beeline straight towards Pacman (or away from him if they're scared!)
    """
    "*** YOUR CODE HERE ***"
    util.raiseNotDefined()


text:
package com.uk.xarixa.cloud.filesystem.core.utils;

import org.jmock.integration.junit4.JUnitRuleMockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import com.uk.xarixa.cloud.filesystem.core.nio.CloudPath;
import com.uk.xarixa.cloud.filesystem.core.utils.DefaultPathMatcher;

@RunWith(BlockJUnit4ClassRunner.class)
public class DefaultPathMatcherTest {

	@Rule
	public JUnitRuleMockery context = new JUnitRuleMockery() {{
		setImposteriser(ClassImposteriser.INSTANCE);
	}};

	@Test
	public void testExtractRegexFromGlobPatternFailsIfAGroupingIsNotFound() {
		try {
			DefaultPathMatcher.extractRegexFromGlobPattern("*.{java,class", CloudPath.DEFAULT_PATH_SEPARATOR);
			Assert.fail("Expected an exception to be thrown");
		} catch (IllegalArgumentException e) {
			// OK
		}
	}

	@Test
	public void testExtractRegexFromGlobPatternFailsIfABracketsEndingIsNotFound() {
		try {
			DefaultPathMatcher.extractRegexFromGlobPattern("*.[a-z", CloudPath.DEFAULT_PATH_SEPARATOR);
			Assert.fail("Expected an exception to be thrown");
		} catch (IllegalArgumentException e) {
			// OK
		}
	}

	@Test
	public void testExtractRegexFromGlobPatternParsesCorrectly() {
		Assert.assertEquals("[^/]*\\.java", DefaultPathMatcher.extractRegexFromGlobPattern("*.java", CloudPath.DEFAULT_PATH_SEPARATOR));
		Assert.assertEquals(".*\\.java", DefaultPathMatcher.extractRegexFromGlobPattern("**.java", CloudPath.DEFAULT_PATH_SEPARATOR));
		Assert.assertEquals(".*/[^/]*\\.java", DefaultPathMatcher.extractRegexFromGlobPattern("**/*.java", CloudPath.DEFAULT_PATH_SEPARATOR));
		Assert.assertEquals("/home/.*", DefaultPathMatcher.extractRegexFromGlobPattern("/home/**", CloudPath.DEFAULT_PATH_SEPARATOR));
		Assert.assertEquals("/home/gus/.*", DefaultPathMatcher.extractRegexFromGlobPattern("/home/gus/**", CloudPath.DEFAULT_PATH_SEPARATOR));
		Assert.assertEquals("/home/gus/[^/]*", DefaultPathMatcher.extractRegexFromGlobPattern("/home/gus/*", CloudPath.DEFAULT_PATH_SEPARATOR));
		Assert.assertEquals("file\\.[^/][^/][^/]", DefaultPathMatcher.extractRegexFromGlobPattern("file.???", CloudPath.DEFAULT_PATH_SEPARATOR));
		Assert.assertEquals("special\\@chars\\.\\$\\$\\$", DefaultPathMatcher.extractRegexFromGlobPattern("special\\@chars.$$$", CloudPath.DEFAULT_PATH_SEPARATOR));
	}

	@Test
	public void testConstructorCreatesANewPatternMatcherFromASimpleGlobExpression() {
		DefaultPathMatcher matcher = new DefaultPathMatcher("glob:*.java");
		Assert.assertTrue(matcher.matches("DefaultPathMatcherTest.java"));
		Assert.assertFalse(matcher.matches("/DefaultPathMatcherTest.java"));
		Assert.assertFalse(matcher.matches("/dir/DefaultPathMatcherTest.java"));
	}

	@Test
	public void testConstructorCreatesANewPatternMatcherFromASimpleGlobExpressionWithSpecialCharacters() {
		DefaultPathMatcher matcher = new DefaultPathMatcher("glob:*xx.$$$");
		Assert.assertTrue(matcher.matches("somexx.$$$"));
		Assert.assertFalse(matcher.matches("/somexx.$$$"));
		Assert.assertFalse(matcher.matches("/dir/somexx.$$$"));
	}

	@Test
	public void testConstructorCreatesANewPatternMatcherFromAComplexGlobExpressionWithDirectories() {
		DefaultPathMatcher matcher = new DefaultPathMatcher("glob:/home/users/**/*efault*.java");
		Assert.assertFalse(matcher.matches("DefaultPathMatcherTest.java"));
		Assert.assertFalse(matcher.matches("/DefaultPathMatcherTest.java"));
		Assert.assertFalse(matcher.matches("/home/users/DefaultPathMatcherTest.java"));
		Assert.assertTrue(matcher.matches("/home/users/userdir/DefaultPathMatcherTest.java"));
	}

	@Test
	public void testConstructorCreatesANewPatternMatcherFromAComplexGlobExpressionWithGroupings() {
		DefaultPathMatcher matcher = new DefaultPathMatcher("glob:**/*.{java,properties,xml}");
		Assert.assertFalse(matcher.matches("DefaultPathMatcherTest.java"));
		Assert.assertTrue(matcher.matches("/DefaultPathMatcherTest.java"));
		Assert.assertTrue(matcher.matches("/home/users/DefaultPathMatcherTest.java"));
		Assert.assertTrue(matcher.matches("/home/users/userdir/DefaultPathMatcherTest.java"));
	}

}


text:
import sys
py2 = sys.version_info[0] == 2

if py2:
    from HTMLParser import HTMLParser
else:
    from html.parser import HTMLParser

from textwrap import dedent

def test_htmlparser():
    html = dedent("""\
        <html>
          <meta name='author' content="傑洛米高">
          <meta name='description' content="<HTML>" />
        <html>""")
    if py2:
        html = html.decode('utf-8') # feed(unicode) is advised

    parser = HTMLMetaParser()
    parser.feed(html)

    assert parser.entries == {
        'author': u'傑洛米高',
        'description': '<HTML>', # no entity refs
    }

class HTMLMetaParser(HTMLParser):

    def __init__(self):
        HTMLParser.__init__(self)
        self.entries = {}

    def handle_starttag(self, tag, attrs):
        if tag != 'meta':
            return

        attrs = dict(attrs)
        if not ('name' in attrs and 'content' in attrs):
            return

        self.entries[attrs['name']] = attrs['content']


text:
{% extends "public/base.html" %}

{% block content_app%}

 Application form received

 Thank you for applying for membership of Coombe Wood LTC. Your application will be considered and we will get
      back to you shortly.

We have sent an acknowledgement email to {{ email }} from our membership system's address {{ subs_email }}.
      Please check that you have received that email.

Sometimes, particularly with hotmail, msn or outlook addresses, our emails
      get put into your spam or junk mail folder. If that happens, please add {{ subs_email }} and {{ info_email }}
      to your safe senders list.

If you do not receive an acknowledgement email or have any questions about your membership application,
      please mail the  membership secretary.

{% endblock %}


text:
(function(){
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

if (!Object.keys){
  Object.keys = function(obj) {
      var key;
      var keys=[];
      for (key in obj) {
          if (obj.hasOwnProperty(key)) keys.push(key);
      }
      return keys;
  };
}
//

//function isNumber(n) {
//  return !isNaN(parseFloat(n)) && isFinite(n);
//}
//input binding
var hdtable = new Shiny.InputBinding();
$.extend(hdtable, {
  find: function(scope) {
    return $(scope).find(".hdtable");
  },
  getValue: function(el) {
    var ht = $(el).handsontable("getInstance")
    if (ht == null) {
      return (null)
    } else {
      var ht1 = ht.getData()
     // console.log('ht1 '+ ht1);
      ht2 = ht1
      return ({
        colHeaders: ht.getColHeader(),
        data: ht1
      });
    }
  },
  setValue: function(el, value) {},
  subscribe: function(el, callback) {
    $(el).on("afterChange", function(e) {
      callback();
    });
  },
  unsubscribe: function(el) {
    $(el).off(".hdtable");
  }
});
Shiny.inputBindings.register(hdtable);

//output binding
var hdtableOutput = new Shiny.OutputBinding();
$.extend(hdtableOutput, {
  find: function(scope) {
    return $(scope).find('.hdtable');
  },
  renderValue: function(el, json) {
    if (json === null) return;
    if (!json.hasOwnProperty("data")) return;

    // define handsontable
    $(el).handsontable({
      columns: json.columns,
      manualColumnResize: true,
      minSpareRows: 0, // at least one empty row
      colHeaders: json.colHeaders,
      handlebar: true,
      columnSorting: true
    });

    var ht = $(el).handsontable('getInstance');
    var obj_of_arr = json.data;
    // console.debug(obj_of_arr);

    // parse an object of arrays into array of object
    var keys = json.colHeaders; // obtain the keys from the colHeaders - This retains the order of the columns
    var arr_of_obj = [];

    if (typeof obj_of_arr[keys[0]] === "object") {
      var l = obj_of_arr[keys[0]].length;
      for (var i = 0; i < l; i++) {
        var tmpobj = [];
        keys.map(function(key) {
          tmpobj.push(obj_of_arr[key][i]);
        })
        arr_of_obj.push(tmpobj);
      }
    } else {
      var l = 1;
      var tmpobj = [];
      keys.map(function(key) {
        tmpobj.push(obj_of_arr[key]);
      })
      arr_of_obj = [tmpobj];
    }
    // console.debug(arr_of_obj);

    ht.loadData(arr_of_obj);
    ht.addHook("afterChange", function() {
      $(el).trigger("afterChange");
    })
    $(el).trigger("afterChange");
  }
});
Shiny.outputBindings.register(hdtableOutput, "hdtable");
//
//
cellClasses = {};

Shiny.addCustomMessageHandler('htable-style', function(data) {
  // console.log('data = '+JSON.stringify(data));
  var $el = $('#' + data.id);
  if (!$el || !data.style)
    return;

  if (!cellClasses[data.id]){
    cellClasses[data.id] = {};
  }

  var style = data.style;
  // console.log('style = '+JSON.stringify(style) );
  // Convert to arrays if they're not already
  style.row = [].concat(style.row);
  style.col = [].concat(style.col);

  for (var r = 0; r < style.row.length; r++){
    var row = style.row[r];
    if (!cellClasses[data.id][row]){
      cellClasses[data.id][row] = {};
    }

    for (var c = 0; c < style.col.length; c++){
      var col = style.col[c];
      // console.log('cell class info '+style.cssClass);
      cellClasses[data.id][row][col] = style.cssClass;
      // console.debug(cellClasses[data.id][row][col]);

    }
  }

  applyStyles(data.id);
// console.debug(data);
});

function applyStyles(id){
  if (!cellClasses[id]){
    return;
  }

  var $el = $('#' + id); //console.log($el);
  var tbl = $el.handsontable('getInstance');
    if (!tbl){
      // Create if it doesn't exist yet.
      $el.handsontable();
      tbl = $el.handsontable('getInstance');
    }
  // console.log('instance v--->'+ tbl);
  var rows = Object.keys(cellClasses[id]);

  $.each(rows, function(i, row){
   // console.log(", Row " + row);
    var cols = Object.keys(cellClasses[id][row]);
    $.each(cols, function(j, col){
    //  console.log(", col " + col);

      col = parseInt(col,10);
      row = parseInt(row,10);
      // console.log('row = '+row+' col = '+col);
      // console.log($el + ": Tbl ", tbl);
      var td = tbl.getCell(row,col);  //(1,1)

      // Clear out existing styles
      if (!td)
        return;
      while (td.classList.length > 0){
        td.classList.remove(td.classList[0]);
      }

      td.classList.add(cellClasses[id][row][col]);

    });
  });

}

})();


text:
layout: documentation
---

# CurrentServerState
`Client`

As a consumer you can use the `CurrentServerState` to get the current game state as it exists on the server. This is the game state that does not have any input received by the client and not processed by the server. This is the true state of the world but suffers a lag equal to the roundtrip time from the client to the server.

Like the [`StateTracker`](StateTracker.html), the `CurrentServerState` expects functions for most of it's input types. We do this so you can describe a path to a property in advance.

~~~javascript
var pathToState = function (state) {
  return state.game.players.count;
}

currentState().get(pathToState);
~~~


text:
"""Tests for tensorflow.ops.tf.gather."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf

class GatherTest(tf.test.TestCase):
    def testScalar1D(self):
        with self.test_session():
            params = tf.constant([0, 1, 2, 3, 7, 5])
            indices = tf.constant(4)
            gather_t = tf.gather(params, indices)
            gather_val = gather_t.eval()
        self.assertAllEqual(7, gather_val)
        self.assertEqual([], gather_t.get_shape())

    def testScalar2D(self):
        with self.test_session():
            params = tf.constant([[0, 1, 2], [3, 4, 5], [6, 7, 8],
                                  [9, 10, 11], [12, 13, 14]])
            indices = tf.constant(2)
            gather_t = tf.gather(params, indices)
            gather_val = gather_t.eval()
        self.assertAllEqual([6, 7, 8], gather_val)
        self.assertEqual([3], gather_t.get_shape())

    def testSimpleTwoD32(self):
        with self.test_session():
            params = tf.constant([[0, 1, 2], [3, 4, 5], [6, 7, 8],
                                  [9, 10, 11], [12, 13, 14]])
            indices = tf.constant([0, 4, 0, 2])
            gather_t = tf.gather(params, indices)
            gather_val = gather_t.eval()
        self.assertAllEqual([[0, 1, 2], [12, 13, 14], [0, 1, 2], [6, 7, 8]],
                            gather_val)
        self.assertEqual([4, 3], gather_t.get_shape())

    def testHigherRank(self):
        np.random.seed(1)
        shape = (4, 3, 2)
        params = np.random.randn(*shape)
        indices = np.random.randint(shape[0], size=15).reshape(3, 5)
        with self.test_session():
            tf_params = tf.constant(params)
            tf_indices = tf.constant(indices)
            gather = tf.gather(tf_params, tf_indices)
            self.assertAllEqual(params[indices], gather.eval())
            self.assertEqual(indices.shape + params.shape[1:], gather.get_shape())
            # Test gradients
            gather_grad = np.random.randn(*gather.get_shape().as_list())
            params_grad, indices_grad = tf.gradients(gather, [tf_params, tf_indices],
                                                     gather_grad)
            self.assertEqual(indices_grad, None)
            self.assertEqual(type(params_grad), tf.IndexedSlices)
            params_grad = tf.convert_to_tensor(params_grad)
            correct_params_grad = np.zeros(shape)
            for i, g in zip(indices.ravel(), gather_grad.reshape((15,) + shape[1:])):
                correct_params_grad[i] += g
            self.assertAllEqual(correct_params_grad, params_grad.eval())

    def testUnknownIndices(self):
        params = tf.constant([[0, 1, 2]])
        indices = tf.placeholder(tf.int32)
        gather_t = tf.gather(params, indices)
        self.assertEqual(None, gather_t.get_shape())

if __name__ == "__main__":
    tf.test.main()


text:
// Type definitions for xml-escape 1.1
// Project: https://github.com/miketheprogrammer/xml-escape
// Definitions by: Charles Kenney <https://github.com/charliekenney23>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

/**
 * Escape an XML string
 *
 * @param string String of XML to escape
 * @param ignore Characters to ignore
 */
declare function escape(string: string, ignore?: string): string;
export = escape;


text:
user = ENV['OPSCODE_USER'] || ENV['USER']
node_name                   user
client_key                  "#{ENV['HOME']}/.chef/#{user}.pem"
validation_client_name      'bke-validator'
validation_key              "#{ENV['HOME']}/.chef/bke-validation.pem"
chef_server_url             "https://#{ENV['CHEF_SERVER_URL']}/organizations/bke"
syntax_check_cache_path     "#{ENV['HOME']}/.chef/syntax_check_cache"
cookbook_path               ["#{ENV['CHEF_WORKSPACE']}/cookbooks"]
cookbook_copyright          "Buckle, Inc"
cookbook_license            "apachev2"
cookbook_email              "wsdsysadmin@buckle.com"