text:
<?php

namespace Drupal\Tests\search_api\Unit\Plugin\Processor;

use Drupal\search_api\IndexInterface;
use Drupal\search_api\Item\Field;
use Drupal\search_api\Plugin\search_api\data_type\value\TextToken;
use Drupal\search_api\Plugin\search_api\data_type\value\TextValue;
use Drupal\search_api\Query\Condition;
use Drupal\Tests\UnitTestCase;

/**
 * Tests the base class for fields-based processors.
 *
 * @coversDefaultClass \Drupal\search_api\Processor\FieldsProcessorPluginBase
 *
 * @group search_api
 */
class FieldsProcessorPluginBaseTest extends UnitTestCase {

  use TestItemsTrait;

  /**
   * A search index mock to use in this test case.
   *
   * @var \Drupal\search_api\IndexInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $index;

  /**
   * The class under test.
   *
   * @var \Drupal\Tests\search_api\Unit\Plugin\Processor\TestFieldsProcessorPlugin
   */
  protected $processor;

  /**
   * Creates a new processor object for use in the tests.
   */
  public function setUp() {
    parent::setUp();

    $this->setUpMockContainer();
    $this->index = $this->getMock('Drupal\search_api\IndexInterface');
    $this->index->expects($this->any())
      ->method('status')
      ->will($this->returnValue(TRUE));
    $items = $this->getTestItem();
    $fields = $items[$this->itemIds[0]]->getFields();
    $this->index->expects($this->any())
      ->method('getFields')
      ->will($this->returnValue($fields));

    $this->processor = new TestFieldsProcessorPlugin(['#index' => $this->index], '', []);
  }

  /**
   * Tests whether the processor handles field changes correctly.
   */
  public function testFieldRenaming() {
    $configuration['fields'] = [
      'float_field',
      'float_field_2',
      'string_field',
      'text_field',
      'text_field_2',
    ];
    $this->processor->setConfiguration($configuration);

    $override = function ($type) {
      return in_array($type, ['string', 'text']);
    };
    $this->processor->setMethodOverride('testType', $override);

    $this->index->method('getFieldRenames')
      ->willReturn([
        'float_field' => 'foo',
        'text_field' => 'bar',
      ]);
    $this->index->method('getField')
      ->willReturnMap([
        ['float_field', (new Field($this->index, ''))->setType('float')],
        ['float_field_2', NULL],
        ['string_field', (new Field($this->index, ''))->setType('string')],
        ['bar', (new Field($this->index, ''))->setType('text')],
        ['text_field_2', (new Field($this->index, ''))->setType('text')],
      ]);

    $this->processor->preIndexSave();

    $fields = $this->processor->getConfiguration()['fields'];
    sort($fields);
    $expected = [
      'bar',
      'string_field',
      'text_field_2',
    ];
    $this->assertEquals($expected, $fields);
  }

  /**
   * Tests whether the "Enable on all supported fields" option works correctly.
   *
   * We want the option to make sure that all supported fields are automatically
   * added to the processor, without adding unsupported ones or keeping old ones
   * that were removed.
   */
  public function testAllFields() {
    $configuration['all_fields'] = TRUE;
    $configuration['fields'] = [
      'float_field',
      'string_field',
    ];
    $this->processor->setConfiguration($configuration);

    $override = function ($type) {
      return in_array($type, ['string', 'text']);
    };
    $this->processor->setMethodOverride('testType', $override);

    // Since it's not possible to override an already specified method on a mock
    // object, we need to create a new mock object for the index in this test.
    /** @var \Drupal\search_api\IndexInterface|\PHPUnit_Framework_MockObject_MockObject $index */
    $index = $this->getMock(IndexInterface::class);
    $index->method('getFields')->willReturn([
      'float_field' => (new Field($this->index, ''))->setType('float'),
      'float_field_2' => (new Field($this->index, ''))->setType('float'),
      'string_field' => (new Field($this->index, ''))->setType('string'),
      'text_field' => (new Field($this->index, ''))->setType('text'),
      'text_field_2' => (new Field($this->index, ''))->setType('text'),
    ]);
    $this->processor->setIndex($index);

    $this->processor->preIndexSave();

    $fields = $this->processor->getConfiguration()['fields'];
    sort($fields);
    $expected = [
      'string_field',
      'text_field',
      'text_field_2',
    ];
    $this->assertEquals($expected, $fields);
  }

  /**
   * Tests whether the default implementation of testType() works correctly.
   */
  public function testTestTypeDefault() {
    $items = $this->getTestItem();
    $this->processor->preprocessIndexItems($items);
    $this->assertFieldsProcessed($items, ['text_field', 'string_field']);
  }

  /**
   * Tests whether overriding of testType() works correctly.
   */
  public function testTestTypeOverride() {
    $override = function ($type) {
      return \Drupal::getContainer()
        ->get('search_api.data_type_helper')
        ->isTextType($type, ['string', 'integer']);
    };
    $this->processor->setMethodOverride('testType', $override);

    $items = $this->getTestItem();
    $this->processor->preprocessIndexItems($items);
    $this->assertFieldsProcessed($items, ['string_field', 'integer_field']);
  }

  /**
   * Tests whether selecting fields works correctly.
   */
  public function testTestField() {
    // testType() shouldn't have any effect anymore when fields are configured.
    $override = function () {
      return FALSE;
    };
    $this->processor->setMethodOverride('testType', $override);
    $configuration['fields'] = ['text_field', 'float_field'];
    $this->processor->setConfiguration($configuration);

    $items = $this->getTestItem();
    $this->processor->preprocessIndexItems($items);
    $this->assertFieldsProcessed($items, ['text_field', 'float_field']);
  }

  /**
   * Tests whether overriding of processFieldValue() works correctly.
   */
  public function testProcessFieldValueOverride() {
    $override = function (&$value, &$type) {
      // Check whether the passed $type matches the one included in the value.
      if (strpos($value, "{$type}_field") !== FALSE) {
        $value = "&$value";
      }
      else {
        $value = "/$value";
      }
    };
    $this->processor->setMethodOverride('processFieldValue', $override);

    $items = $this->getTestItem();
    $this->processor->preprocessIndexItems($items);
    $this->assertFieldsProcessed($items, ['text_field', 'string_field'], '&');
  }

  /**
   * Tests whether removing values in processFieldValue() works correctly.
   */
  public function testProcessFieldRemoveValue() {
    $override = function (&$value) {
      if ($value != 'bar') {
        $value = "*$value";
      }
      else {
        $value = '';
      }
    };
    $this->processor->setMethodOverride('processFieldValue', $override);

    $fields = [
      'field1' => [
        'type' => 'string',
        'values' => [
          'foo',
          'bar',
        ],
      ],
    ];
    $items = $this->createItems($this->index, 1, $fields);

    $this->processor->preprocessIndexItems($items);

    $item_fields = $items[$this->itemIds[0]]->getFields();
    $this->assertEquals(['*foo'], $item_fields['field1']->getValues(), 'Field value was correctly removed.');
  }

  /**
   * Tests whether the processField() method operates correctly.
   */
  public function testProcessFieldsTokenized() {
    $override = function (&$value, $type) {
      switch ($type) {
        case 'integer':
          ++$value;
          return;

        case 'string':
          $value = "++$value";
          return;
      }

      if (strpos($value, ' ')) {
        $value = TestFieldsProcessorPlugin::createTokenizedText($value, 4)->getTokens();
      }
      elseif ($value == 'bar') {
        $value = TestFieldsProcessorPlugin::createTokenizedText('*bar', 2)->getTokens();
      }
      elseif ($value == 'baz') {
        $value = '';
      }
      else {
        $value = "*$value";
      }
    };
    $this->processor->setMethodOverride('processFieldValue', $override);

    $value = TestFieldsProcessorPlugin::createTokenizedText('foobar baz', 3);
    $tokens = $value->getTokens();
    $tokens[] = new TextToken('foo bar', 2);
    $value->setTokens($tokens);
    $fields = [
      'field1' => [
        'type' => 'text',
        'values' => [
          TestFieldsProcessorPlugin::createTokenizedText('foo bar baz', 3),
          $value,
          new TextValue('foo'),
          new TextValue('foo bar'),
          new TextValue('bar'),
          new TextValue('baz'),
        ],
      ],
      'field2' => [
        'type' => 'integer',
        'values' => [
          1,
          3,
        ],
      ],
      'field3' => [
        'type' => 'string',
        'values' => [
          'foo',
          'foo bar baz',
        ],
      ],
    ];
    $items = $this->createItems($this->index, 1, $fields);

    $this->processor->setConfiguration([
      'fields' => ['field1', 'field2', 'field3'],
    ]);

    $this->processor->preprocessIndexItems($items);

    $fields = $items[$this->itemIds[0]]->getFields();

    /** @var \Drupal\search_api\Plugin\search_api\data_type\value\TextValueInterface[] $values */
    $values = $fields['field1']->getValues();
    $summary = [];
    foreach ($values as $i => $value) {
      $summary[$i]['text'] = $value->toText();
      $tokens = $value->getTokens();
      if ($tokens !== NULL) {
        $summary[$i]['tokens'] = [];
        foreach ($tokens as $token) {
          $summary[$i]['tokens'][] = [
            'text' => $token->getText(),
            'boost' => $token->getBoost(),
          ];
        }
      }
    }
    $expected = [
      [
        'text' => '*foo *bar',
        'tokens' => [
          [
            'text' => '*foo',
            'boost' => 3,
          ],
          [
            'text' => '*bar',
            'boost' => 6,
          ],
        ],
      ],
      [
        'text' => '*foobar foo bar',
        'tokens' => [
          [
            'text' => '*foobar',
            'boost' => 3,
          ],
          [
            'text' => 'foo',
            'boost' => 8,
          ],
          [
            'text' => 'bar',
            'boost' => 8,
          ],
        ],
      ],
      [
        'text' => '*foo',
      ],
      [
        'text' => 'foo bar',
        'tokens' => [
          [
            'text' => 'foo',
            'boost' => 4,
          ],
          [
            'text' => 'bar',
            'boost' => 4,
          ],
        ],
      ],
      [
        'text' => '*bar',
        'tokens' => [
          [
            'text' => '*bar',
            'boost' => 2,
          ],
        ],
      ],
    ];
    $this->assertEquals($expected, $summary);

    $expected = [2, 4];
    $this->assertEquals('integer', $fields['field2']->getType());
    $this->assertEquals($expected, $fields['field2']->getValues());

    $expected = ['++foo', '++foo bar baz'];
    $this->assertEquals('string', $fields['field3']->getType());
    $this->assertEquals($expected, $fields['field3']->getValues());
  }

  /**
   * Tests whether preprocessing of queries without search keys works correctly.
   */
  public function testProcessKeysNoKeys() {
    $query = \Drupal::getContainer()
      ->get('search_api.query_helper')
      ->createQuery($this->index);

    $this->processor->preprocessSearchQuery($query);

    $this->assertNull($query->getKeys(), 'Query without keys was correctly ignored.');
  }

  /**
   * Tests whether preprocessing of simple search keys works correctly.
   */
  public function testProcessKeysSimple() {
    $query = \Drupal::getContainer()
      ->get('search_api.query_helper')
      ->createQuery($this->index);
    $keys = &$query->getKeys();
    $keys = 'foo';

    $this->processor->preprocessSearchQuery($query);

    $this->assertEquals('*foo', $query->getKeys(), 'Search keys were correctly preprocessed.');
  }

  /**
   * Tests whether preprocessing of complex search keys works correctly.
   */
  public function testProcessKeysComplex() {
    $query = \Drupal::getContainer()
      ->get('search_api.query_helper')
      ->createQuery($this->index);
    $keys = &$query->getKeys();
    $keys = [
      '#conjunction' => 'OR',
      'foo',
      [
        '#conjunction' => 'AND',
        'bar',
        'baz',
        '#negation' => TRUE,
      ],
    ];

    $this->processor->preprocessSearchQuery($query);

    $expected = [
      '#conjunction' => 'OR',
      '*foo',
      [
        '#conjunction' => 'AND',
        '*bar',
        '*baz',
        '#negation' => TRUE,
      ],
    ];
    $this->assertEquals($expected, $query->getKeys(), 'Search keys were correctly preprocessed.');
  }

  /**
   * Tests whether overriding of processKey() works correctly.
   */
  public function testProcessKeyOverride() {
    $override = function (&$value) {
      if ($value != 'baz') {
        $value = "&$value";
      }
      else {
        $value = '';
      }
    };
    $this->processor->setMethodOverride('processKey', $override);

    $query = \Drupal::getContainer()
      ->get('search_api.query_helper')
      ->createQuery($this->index);
    $keys = &$query->getKeys();
    $keys = [
      '#conjunction' => 'OR',
      'foo',
      [
        '#conjunction' => 'AND',
        'bar',
        'baz',
        '#negation' => TRUE,
      ],
    ];

    $this->processor->preprocessSearchQuery($query);

    $expected = [
      '#conjunction' => 'OR',
      '&foo',
      [
        '#conjunction' => 'AND',
        '&bar',
        '#negation' => TRUE,
      ],
    ];
    $this->assertEquals($expected, $query->getKeys(), 'Search keys were correctly preprocessed.');
  }

  /**
   * Tests whether preprocessing search conditions works correctly.
   */
  public function testProcessConditions() {
    $query = \Drupal::getContainer()
      ->get('search_api.query_helper')
      ->createQuery($this->index);
    $query->addCondition('text_field', 'foo');
    $query->addCondition('text_field', ['foo', 'bar'], 'IN');
    $query->addCondition('string_field', NULL, '<>');
    $query->addCondition('integer_field', 'bar');

    $this->processor->preprocessSearchQuery($query);

    $expected = [
      new Condition('text_field', '*foo'),
      new Condition('text_field', ['*foo', '*bar'], 'IN'),
      new Condition('string_field', 'undefined', '<>'),
      new Condition('integer_field', 'bar'),
    ];
    $this->assertEquals($expected, $query->getConditionGroup()->getConditions(), 'Conditions were preprocessed correctly.');
  }

  /**
   * Tests whether preprocessing nested search conditions works correctly.
   */
  public function testProcessConditionsNestedConditions() {
    $query = \Drupal::getContainer()
      ->get('search_api.query_helper')
      ->createQuery($this->index);
    $conditions = $query->createConditionGroup();
    $conditions->addCondition('text_field', 'foo');
    $conditions->addCondition('text_field', ['foo', 'bar'], 'IN');
    $conditions->addCondition('string_field', NULL, '<>');
    $conditions->addCondition('integer_field', 'bar');
    $query->addConditionGroup($conditions);

    $this->processor->preprocessSearchQuery($query);

    $expected = [
      new Condition('text_field', '*foo'),
      new Condition('text_field', ['*foo', '*bar'], 'IN'),
      new Condition('string_field', 'undefined', '<>'),
      new Condition('integer_field', 'bar'),
    ];
    $this->assertEquals($expected, $query->getConditionGroup()->getConditions()[0]->getConditions(), 'Conditions were preprocessed correctly.');
  }

  /**
   * Tests whether overriding processConditionValue() works correctly.
   */
  public function testProcessConditionValueOverride() {
    $override = function (&$value) {
      if (isset($value)) {
        $value = '';
      }
    };
    $this->processor->setMethodOverride('processConditionValue', $override);

    $query = \Drupal::getContainer()
      ->get('search_api.query_helper')
      ->createQuery($this->index);
    $query->addCondition('text_field', 'foo');
    $query->addCondition('string_field', NULL, '<>');
    $query->addCondition('integer_field', 'bar');

    $this->processor->preprocessSearchQuery($query);

    $expected = [
      new Condition('string_field', NULL, '<>'),
      new Condition('integer_field', 'bar'),
    ];
    $this->assertEquals($expected, array_merge($query->getConditionGroup()->getConditions()), 'Conditions were preprocessed correctly.');
  }

  /**
   * Tests whether overriding processConditionValue() works correctly.
   */
  public function testProcessConditionValueArrayHandling() {
    $override = function (&$value) {
      $length = strlen($value);
      if ($length == 2) {
        $value = '';
      }
      elseif ($length == 3) {
        $value .= '*';
      }
    };
    $this->processor->setMethodOverride('process', $override);

    $query = \Drupal::getContainer()
      ->get('search_api.query_helper')
      ->createQuery($this->index);
    $query->addCondition('text_field', ['a', 'b'], 'NOT IN');
    $query->addCondition('text_field', ['a', 'bo'], 'IN');
    $query->addCondition('text_field', ['ab', 'bo'], 'NOT IN');
    $query->addCondition('text_field', ['a', 'bo'], 'BETWEEN');
    $query->addCondition('text_field', ['ab', 'bo'], 'NOT BETWEEN');
    $query->addCondition('text_field', ['a', 'bar'], 'IN');
    $query->addCondition('text_field', ['abo', 'baz'], 'BETWEEN');

    $this->processor->preprocessSearchQuery($query);

    $expected = [
      new Condition('text_field', ['a', 'b'], 'NOT IN'),
      new Condition('text_field', ['a'], 'IN'),
      new Condition('text_field', ['a', 'bo'], 'BETWEEN'),
      new Condition('text_field', ['ab', 'bo'], 'NOT BETWEEN'),
      new Condition('text_field', ['a', 'bar*'], 'IN'),
      new Condition('text_field', ['abo*', 'baz*'], 'BETWEEN'),
    ];
    $this->assertEquals($expected, array_merge($query->getConditionGroup()->getConditions()), 'Conditions were preprocessed correctly.');
  }

  /**
   * Returns an array with one test item suitable for this test case.
   *
   * @param string[]|null $types
   *   (optional) The types of fields to create. Defaults to using "text",
   *   "string", "integer" and "float".
   *
   * @return \Drupal\search_api\Item\ItemInterface[]
   *   An array containing one item.
   */
  protected function getTestItem($types = NULL) {
    if ($types === NULL) {
      $types = ['text', 'string', 'integer', 'float'];
    }

    $fields = [];
    foreach ($types as $type) {
      $field_id = "{$type}_field";
      $fields[$field_id] = [
        'type' => $type,
        'values' => [
          "$field_id value 1",
          "$field_id value 2",
        ],
      ];
    }
    return $this->createItems($this->index, 1, $fields);
  }

  /**
   * Asserts that the given fields have been correctly processed.
   *
   * @param \Drupal\search_api\Item\ItemInterface[] $items
   *   An array containing one item.
   * @param string[] $processed_fields
   *   The fields which should be processed.
   * @param string $prefix
   *   (optional) The prefix that processed fields receive.
   */
  protected function assertFieldsProcessed(array $items, array $processed_fields, $prefix = "*") {
    $processed_fields = array_fill_keys($processed_fields, TRUE);
    foreach ($items as $item) {
      foreach ($item->getFields() as $field_id => $field) {
        if (!empty($processed_fields[$field_id])) {
          $expected = [
            "$prefix$field_id value 1",
            "$prefix$field_id value 2",
          ];
        }
        else {
          $expected = [
            "$field_id value 1",
            "$field_id value 2",
          ];
        }
        $this->assertEquals($expected, $field->getValues(), "Field $field_id is correct.");
      }
    }
  }

}


text:
<!doctype html>

    <title>Layer Definitions Example</title>
    <link rel="stylesheet" href="css/test_app.css" />
    <link rel="stylesheet" href="css/leaflet.css" />

redpajama_set_name: RedPajamaGithub


text:
<?php //-->
return function($request, $response) {
	//get settings from config
	$config = $this
		->package('global')
		->config('settings');

	if(!isset($config['debug_mode'])) {
		$config['debug_mode'] = 0;
	}

	if(!isset($config['argument_test'])) {
		$config['argument_test'] = false;
	}

	//if debug mode is on
	if($config['debug_mode'] && !ini_get('display_errors')) {
		ini_set('display_errors', '1');
	}

	//create a protocol like debug://hi
	$this->protocol('debug', function($event, $request, $response) {
		echo $event;
	});
};


text:
#!/bin/bash
set -x

# 注意:
# - ローカル開発を前提としているので、セキュリティの設定などは行なっていない
# - httpd, iptables の設定は上書きされるので、ゲスト OS 内でカスタマイズしている場合注意

# yum でのパッケージのインストール・更新は日本のミラーのみ利用 (時間短縮のため)
sudo sed -ie "s/^#include_only=.*/include_only=.jp/" /etc/yum/pluginconf.d/fastestmirror.conf

#yum update -y

# 共通パッケージ
yum install -y "http://ftp.riken.jp/Linux/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm"
yum install -y "http://rpms.famillecollet.com/enterprise/remi-release-6.rpm"
yum install -y ntp
yum install -y git
yum install -y vim-enhanced
chkconfig ntpd on

# httpd
yum install -y httpd
yum install -y mod_ssl
chkconfig httpd on

# vagrant 用 httpd 設定。設定は上書きされるので、カスタムする場合は注意
# /vagrant_data/www/public がデフォルトの公開ディレクトリになる。
# /vagrant_data/*/public で *.dev ドメインの利用も想定している
cat << EOS > /etc/httpd/conf.d/00-vagrant.conf
NameVirtualHost *:80
<Directory "/vagrant_data/*/public">
        Options -Indexes
        AllowOverride All
        # http://docs-v1.vagrantup.com/v1/docs/config/vm/share_folder.html
        EnableSendfile Off
</Directory>
<VirtualHost *:80>
        ServerName any
        DocumentRoot /vagrant_data/www/public
</VirtualHost>
<VirtualHost *:80>
        ServerName any
        ServerAlias *.dev
        VirtualDocumentRoot /vagrant_data/%1/public
</VirtualHost>
EOS

# php
yum install -y php php php-pear php-pdo php-mysql php-xml php-mbstring php-gd php-intl php-pecl-apc pcre
yum install -y php-pecl-xdebug

# php 追加パッケージ
# (EPELを利用。デフォルトで EPEL が有効なので、enablerepo の指定は不要だが、明示的にするため付与)
yum install -y --enablerepo=epel php-mcrypt php-phpunit-PHPUnit php-pear-Mail-Mime php-pear-Mail-mimeDecode php-pear-Mail php-pecl-mailparse

service httpd restart

# Firewall (iptables) の設定
cat << EOS > /etc/sysconfig/iptables
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

EOS
service iptables restart

yum install -y mysql-server
service mysqld restart
chkconfig mysqld on
echo "CREATE DATABASE dev;" | mysql

# composer
if [ ! -e /usr/local/bin/composer ]; then
	curl -sS https://getcomposer.org/installer | php
	mv composer.phar /usr/local/bin/composer
else
	/usr/local/bin/composer self-update
fi

cat << EOS

###########################################################################
#
# TO INSTALL LARAVEL:
#
# [host  ]$ vagrant ssh
# [guest ]$ cd /vagrant_data
# [guest ]$ composer create-project laravel/laravel --prefer-dist www
#
###########################################################################

EOS

# PHP 5.4
# yum update --enablerepo=remi


text:
'use strict';

// Replaces the element text with an array of spans
// and returns it
function splitTextInSpans(elem) {
  var letters = elem.textContent.split('');
  elem.innerHTML = '';
  return letters.map(function (letter) {
    var span = document.createElement('span');
    span.textContent = letter;
    elem.appendChild(span);
    return span;
  });
}

function intro() {
  function animateLogo(tl) {
    var maxWindowSize = Math.max(window.innerHeight, window.innerWidth);

    var squareDarkWrapper = document.querySelector('.square-dark-wrapper');
    var squareDark = squareDarkWrapper.querySelector('.square-dark');

    var square = document.querySelector('.square-wrapper');
    var lines = square.querySelectorAll('.line');

    var sparks = document.querySelectorAll('.spark');
    var outerCircle = document.querySelector('.outer-logo-circle .circle');
    var logo = document.querySelector('.pango-logo');

    tl.set(squareDark, {
      height: maxWindowSize,
      width: maxWindowSize
    }).set(lines, { scaleX: 0 });

    _.forEach(lines, function (line, i) {
      tl.to(lines[i], 2, {
        scaleX: 1,
        ease: 'Expo.easeOut'
      }, i / 10);
    });

    tl.to(lines, .05, {
      opacity: 0
    }, 1).to(squareDarkWrapper, 1.5, {
      scale: 1.4,
      ease: 'Expo.easeOut'
    }, 1).to(square, 2, {
      rotationZ: 45,
      ease: 'Expo.easeOut'
    }, 1.5).to(sparks, 1, {
      strokeDashoffset: 0,
      ease: 'Expo.easeOut'
    }, 1.5).to(sparks, 1, {
      strokeDashoffset: 145,
      ease: 'Expo.easeOut'
    }, 1.5).to(outerCircle, 1.4, {
      strokeDashoffset: 0,
      ease: 'Expo.easeInOut'
    }, 1.7).to(outerCircle, .4, {
      opacity: 0,
      ease: 'Power4.easeOut'
    }, 2.7).to(logo, 1, {
      opacity: 1,
      scale: 1,
      ease: 'Power4.easeOut'
    }, 2.7);

    return tl;
  }

  function animateWords(tl) {
    var wordsWrapper = document.querySelector('.pango-words');
    var words = wordsWrapper.querySelectorAll('.pango-word');
    var lineSeparator = wordsWrapper.querySelector('.line-separator');

    tl.set(lineSeparator, { scaleX: 0 }).to(lineSeparator, 1, {
      scaleX: 1,
      ease: 'Expo.easeOut'
    }, 3);

    _.forEach(words, function (word) {
      var spans = splitTextInSpans(word);
      _.forEach(spans, function (span, j) {
        var tlWords = new TimelineMax();

        tlWords.set(span, { y: span.clientHeight, opacity: 1 });
        var delay = (3 + Math.abs(spans.length / 2 - j) / 20).toFixed(2);
        tlWords.to(span, 1.4, {
          y: 0,
          ease: 'Expo.easeOut'
        }, delay);
      });
    });
    return tl;
  }

  function animateBackground(tl) {
    var wrapper = document.querySelector('.bg-lines-wrapper');
    var createLines = function createLines(qty) {
      for (var i = 0; i < qty; i++) {
        var line = document.createElement('div');
        line.classList.add('line');
        wrapper.appendChild(line);
        tl.set(line, {
          x: _.random(window.innerWidth),
          y: _.random(window.innerHeight),
          z: _.random(-200, 200),
          width: _.random(0, 100) + 50,
          scaleX: 0
        });
      }
    };

    function animateLines(lines) {
      for (var _iterator = lines, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
        var _ref;

        if (_isArray) {
          if (_i >= _iterator.length) break;
          _ref = _iterator[_i++];
        } else {
          _i = _iterator.next();
          if (_i.done) break;
          _ref = _i.value;
        }

        var line = _ref;

        var startTime = _.random(5, true);
        tl.to(line, .4, {
          scaleX: 1,
          ease: 'Expo.Power4'
        }, startTime).to(line, 2, {
          scaleX: 0,
          x: '+=' + line.style.width,
          ease: 'Power4.easeOut'
        }, startTime + .4);
      }

      // 3d rotation
      var rotate = function rotate(rx, ry) {
        TweenMax.to(wrapper, .75, {
          rotationX: ry,
          rotationY: rx,
          ease: 'Power0.easenone'
        });
      };

      // update rotation values
      function update(elem, event, tilt) {
        if (tilt) {
          var tiltLR = event.gamma;
          var tiltFB = event.beta;
          rotate(tiltLR / 1.5, tiltFB / 1.5);

          return;
        }

        var xpos = event.layerX || event.offsetX;
        var ypos = event.layerY || event.offsetY;

        var ax = -(window.innerWidth / 2 - xpos) / 40;
        var ay = (window.innerHeight / 2 - ypos) / 10;
        rotate(ax, ay);
      }

      // get element for mousemove event tracking
      // on top of all other layers
      var trackerLayer = document.querySelector('.mouse-tracker-layer');
      trackerLayer.addEventListener('mousemove', function (e) {
        return window.requestAnimationFrame(function () {
          return update(wrapper, e);
        });
      });

      if (window.DeviceOrientationEvent) {
        window.addEventListener('deviceorientation', function (e) {
          return window.requestAnimationFrame(function () {
            return update(wrapper, e, true);
          });
        });
      }
    }

    createLines(50);
    animateLines(wrapper.querySelectorAll('.line'));
  }

  return {
    animateLogo: animateLogo,
    animateWords: animateWords,
    animateBackground: animateBackground
  };
}

/*intro().animateBackground(new TimelineMax({
  delay: 2.8,
  repeat: -1,
  repeatDelay: 0
}))*/
intro().animateLogo(new TimelineMax());
intro().animateWords(new TimelineMax());


text:
<?php
/** @noinspection PhpLanguageLevelInspection */
declare(strict_types=1);
/**
 * @author @jenschude <jens.schulze@commercetools.de>
 */

namespace Commercetools\Core\Fixtures;

use Commercetools\Core\IntegrationTests\ApiTestCase;
use PHPUnit\Runner\AfterTestErrorHook;
use PHPUnit\Runner\AfterTestFailureHook;

class ErrorExtension implements AfterTestErrorHook, AfterTestFailureHook
{
    public function executeAfterTestError(string $test, string $message, float $time): void
    {
        if (is_a($test, ApiTestCase::class, true)) {
            $test::flushErrorLog();
        }
    }

    public function executeAfterTestFailure(string $test, string $message, float $time): void
    {
        if (is_a($test, ApiTestCase::class, true)) {
            $test::flushErrorLog();
        }
    }
}


text:
#pragma once

#include "GameOption.h"

class Debris;

class DebrisZone
{
public:
	DebrisZone();
	~DebrisZone();

	void Init( int id );

	void AddDebris( int key, Debris* debris );
	void RemoveDebris( int key );

	Debris* GetDebris( int key );

	void Update( float dt );

private:
	int m_ZoneId = -1;
	std::map<int, Debris*> m_DebrisList;
};


text:
const {Emitter, CompositeDisposable} = require('event-kit')

module.exports =
class AutoUpdateManager {
  constructor ({applicationDelegate}) {
    this.applicationDelegate = applicationDelegate
    this.subscriptions = new CompositeDisposable()
    this.emitter = new Emitter()
  }

  initialize () {
    this.subscriptions.add(
      this.applicationDelegate.onDidBeginCheckingForUpdate(() => {
        this.emitter.emit('did-begin-checking-for-update')
      }),
      this.applicationDelegate.onDidBeginDownloadingUpdate(() => {
        this.emitter.emit('did-begin-downloading-update')
      }),
      this.applicationDelegate.onDidCompleteDownloadingUpdate((details) => {
        this.emitter.emit('did-complete-downloading-update', details)
      }),
      this.applicationDelegate.onUpdateNotAvailable(() => {
        this.emitter.emit('update-not-available')
      }),
      this.applicationDelegate.onUpdateError(() => {
        this.emitter.emit('update-error')
      })
    )
  }

  destroy () {
    this.subscriptions.dispose()
    this.emitter.dispose()
  }

  checkForUpdate () {
    this.applicationDelegate.checkForUpdate()
  }

  restartAndInstallUpdate () {
    this.applicationDelegate.restartAndInstallUpdate()
  }

  getState () {
    return this.applicationDelegate.getAutoUpdateManagerState()
  }

  getErrorMessage () {
    return this.applicationDelegate.getAutoUpdateManagerErrorMessage()
  }

  platformSupportsUpdates () {
    return atom.getReleaseChannel() !== 'dev' && this.getState() !== 'unsupported'
  }

  onDidBeginCheckingForUpdate (callback) {
    return this.emitter.on('did-begin-checking-for-update', callback)
  }

  onDidBeginDownloadingUpdate (callback) {
    return this.emitter.on('did-begin-downloading-update', callback)
  }

  onDidCompleteDownloadingUpdate (callback) {
    return this.emitter.on('did-complete-downloading-update', callback)
  }

  // TODO: When https://github.com/atom/electron/issues/4587 is closed, we can
  // add an update-available event.
  // onUpdateAvailable (callback) {
  //   return this.emitter.on('update-available', callback)
  // }

  onUpdateNotAvailable (callback) {
    return this.emitter.on('update-not-available', callback)
  }

  onUpdateError (callback) {
    return this.emitter.on('update-error', callback)
  }

  getPlatform () {
    return process.platform
  }
}


text:
class SpreeSpraycanAbility
# stuff like class AbilityDecorator goes here
  include CanCan::Ability

  def initialize(user)
    #no rules yet, spree-auth admin can manage all is sufficient for now.
  end
end


text:
import random
import re
import subprocess
import sys

sys.path.append("external/pyparsing-2.4.5")
from pyparsing import *

import grammar

def random_ident():
    s = "".join(random.sample("abcdefghijklmnopqrstuvwxyz", random.randint(2, 9)))
    return s

class Generator:
    def __init__(self):
        self.tokens = []
        self.depth = 0

    def eval(self, node):
        self.depth += 1
        if hasattr(node, "name") and node.name == "Statement":
            self.tokens.append("\n" + " "*self.depth)
        if hasattr(node, "name") and node.name in ["Expression", "BracketedExpression"] and (random.uniform(0, 1) >= 0.05 or self.depth > 5):
            self.tokens.append(random_ident())
        elif node is grammar.table["Number"]:
            self.tokens.append("12345")
        elif node is grammar.table["Identifier"]:
            self.tokens.append(random_ident())
        elif node is grammar.table["StringLiteral"]:
            self.tokens.append('"foo"')
        elif node is grammar.table["ExecBody"]:
            self.tokens.append("select * from table;")
        elif isinstance(node, And):
            for e in node.exprs:
                self.eval(e)
        elif isinstance(node, Forward):
            self.eval(node.expr)
        elif isinstance(node, Group):
            self.eval(node.expr)
        elif isinstance(node, (Keyword, Literal)):
            self.tokens.append(node.match)
        elif isinstance(node, MatchFirst):
            self.eval(random.choice(node.exprs))
        elif isinstance(node, NotAny):
            pass
        elif isinstance(node, Optional):
            if random.choice([False, True]):
                self.eval(node.expr)
        elif isinstance(node, Or):
            self.eval(random.choice(node.exprs))
        elif isinstance(node, QuotedString):
            self.tokens.append('"foo"')
        elif isinstance(node, ZeroOrMore):
            while random.choice([False, True]):
                self.eval(node.expr)
        else:
            assert False, type(node)
        self.depth -= 1

neonc = "bin/neonc"

i = 1
while i < len(sys.argv):
    if sys.argv[i].startswith("-"):
        if sys.argv[i] == "--neonc":
            i += 1
            neonc = sys.argv[i]
        else:
            print("test-random: unknown option {}".format(sys.argv[i]))
            sys.exit(1)
    else:
        break
    i += 1

sys.setrecursionlimit(5000)
for _ in range(100):
    g = Generator()
    g.eval(grammar.parsers["Statement"])
    source = " ".join(map(str, g.tokens))
    #print(source)
    p = subprocess.Popen([neonc, "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate(source.encode())
    out = out.decode()
    err = err.decode()
    r = p.wait()
    if r < 0 or "Error N1" in err or "Error N2" in err:
        with open("tmp/random.out", "w") as f:
            f.write(source)
        print(err)
        print("Randomly generated source saved in tmp/random.out")
        sys.exit(1)


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.facebook.presto.type;

import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.function.ScalarFunction;
import com.facebook.presto.spi.function.ScalarOperator;
import com.facebook.presto.spi.function.SqlType;
import com.facebook.presto.spi.type.StandardTypes;
import io.airlift.slice.Slice;
import org.joda.time.chrono.ISOChronology;

import java.util.concurrent.TimeUnit;

import static com.facebook.presto.spi.StandardErrorCode.INVALID_CAST_ARGUMENT;
import static com.facebook.presto.spi.function.OperatorType.BETWEEN;
import static com.facebook.presto.spi.function.OperatorType.CAST;
import static com.facebook.presto.spi.function.OperatorType.EQUAL;
import static com.facebook.presto.spi.function.OperatorType.GREATER_THAN;
import static com.facebook.presto.spi.function.OperatorType.GREATER_THAN_OR_EQUAL;
import static com.facebook.presto.spi.function.OperatorType.HASH_CODE;
import static com.facebook.presto.spi.function.OperatorType.LESS_THAN;
import static com.facebook.presto.spi.function.OperatorType.LESS_THAN_OR_EQUAL;
import static com.facebook.presto.spi.function.OperatorType.NOT_EQUAL;
import static com.facebook.presto.spi.type.DateTimeEncoding.packDateTimeWithZone;
import static com.facebook.presto.spi.type.DateTimeEncoding.unpackMillisUtc;
import static com.facebook.presto.spi.type.DateTimeEncoding.unpackZoneKey;
import static com.facebook.presto.type.DateTimeOperators.modulo24Hour;
import static com.facebook.presto.util.DateTimeUtils.parseTimestampWithTimeZone;
import static com.facebook.presto.util.DateTimeUtils.printTimestampWithTimeZone;
import static com.facebook.presto.util.DateTimeZoneIndex.unpackChronology;
import static io.airlift.slice.SliceUtf8.trim;
import static io.airlift.slice.Slices.utf8Slice;

public final class TimestampWithTimeZoneOperators
{
    private TimestampWithTimeZoneOperators()
    {
    }

    @ScalarOperator(EQUAL)
    @SqlType(StandardTypes.BOOLEAN)
    public static boolean equal(@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long left, @SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long right)
    {
        return unpackMillisUtc(left) == unpackMillisUtc(right);
    }

    @ScalarOperator(NOT_EQUAL)
    @SqlType(StandardTypes.BOOLEAN)
    public static boolean notEqual(@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long left, @SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long right)
    {
        return unpackMillisUtc(left) != unpackMillisUtc(right);
    }

    @ScalarOperator(LESS_THAN)
    @SqlType(StandardTypes.BOOLEAN)
    public static boolean lessThan(@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long left, @SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long right)
    {
        return unpackMillisUtc(left) < unpackMillisUtc(right);
    }

    @ScalarOperator(LESS_THAN_OR_EQUAL)
    @SqlType(StandardTypes.BOOLEAN)
    public static boolean lessThanOrEqual(@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long left, @SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long right)
    {
        return unpackMillisUtc(left) <= unpackMillisUtc(right);
    }

    @ScalarOperator(GREATER_THAN)
    @SqlType(StandardTypes.BOOLEAN)
    public static boolean greaterThan(@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long left, @SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long right)
    {
        return unpackMillisUtc(left) > unpackMillisUtc(right);
    }

    @ScalarOperator(GREATER_THAN_OR_EQUAL)
    @SqlType(StandardTypes.BOOLEAN)
    public static boolean greaterThanOrEqual(@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long left, @SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long right)
    {
        return unpackMillisUtc(left) >= unpackMillisUtc(right);
    }

    @ScalarOperator(BETWEEN)
    @SqlType(StandardTypes.BOOLEAN)
    public static boolean between(
            @SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long value,
            @SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long min,
            @SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long max)
    {
        return unpackMillisUtc(min) <= unpackMillisUtc(value) && unpackMillisUtc(value) <= unpackMillisUtc(max);
    }

    @ScalarFunction("date")
    @ScalarOperator(CAST)
    @SqlType(StandardTypes.DATE)
    public static long castToDate(@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long value)
    {
        // round down the current timestamp to days
        ISOChronology chronology = unpackChronology(value);
        long date = chronology.dayOfYear().roundFloor(unpackMillisUtc(value));
        // date is currently midnight in timezone of the original value
        // convert to UTC
        long millis = date + chronology.getZone().getOffset(date);
        return TimeUnit.MILLISECONDS.toDays(millis);
    }

    @ScalarOperator(CAST)
    @SqlType(StandardTypes.TIME)
    public static long castToTime(@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long value)
    {
        return modulo24Hour(unpackChronology(value), unpackMillisUtc(value));
    }

    @ScalarOperator(CAST)
    @SqlType(StandardTypes.TIME_WITH_TIME_ZONE)
    public static long castToTimeWithTimeZone(@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long value)
    {
        int millis = modulo24Hour(unpackChronology(value), unpackMillisUtc(value));
        return packDateTimeWithZone(millis, unpackZoneKey(value));
    }

    @ScalarOperator(CAST)
    @SqlType(StandardTypes.TIMESTAMP)
    public static long castToTimestamp(@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long value)
    {
        return unpackMillisUtc(value);
    }

    @ScalarOperator(CAST)
    @SqlType(StandardTypes.VARCHAR)
    public static Slice castToSlice(@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long value)
    {
        return utf8Slice(printTimestampWithTimeZone(value));
    }

    @ScalarOperator(CAST)
    @SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE)
    public static long castFromSlice(ConnectorSession session, @SqlType(StandardTypes.VARCHAR) Slice value)
    {
        try {
            return parseTimestampWithTimeZone(session.getTimeZoneKey(), trim(value).toStringUtf8());
        }
        catch (IllegalArgumentException e) {
            throw new PrestoException(INVALID_CAST_ARGUMENT, "Value cannot be cast to timestamp with time zone: " + value.toStringUtf8(), e);
        }
    }

    @ScalarOperator(HASH_CODE)
    @SqlType(StandardTypes.BIGINT)
    public static long hashCode(@SqlType(StandardTypes.TIMESTAMP_WITH_TIME_ZONE) long value)
    {
        return unpackMillisUtc(value);
    }
}


text:
<!DOCTYPE html>

  <title>Tests that unprefixed animation events are correctly fired when using html event listeners (only unprefixed should be fired).</title>

Tests that unprefixed animation events are correctly fired when using html event listeners (only unprefixed should be fired).

FAIL: No animation events received


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using ExcelDna.Integration.Rtd;

namespace RtdPerformance
{
    [ComVisible(true)]                   // Required since the default template puts [assembly:ComVisible(false)] in the AssemblyInfo.cs
    [ProgId(RtdServer.ServerProgId)]     //  If ProgId is not specified, change the XlCall.RTD call in the wrapper to use namespace + type name (the default ProgId)
    public class RtdServer : ExcelRtdServer
    {
        public const string ServerProgId = "RtdPerformance.Server";

        static DataService _dataService;

        protected override bool ServerStart()
        {
            Debug.Print("ServerStart called");
            _dataService = new DataService();
            return true;
        }

        protected override void ServerTerminate()
        {
            if (_dataService == null)
            {
                Debug.Print("ServerStart not called ???");
                return;
            }

            _dataService.Terminate();
        }

        protected override object ConnectData(Topic topic, IList<string> topicInfo, ref bool newValues)
        {
            _dataService.ConnectTopic(topic);

            return topic.Value;
        }

        protected override void DisconnectData(Topic topic)
        {
            _dataService.DisconnectTopic(topic);
        }
    }
}


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.facebook.presto.sql.planner.plan;

import com.facebook.presto.spi.plan.Assignments;
import com.facebook.presto.spi.relation.VariableReferenceExpression;
import org.testng.annotations.Test;

import java.util.List;

import static com.facebook.presto.common.type.BigintType.BIGINT;
import static com.facebook.presto.sql.planner.iterative.rule.test.PlanBuilder.assignment;
import static com.facebook.presto.sql.tree.BooleanLiteral.TRUE_LITERAL;
import static org.testng.Assert.assertTrue;

public class TestAssignments
{
    private final Assignments assignments = assignment(new VariableReferenceExpression("test", BIGINT), TRUE_LITERAL);

    @Test(expectedExceptions = {UnsupportedOperationException.class})
    public void testOutputsImmutable()
    {
        List<VariableReferenceExpression> outputs = assignments.getOutputs();
        // should throw as it is an unmodifiableList
        outputs.add(new VariableReferenceExpression("test", BIGINT));
    }

    @Test
    public void testOutputsMemoized()
    {
        assertTrue(assignments.getOutputs() == assignments.getOutputs());
    }
}


text:
import { LiveAnnouncer } from '@angular/cdk/a11y';
import { ArrayDataSource } from '@angular/cdk/collections';
import { FlatTreeControl } from '@angular/cdk/tree';
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, OnChanges, Output, QueryList, SimpleChanges, TemplateRef, ViewChildren } from '@angular/core';
import { ColumnPickerService } from './column-picker.service';
import { ColumnPickerGroupItem, isColumnPickerGroupItem } from './interfaces/column-picker-group-item.interface';
import { ColumnPickerTreeNode } from './interfaces/column-picker-tree-node.interface';

@Component({
    selector: 'ux-column-picker',
    templateUrl: './column-picker.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
    providers: [ColumnPickerService]
})
export class ColumnPickerComponent implements OnChanges {

    /** Define a list of all selected columns. */
    @Input() selected: ReadonlyArray<string | ColumnPickerGroupItem> = [];

    /** Define a list of columns that are always selected. The columns cannot be moved or reordered. */
    @Input() locked: ReadonlyArray<string> = [];

    /** Define a list of columns that are not selected or locked. All columns must have unique names, including columns in different groups. */
    @Input() deselected: ReadonlyArray<string | ColumnPickerGroupItem> = [];

    /** Define a custom selected title template. */
    @Input() selectedTitleTemplate: TemplateRef<void>;

    /** Define a custom deselected title template. */
    @Input() deselectedTitleTemplate: TemplateRef<void>;

    /** Define a custom template for deselected items. */
    @Input() deselectedTemplate: TemplateRef<string>;

    /** Define a custom template for selected items. */
    @Input() selectedTemplate: TemplateRef<string>;

    /** Define a custom template for locked items. */
    @Input() lockedTemplate: TemplateRef<string>;

    /** Define a custom template for the action buttons columns. */
    @Input() actionsTemplate: TemplateRef<ColumnPickerActionsContext>;

    /** Define a function to get the aria label of reorderable items in the selected column. */
    @Input() selectedAriaLabel: (column: string | ColumnPickerGroupItem, index: number) => string = this.getDefaultSelectedAriaLabel;

    /** Define a function to get the aria label of a group in the deselected list. */
    @Input() deselectedGroupAriaLabel: (column: string | ColumnPickerGroupItem, isExpanded: boolean) => string = this.getDefaultDeselectedGroupAriaLabel;

    /** Define a function that returns a column move announcement. */
    @Input() columnMovedAnnouncement: (column: string | ColumnPickerGroupItem, delta: number) => string = this.getColumnMovedAnnouncement;

    /** Define settings for the grouped deselected items. */
    @Input() set groups(groups: ColumnPickerGroup[]) {
        this._columnPicker.groups = groups;
    }

    get groups(): ColumnPickerGroup[] {
        return this._columnPicker.groups;
    }

    /** Define a comparator function used for sorting the deselected columns. */
    @Input() sort: (a: ColumnPickerGroupItem, b: ColumnPickerGroupItem) => number;

    /** Emits when the selected items change or the order of the selected items change. */
    @Output() selectedChange = new EventEmitter<ReadonlyArray<string | ColumnPickerGroupItem>>();

    /** Emits when the deselected items change. */
    @Output() deselectedChange = new EventEmitter<ReadonlyArray<string | ColumnPickerGroupItem>>();

    /** The Nested tree control used for the deselect tree */
    _treeControl: FlatTreeControl<ColumnPickerTreeNode> = new FlatTreeControl<ColumnPickerTreeNode>(
        node => node.level,
        node => node.expandable
    );

    /** A tree-friendly representation of the deselected data */
    _treeData: ColumnPickerTreeNode[];

    /** Data source observable bound to the tree control */
    _treeDataSource: ArrayDataSource<ColumnPickerTreeNode>;

    /** The remaining selectable columns in the deselected list */
    _availableDeselectedColumns: number = 0;

    /** An array of items that are currently selected in the left column. */
    _deselectedSelection: ReadonlyArray<string | ColumnPickerGroupItem> = [];

    /** An array of items that are currently selected in the right column. */
    _selectedSelection: ReadonlyArray<string | ColumnPickerGroupItem> = [];

    /** Cache selection during reordering */
    private _selection: ReadonlyArray<string | ColumnPickerGroupItem> = [];

    /** Shallow copy of selection for reordering directive */
    _storedSelection: Array<string | ColumnPickerGroupItem> = [];

    /** Get the elements for the selected items */
    @ViewChildren('selectedColumn') selectedElements: QueryList<ElementRef>;

    constructor(
        private readonly _columnPicker: ColumnPickerService,
        /** Access the LiveAnnounce to provide accessibility on reordering */
        private readonly _liveAnnouncer: LiveAnnouncer,
        /** We are using OnPush change detection so we must manually trigger CD */
        private readonly _changeDetectorRef: ChangeDetectorRef
    ) { }

    ngOnChanges(changes: SimpleChanges): void {
        // recreate tree when deselected changes
        if (changes.deselected && changes.deselected.currentValue !== changes.deselected.previousValue) {
            this.rebuildDeselectTree();
        }
    }

    /** Parse data into suitable format for the FlatTreeComponent to understand and initialize deselect tree */
    private rebuildDeselectTree(): void {
        const columns = this._columnPicker.getDeselectedColumnsInPresentationOrder(this.deselected.slice(), this.sort);

        const treeData = this._columnPicker.createTreeData(columns);
        this._treeData = treeData;
        this._treeDataSource = new ArrayDataSource(treeData);

        // set initial count for deselected values
        this.updateAvailableDeselectedColumns();
    }

    /** A function that can be called to add columns. If no columns are passed to the function, the items that are selected in the left column will be added. */
    addColumns(columns: ReadonlyArray<string | ColumnPickerGroupItem> = this._deselectedSelection): void {
        const deselectedSelection = columns.filter(column => this.selected.indexOf(column) === -1);

        // add each item to the selected columns list
        this.selected = [...this.selected, ...deselectedSelection];

        this.deselected = this.deselected.filter(column => deselectedSelection.indexOf(column) === -1);

        // emit the selection changes
        this.selectedChange.emit(this.selected);
        this.deselectedChange.emit(this.deselected);

        // store the available deselected items
        this.updateAvailableDeselectedColumns();

        // clear the current selection
        this._deselectedSelection = [];
    }

    /** A function that can be called to remove columns. If no columns are passed to the function, the items that are selected in the right column will be removed. */
    removeColumns(columns: ReadonlyArray<string | ColumnPickerGroupItem> = this._selectedSelection): void {

        // remove each item from the selected columns list
        this.selected = this.selected.filter(column => columns.indexOf(column) === -1);

        this.deselected = [
            ...this.deselected,
            ...columns
        ];

        // emit the selection changes
        this.selectedChange.emit(this.selected);
        this.deselectedChange.emit(this.deselected);

        // store the available deselected items
        this.updateAvailableDeselectedColumns();

        // clear the current selection
        this._selectedSelection = [];
    }

    /** A function that can be called to add all columns. */
    addAllColumns(): void {
        this.addColumns(this.deselected);
    }

    /** A function that can be called to remove all columns. */
    removeAllColumns(): void {
        this.removeColumns(this.selected);
    }

    /** Ensure we don't select while dragging */
    storeSelection(): void {
        this._selection = [...this._selectedSelection];
        this._storedSelection = [...this.selected];
    }

    /** Restore the selection once dragging ends */
    restoreSelection(): void {
        this._selectedSelection = [...this._selection];
    }

    /** Update when reordering has occurred */
    onReorder(): void {
        this.selectedChange.emit(this.selected);
    }

    /** Get an aria label for deselected list groups */
    private getDefaultDeselectedGroupAriaLabel(column: string, isExpanded: boolean): string {
        return `Toggle ${column}`;
    }

    /** Get an aria label for reorderable items */
    private getDefaultSelectedAriaLabel(column: string, index: number): string {
        return `${column}. Press Alt up and alt down to reorder.`;
    }

    /** Get the announcement to read when a selected column is moved */
    getColumnMovedAnnouncement(column: string, delta: number): string {
        return `${column} column moved ${delta > 0 ? 'down' : 'up'}`;
    }

    /** Perform a reorder with the keyboard */
    move(column: string | ColumnPickerGroupItem, delta: number): void {
        // perform the move
        const index = this.selected.indexOf(column);
        this.swap(index, index + delta);

        // Announce the move if the order has changed
        if (this.selected.indexOf(column) !== index) {
            this._liveAnnouncer.announce(`Column moved ${delta > 0 ? 'down' : 'up'}`);
        }

        // emit the changes
        this.selectedChange.emit(this.selected);

        // perform change detection
        this._changeDetectorRef.detectChanges();

        // after the UI has updated focus the element again (ngFor creates new DOM elements)
        setTimeout(() => {
            const columnIndex = this.selected.indexOf(column);
            const target = this.selectedElements.toArray()[columnIndex];

            if (target) {
                // focus the element
                target.nativeElement.focus();
            }
        });
    }

    /** Provide a trackBy function for the reorderable options */
    selectedTrackBy(index: number, column: string | ColumnPickerGroupItem): string {
        return index + getColumnPickerGroupItemName(column);
    }

    /** Swap two elements in the selected columns array */
    private swap(source: number, target: number): void {

        // perform boundary checks
        if (target < 0 || target > this.selected.length - 1) {
            return;
        }

        // create a copy of the array to manipulate
        const selected = [...this.selected];

        // swap the array elements
        [selected[target], selected[source]] = [selected[source], selected[target]];

        // update the original array
        this.selected = [...selected];
    }

    /** Get the column name based on type */
    _getColumnName(item: string | ColumnPickerGroupItem): string {
        return isColumnPickerGroupItem(item) ? item.name : item;
    }

    /** Check if tree group has visible children */
    _nodeHasChildren(_: number, node: ColumnPickerTreeNode): boolean {
        return node.expandable;
    }

    _nodeHasAvailableChildren(node: ColumnPickerTreeNode): boolean {
        return node.children.filter(column => this.selected.indexOf(column) === -1).length > 0;
    }

    /** Check to see if current item should display in deselect tree */
    _shouldRenderNode(node: ColumnPickerTreeNode): boolean {
        const parent = this.getTreeParent(node);

        return (!parent || parent.isExpanded) && !this.selected.find(column => this._getColumnName(column) === node.name);
    }

    /** Work backwards from the index of the current node to find the parent node  */
    private getTreeParent(node: ColumnPickerTreeNode): ColumnPickerTreeNode {
        const nodeIndex = this._treeData.indexOf(node);

        if (node.level > 0) {
            for (let i: number = nodeIndex - 1; i >= 0; i--) {
                if (this._treeData[i].level === 0) {
                    return this._treeData[i];
                }
            }
        }

        return null;
    }

    /** Store the current count of nodes that are available for selection from the deselected list */
    private updateAvailableDeselectedColumns(): void {
        this._availableDeselectedColumns = this.deselected.length;
    }

    /** Update the order of the items when reordering has changed */
    onReorderChange(model: string[]): void {
        this.selected = [...model];
        this.onReorder();
    }

    /** Get the action context, ensuring that functions have a pre-bound context */
    _getActionContext(): ColumnPickerActionsContext {
        return {
            addSelection: this._deselectedSelection,
            removeSelection: this._selectedSelection,
            addColumns: this.addColumns.bind(this),
            removeColumns: this.removeColumns.bind(this),
            addAllColumns: this.addAllColumns.bind(this),
            removeAllColumns: this.removeAllColumns.bind(this)
        };
    }

    /** Change the expanded state of a node */
    _setNodeExpanded(node: ColumnPickerTreeNode, isExpanded: boolean): void {
        node.isExpanded = isExpanded;

        // the first change detection cycle will hide the elements but we need to trigger
        // a second change detection cycle on the next tick to ensure the ContentChildren
        // QueryList gets updated in the uxTabbableList directive
        requestAnimationFrame(() => this._changeDetectorRef.detectChanges());
    }
}

function getColumnPickerGroupItemName(column: string | ColumnPickerGroupItem) {
    return isColumnPickerGroupItem(column) ? column.name : column;
}

/** Define a context for the column actions template */
export interface ColumnPickerActionsContext {
    /** An array of items that are currently selected in the left column. */
    addSelection: ReadonlyArray<string | ColumnPickerGroupItem>;
    /** An array of items that are currently selected in the right column. */
    removeSelection: ReadonlyArray<string | ColumnPickerGroupItem>;
    /** A function that can be called to add columns. If no columns are passed to the function, the items that are selected in the left column will be added. */
    addColumns(columns?: ReadonlyArray<string | ColumnPickerGroupItem>): void;
    /** A function that can be called to remove columns. If no columns are passed to the function, the items that are selected in the right column will be removed. */
    removeColumns(columns?: ReadonlyArray<string | ColumnPickerGroupItem>): void;
    /** A function that can be called to add all columns. */
    addAllColumns(): void;
    /** A function that can be called to remove all columns. */
    removeAllColumns(): void;
}

/** An interface representing settings of groups defined in ColumnPickerGroupItem objects */
export interface ColumnPickerGroup {
    /**  The name of the group this setting object is related to. */
    name: string;
    /**  Defines if this group will be expanded on load. This is an optional property. */
    expanded?: boolean;
}


text:
<?php
/**
 * This file is a part of CSCFA navbar project.
 *
 * The navbar project is a symfony bundle written in php
 * with Symfony2 framework.
 *
 * PHP version 5.5
 *
 * @category Twig extension
 * @package  CscfaNavBarBundle
 * @author   Matthieu VALLANCE <matthieu.vallance@cscfa.fr>
 * @license  http://opensource.org/licenses/MIT MIT
 * @filesource
 * @link     http://cscfa.fr
 */
namespace Cscfa\Bundle\NavBarBundle\Twig\Extension;

use Cscfa\Bundle\NavBarBundle\Objects\NavBarLoader;
use Symfony\Component\Security\Core\SecurityContext;
use Cscfa\Bundle\NavBarBundle\Objects\NavBar;
use Symfony\Bundle\TwigBundle\TwigEngine;
use Cscfa\Bundle\NavBarBundle\Objects\NavBarElement;
use Symfony\Bundle\FrameworkBundle\Routing\Router;

/**
 * NavBarExtension class.
 *
 * The NavBarExtension class define
 * the twig extension to display
 * the CSManager navigation bar.
 *
 * @category Twig extension
 * @package  CscfaNavBarBundle
 * @author   Matthieu VALLANCE <matthieu.vallance@cscfa.fr>
 * @license  http://opensource.org/licenses/MIT MIT
 * @link     http://cscfa.fr
 */
class NavBarExtension extends \Twig_Extension
{

    const DEFAULT_TEMPLATE = "CscfaNavBarBundle:navbar:navbar.html.twig";
    const DEFAULT_CHILD_TEMPLATE = "CscfaNavBarBundle:navbar:child.html.twig";

    /**
     * User
     *
     * The current user
     *
     * @var User
     */
    protected $user;

    /**
     * Router
     *
     * The application router service
     *
     * @var Router
     */
    protected $router;

    /**
     * Loader
     *
     * The navbar loader service
     *
     * @var NavBarLoader
     */
    protected $loader;

    /**
     * Template
     *
     * The main template to use
     *
     * @var string
     */
    protected $template;

    /**
     * Child template
     *
     * The template to use to
     * render child
     *
     * @var string
     */
    protected $childTemplate;

    /**
     * Constructor
     *
     * Default constructor
     *
     * @param NavBarLoader    $loader  - the navbar loader service
     * @param SecurityContext $context - the security context service
     * @param Router          $router  - the application router service
     */
    public function setArguments(NavBarLoader $loader, SecurityContext $context, Router $router, $config)
    {
        $template = $config['template'];
        $childTemplate = $config['child_template'];

        if ($template !== null) {
            $this->template = $template;
        } else {
            $this->template = self::DEFAULT_TEMPLATE;
        }

        if ($childTemplate !== null) {
            $this->childTemplate = $childTemplate;
        } else {
            $this->childTemplate = self::DEFAULT_CHILD_TEMPLATE;
        }

        $this->router = $router;
        $this->loader = $loader;

        if (method_exists($context->getToken(), 'getUser') &&
            is_object($context->getToken()->getUser()) &&
            method_exists($context->getToken(), 'getRoles')) {
            $this->user = $context->getToken()->getUser();
        } else {
            $this->user = null;
        }
    }

    /**
     * Get function
     *
     * Return the mapping of
     * the function name and
     * class methods
     *
     * @see Twig_Extension::getFunctions()
     */
    public function getFunctions() {
        return array(
            new \Twig_SimpleFunction('renderNavbar', array($this, 'renderNavbar'), array(
                    'is_safe' => array('html'),
                    'needs_environment' => true
                )
            )
        );
    }

    /**
     * Get filters
     *
     * Return the mapping of
     * the filters name and
     * class methods
     *
     * @see Twig_Extension::getFilters()
     */
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('navbarChild', array($this, 'renderChild'), array(
                    'is_safe' => array('html'),
                    'needs_environment' => true
                )
            ),
        );
    }

    /**
     * Render navbar
     *
     * Return a rendered twig
     * view that contain the
     * html navbar
     *
     * @param \Twig_Environment $twig - the current twig environment
     *
     * @return string - The rendered template
     */
    public function renderNavbar(\Twig_Environment $twig){

        $navbar = $this->loader->buildNavbar($this->router);
        $elements = $navbar->getElements();

        if ($this->user !== null) {
            $roles = $this->user->getRoles();
        } else {
            $roles = array();
        }

        foreach ($elements as $key=>$element) {
            if (!$this->checkRole($element, $roles)) {
                unset($elements[$key]);
            }
        }

        $navbar->setElements($elements);

        return $twig->render($this->template, array("navbar"=>$navbar->getHead()));
    }

    /**
     * Render child
     *
     * Return a rendered twig
     * view that contain the
     * html elements
     *
     * @param \Twig_Environment $twig        - the current twig environment
     * @param NavBarElement     $child       - the element to render
     * @param integer           $nestedLevel - the element nesting level
     *
     * @return string - The rendered template
     */
    public function renderChild(\Twig_Environment $twig, NavBarElement $child, $nestedLevel){
        return $twig->render($this->childTemplate, array("element"=>$child, "nestedLevel"=>($nestedLevel + 1)));
    }

    /**
     * Check role
     *
     * Verify if the user has
     * granted the needed roles
     * of the element and it's
     * childs and remove it if
     * not
     *
     * @param NavBarElement $element  - the element to valid
     * @param array         $userRole - the user roles array
     *
     * @return boolean
     */
    protected function checkRole(&$element, $userRole){
        if($element instanceof NavBarElement){

            $elementRoles = $element->getRoles();
            if (!is_array($elementRoles)) {
                $elementRoles = array();
            }

            foreach ($elementRoles as $role) {
                if (!in_array($role, $userRole)) {
                    return false;
                }
            }

            $childs = $element->getChild();
            if(!empty($childs)){
                foreach ($childs as $key=>$child) {
                    if(!$this->checkRole($child, $userRole)){
                        unset($childs[$key]);
                    }
                }
            }
            $element->setChild($childs);
        }

        return true;
    }

    /**
     * Get name
     *
     * Return the current extension name
     *
     * @see Twig_ExtensionInterface::getName()
     * @return string
     */
    public function getName()
    {
        return 'cs_navbar_extension';
    }
}


text:
<?php
class Kwc_Basic_LinkTag_CommunityVideo_Lightbox_ContentSender extends Kwf_Component_Abstract_ContentSender_Lightbox
{
    protected function _getOptions()
    {
        $ret = parent::_getOptions();
        $ret['width'] = $this->_data->getChildComponent('-video')->getComponent()->getRow()->width;
        $ret['height'] = $this->_data->getChildComponent('-video')->getComponent()->getRow()->height;
        return $ret;
    }
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:clip="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.jvw.clip.Manage">
    <item
        android:id="@+id/manage_add"
        android:icon="@drawable/ic_action_new"
        android:showAsAction="ifRoom"
        android:title="@string/add"
        clip:showAsAction="ifRoom" />
</menu>


text:
function three_state_SS_ATPase_RU_g(current_model,current_data) result(ATPase)
	use h_struct
	use h_models
	use h_routine_specific_vars
	implicit none
	type(model_struct), pointer :: current_model
	type (data_struct),pointer :: current_data
	real,dimension(current_data%len) :: ATPase

! constants
	integer,parameter :: n=3

! Local Var's
	real,dimension(current_data%len,n) :: A_M
	real :: offset,A_zero
	real,dimension(current_data%len) :: g_save
	real :: w2
! begin
! the raw F that is calculated is the duty cycle of myosin x-bridges
! so Fo needs to scale this value to the data.
	call init_tsv()

	w2=		param_list(current_model%model%param(1)%param_basis(10))%val
	tsv%w2=exp(-w2)

	offset=param_list(current_model%model%param(2)%param_basis(1))%val
	A_zero=param_list(current_model%model%param(2)%param_basis(2))%val
	A_M=three_state_SS(current_model,current_data,g_save)
	! A_M contains the n species concentrations.
	ATPase(:)=g_save(:)*A_M(:,3)
	ATPase=ATPase*A_zero + offset
end function


text:
package com.appsingularity.ristretto.lint.checks.detectors;

import com.android.tools.lint.detector.api.Category;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Implementation;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.JavaContext;
import com.android.tools.lint.detector.api.Scope;
import com.android.tools.lint.detector.api.Severity;
import com.appsingularity.ristretto.lint.checks.detectors.util.MethodDefinition;
import com.appsingularity.ristretto.lint.checks.detectors.util.MethodDefinitions;

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

import lombok.ast.AstVisitor;
import lombok.ast.MethodInvocation;

import static com.appsingularity.ristretto.lint.checks.detectors.util.DetectorUtils.argumentsAsString;
import static com.appsingularity.ristretto.lint.checks.detectors.util.DetectorUtils.getFirstArgument;
import static com.appsingularity.ristretto.lint.checks.detectors.util.DetectorUtils.isNode;
import static com.appsingularity.ristretto.lint.checks.detectors.util.DetectorUtils.isWithNode;

public class OnViewDetector extends Detector implements Detector.JavaScanner {
    private static final String MESSAGE_FORMAT = "Consider using `withView({0})`";
    private static final MethodDefinition METHOD_CALL = MethodDefinitions.ON_VIEW;
    public static final Issue ISSUE = Issue.create(
            IssuesIds.WITH_VIEW_ISSUE_ID,
            "Statement can be simplified",
            "You could be using `Ristretto.withView()` which is shorter and easier to read.",
            Category.USABILITY, 6, Severity.INFORMATIONAL,
            new Implementation(OnViewDetector.class, Scope.JAVA_FILE_SCOPE));

    // region JavaScanner
    @Override
    public List<String> getApplicableMethodNames() {
        return Collections.singletonList(METHOD_CALL.methodName);
    }

    @Override
    public void visitMethod(JavaContext context, AstVisitor visitor, MethodInvocation node) {
        if (isNode(context, node, METHOD_CALL)) {
            MethodInvocation first = getFirstArgument(node);
            if (isWithNode(context, first)) {
                String message = argumentsAsString(first, MESSAGE_FORMAT);
                context.report(ISSUE, node, context.getLocation(node), message);
            }
        }
    }
    // endregion

}


text:
using QuantConnect.Data.Market;

namespace QuantConnect.Indicators.CandlestickPatterns
{
    /// <summary>
    /// Engulfing candlestick pattern
    /// </summary>
    /// <remarks>
    /// Must have:
    /// - first: black (white) real body
    /// - second: white(black) real body that engulfs the prior real body
    /// The returned value is positive(+1) when bullish or negative(-1) when bearish;
    /// The user should consider that an engulfing must appear in a downtrend if bullish or in an uptrend if bearish,
    /// while this function does not consider it
    /// </remarks>
    public class Engulfing : CandlestickPattern
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Engulfing"/> class using the specified name.
        /// </summary>
        /// <param name="name">The name of this indicator</param>
        public Engulfing(string name)
            : base(name, 3)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Engulfing"/> class.
        /// </summary>
        public Engulfing()
            : this("ENGULFING")
        {
        }

        /// <summary>
        /// Gets a flag indicating when this indicator is ready and fully initialized
        /// </summary>
        public override bool IsReady
        {
            get { return Samples >= Period; }
        }

        /// <summary>
        /// Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="window">The window of data held in this indicator</param>
        /// <param name="input">The input given to the indicator</param>
        /// <returns>A new value for this indicator</returns>
        protected override decimal ComputeNextValue(IReadOnlyWindow<TradeBar> window, TradeBar input)
        {
            if (!IsReady)
            {
                return 0m;
            }

            decimal value;
            if (
                // white engulfs black
                (GetCandleColor(input) == CandleColor.White && GetCandleColor(window[1]) == CandleColor.Black &&
                  input.Close > window[1].Open && input.Open < window[1].Close
                )
                ||
                // black engulfs white
                (GetCandleColor(input) == CandleColor.Black && GetCandleColor(window[1]) == CandleColor.White &&
                  input.Open > window[1].Close && input.Close < window[1].Open
                )
              )
                value = (int)GetCandleColor(input);
            else
                value = 0;

            return value;
        }
    }
}


text:
module AjaxController::Vote
  # Cast vote. Renders new set of vote controls for HTML page if image,
  # nothing if naming.
  # type::  Type of object.
  # id::    ID of object.
  # value:: Value of vote.
  def vote
    @user = session_user!
    case @type
    when "naming"
      cast_naming_vote(@id, @value)
    when "image"
      cast_image_vote(@id, @value)
    end
  end

  private

  def cast_naming_vote(id, value_str)
    @naming = Naming.includes(
      observation: { namings: :votes }
    ).find_by(id: id)
    value = Vote.validate_value(value_str)
    raise("Bad value.") unless value

    @naming.change_vote(value, @user)
    @observation = @naming.observation
    @votes = gather_users_votes(@observation, @user)
    render(inline: %(<div>
      <%= content_tag(:div, show_obs_title(@observation),
            title: show_obs_title(@observation).strip_html.html_safe) %>
      <%= content_tag(:div, render(partial: 'naming/show',
            locals: { observation: @observation })) %>
    </div>))
  end

  def cast_image_vote(id, value)
    image = Image.find(id)
    raise("Bad value.") if value != "0" && !Image.validate_vote(value)

    value = value == "0" ? nil : Image.validate_vote(value)
    anon = (@user.votes_anonymous == "yes")
    image.change_vote(@user, value, anon: anon)
    render(partial: "image/image_vote_links", locals: { image: image })
  end
end


text:
namespace NUnit.Framework.Constraints
{
    [TestFixture]
    public class SameAsTest : ConstraintTestBase
    {
        private static readonly object obj1 = new object();
        private static readonly object obj2 = new object();

        [SetUp]
        public void SetUp()
        {
            theConstraint = new SameAsConstraint(obj1);
            expectedDescription = "same as <System.Object>";
            stringRepresentation = "<sameas System.Object>";
        }

        static object[] SuccessData = new object[] { obj1 };

        static object[] FailureData = new object[] {
            new TestCaseData( obj2, "<System.Object>" ),
            new TestCaseData( 3, "3" ),
            new TestCaseData( "Hello", "\"Hello\"" ) };
    }
}


text:
/*************************************************************************/
/*  project_settings_editor.h                                            */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef PROJECT_SETTINGS_EDITOR_H
#define PROJECT_SETTINGS_EDITOR_H

#include "core/object/undo_redo.h"
#include "editor/action_map_editor.h"
#include "editor/editor_data.h"
#include "editor/editor_plugin_settings.h"
#include "editor/editor_sectioned_inspector.h"
#include "editor/import_defaults_editor.h"
#include "editor/localization_editor.h"
#include "editor/shader_globals_editor.h"
#include "editor_autoload_settings.h"
#include "scene/gui/tab_container.h"

class ProjectSettingsEditor : public AcceptDialog {
	GDCLASS(ProjectSettingsEditor, AcceptDialog);

	static ProjectSettingsEditor *singleton;
	ProjectSettings *ps;
	Timer *timer;

	TabContainer *tab_container;
	SectionedInspector *inspector;
	ActionMapEditor *action_map;
	LocalizationEditor *localization_editor;
	EditorAutoloadSettings *autoload_settings;
	ShaderGlobalsEditor *shaders_global_variables_editor;
	EditorPluginSettings *plugin_settings;

	LineEdit *search_box;
	CheckButton *advanced;

	LineEdit *property_box;
	OptionButton *feature_box;
	OptionButton *type_box;
	Button *add_button;
	Button *del_button;

	Label *restart_label;
	TextureRect *restart_icon;
	PanelContainer *restart_container;
	Button *restart_close_button;

	ImportDefaultsEditor *import_defaults_editor;
	EditorData *data;
	UndoRedo *undo_redo;

	void _advanced_toggled(bool p_button_pressed);
	void _property_box_changed(const String &p_text);
	void _update_property_box();
	void _feature_selected(int p_index);
	void _select_type(Variant::Type p_type);

	String _get_setting_name() const;
	void _setting_edited(const String &p_name);
	void _setting_selected(const String &p_path);
	void _add_setting();
	void _delete_setting();

	void _editor_restart_request();
	void _editor_restart();
	void _editor_restart_close();

	void _add_feature_overrides();

	void _action_added(const String &p_name);
	void _action_edited(const String &p_name, const Dictionary &p_action);
	void _action_removed(const String &p_name);
	void _action_renamed(const String &p_old_name, const String &p_new_name);
	void _action_reordered(const String &p_action_name, const String &p_relative_to, bool p_before);
	void _update_action_map_editor();

	ProjectSettingsEditor();

protected:
	void _notification(int p_what);
	static void _bind_methods();

public:
	static ProjectSettingsEditor *get_singleton() { return singleton; }
	void popup_project_settings();
	void set_plugins_page();
	void update_plugins();

	EditorAutoloadSettings *get_autoload_settings() { return autoload_settings; }
	TabContainer *get_tabs() { return tab_container; }

	void queue_save();

	ProjectSettingsEditor(EditorData *p_data);
};

#endif // PROJECT_SETTINGS_EDITOR_H


text:
package me.pims.moves.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;

import java.net.URL;

public abstract class BaseDeserializationTest {

    public final ObjectMapper objectMapper = new ObjectMapper();

    public String getJSON(final String filePath) throws Exception {
        URL url = Resources.getResource(filePath);
        return Resources.toString(url, Charsets.UTF_8);
    }

    public abstract void deserializeTest() throws Exception;
}


text:
  #ifdef MESON_STATIC_BUILD
   #define SYMBOL_EXPORT
   #define SYMBOL_IMPORT
  #else
   #define SYMBOL_IMPORT __declspec(dllimport)
   #define SYMBOL_EXPORT __declspec(dllexport)
  #endif
#else
  #define SYMBOL_IMPORT
  #if defined __GNUC__
    #define SYMBOL_EXPORT __attribute__ ((visibility("default")))
  #else
    #pragma message ("Compiler does not support symbol visibility.")
    #define SYMBOL_EXPORT
  #endif
#endif


text:
/**
 *
 */
package fr.univrouen.poste.provider;

import fr.univrouen.poste.domain.User;
import org.apache.log4j.Logger;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class DatabaseUserDetailsService implements UserDetailsService {

	private final Logger logger = Logger.getLogger(getClass());

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {

		username = username.trim().toLowerCase();

		TypedQuery<User> query = User.findUsersByEmailAddress(username, null, null);

		try {
			User targetUser = (User) query.getSingleResult();
			return loadUserByUser(targetUser);
		} catch(EmptyResultDataAccessException | NoResultException e) {
			throw new RuntimeException(username + " not found in the Database.", e);
		}
	}

	public UserDetails loadUserByUser(User targetUser)
			throws UsernameNotFoundException {

		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		Boolean enabled;

		// Roles
		if (targetUser.getIsAdmin()) {
			authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
		}
		if (targetUser.getIsCandidat()) {
			// TODO : check date
			authorities.add(new SimpleGrantedAuthority("ROLE_CANDIDAT"));
		}
		if (targetUser.getIsManager()) {
			authorities.add(new SimpleGrantedAuthority("ROLE_MANAGER"));
		}
		if (targetUser.getIsSuperManager()) {
			authorities.add(new SimpleGrantedAuthority("ROLE_MANAGER"));
			authorities.add(new SimpleGrantedAuthority("ROLE_SUPER_MANAGER"));
		}
		if (targetUser.getIsMembre()) {
			// TODO : check date
			authorities.add(new SimpleGrantedAuthority("ROLE_MEMBRE"));
		}

		// Enabled
		enabled = targetUser.getEnabled();

		return new org.springframework.security.core.userdetails.User(targetUser.getEmailAddress(), targetUser.getPassword() == null ? "dummy" : targetUser.getPassword(), enabled, // enabled
				true, // account not expired
				true, // credentials not expired
				true, // account not locked
				authorities);

	}

}


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

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.spy;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.gluster.GlusterHookParameters;
import org.ovirt.engine.core.common.errors.EngineMessage;

@RunWith(MockitoJUnitRunner.class)
public class EnableGlusterHookCommandTest extends GlusterHookCommandTest<EnableGlusterHookCommand<GlusterHookParameters>> {
    /**
     * The command under test.
     */

    EnableGlusterHookCommand<GlusterHookParameters> cmd;

    @Test
    public void executeCommand() {
        cmd = spy(new EnableGlusterHookCommand<>(new GlusterHookParameters(HOOK_ID)));
        setupMocks(cmd);
        mockBackendStatusChange(cmd, true);
        cmd.executeCommand();
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_HOOK_ENABLE);
    }

    @Test
    public void executeCommandWhenFailed() {
        cmd = spy(new EnableGlusterHookCommand<>(new GlusterHookParameters(HOOK_ID)));
        setupMocks(cmd);
        mockBackendStatusChange(cmd, false);
        cmd.executeCommand();
        assertEquals(cmd.getAuditLogTypeValue(), AuditLogType.GLUSTER_HOOK_ENABLE_FAILED);
    }

    @Test
    public void validateSucceeds() {
        cmd = spy(new EnableGlusterHookCommand<>(new GlusterHookParameters(HOOK_ID)));
        setupMocks(cmd);
        assertTrue(cmd.validate());
    }

    @Test
    public void validateFailsOnNullHookId() {
        cmd = spy(new EnableGlusterHookCommand<>(new GlusterHookParameters(null)));
        setupMocks(cmd);
        assertFalse(cmd.validate());
        assertTrue(cmd.getReturnValue().getValidationMessages().contains(EngineMessage.ACTION_TYPE_FAILED_GLUSTER_HOOK_ID_IS_REQUIRED.toString()));
    }

    @Test
    public void validateFailsOnNoHook() {
        cmd = spy(new EnableGlusterHookCommand<>(new GlusterHookParameters(HOOK_ID)));
        setupMocks(cmd, false);
        assertFalse(cmd.validate());
        assertTrue(cmd.getReturnValue().getValidationMessages().contains(EngineMessage.ACTION_TYPE_FAILED_GLUSTER_HOOK_DOES_NOT_EXIST.toString()));
    }

}


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

namespace MH4U_Database.Database
{
    class HuntingReward
    {
        public int _id { get; set; }
        public string condition { get; set; }
        public int percentage { get; set; }
        public string rank { get; set; }
        public int stack_size { get; set; }

        //Item Variables
        public string item_name { get; set; }
        public int item_id { get; set; }
        public string item_icon { get; set; }
        public string item_icon_path
        {
            get
            {
                return "/Assets/icons_items/" + item_icon;
            }
        }

        //Monster Variables
        public string monster_name { get; set; }
        public int monster_id { get; set; }
        public string monster_icon { get; set; }
        public string monster_icon_path
        {
            get
            {
                return "/Assets/icons_monster/" + monster_icon;
            }
        }

    }
}


text:
%
%initialize the trial-by-trial averages
%
function trialDataInit = getTrialDataInit
trialDataInit.updatePlotPending = 0;

%trialDataInit.nTrialsLFP=0;   %LFP trials
%trialDataInit.LFPtrials=[];
%trialDataInit.LFPav=[];

%trialDataInit.nTrialsRaster = 0;  %raster
%trialDataInit.spikeTimepoints=struct('times',[]);   %structure, (x) is list of timestamps relative offset for every trial x


text:
package main

import (
	"github.com/hashicorp/terraform/plugin"
)

func main() {
	plugin.Serve(&plugin.ServeOpts{
		ProviderFunc: ScriptProvider,
	})
}


text:
"""
init.py

Starting script to run NetPyNE-based M1 model.

Usage:
    python init.py # Run simulation, optionally plot a raster

MPI usage:
    mpiexec -n 4 nrniv -python -mpi init.py
"""

import matplotlib; matplotlib.use('Agg')  # to avoid graphics error in servers

from netpyne import sim
from cfg import cfg
from netParams import netParams

print("Starting sim ...")
sim.createSimulateAnalyze(netParams, cfg)

# Check the model output: sim.checkOutput is used for testing purposes.  Please comment out the following line if you are exploring the example.
sim.checkOutput('M1detailed')


text:
/**
 * Controller for the "GUAC_CAS_TICKET" field which simply redirects the user
 * immediately to the authorization URI.
 */
angular.module('guacCAS').controller('guacCASController', ['$scope',
    function guacCASController($scope) {

        // Redirect to authorization URI
        window.location = $scope.field.authorizationURI;

}]);


text:
<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <title>Agenda 1.0 - [LISTADO]</title>
    <link rel="stylesheet" href="css/reset.css"/>
    <link rel="stylesheet" href="css/estilos.css"/>
    <link rel="stylesheet" href="css/font-awesome.min.css"/>
    <link rel="shortcut icon" type="image/png" href="img/logo.png"/>

Agenda 1.0

Inicio

Altas

☰

Altas

            <input id="nombre" type="text" placeholder="Nombre..." value="1"/>
            <input id="apellidos" type="text" placeholder="Apellidos..." value="1"/>
            <input id="dni" type="text" placeholder="Dni..." value="1"/>
            <input id="curso" type="text" placeholder="Curso..." value="1"/>
            <input id="telefono" type="tel" placeholder="Teléfono..." value="1"/>
            <input id="direccion" type="text" placeholder="Dirección..." value="1"/>

Seleccione una foto...

            <input id="foto" type="file" accept="image/*" class="ocultar"/>

            <button id="btnEnviar" type="button">Guardar</button>
            <button id="btnCancelar" type="button">Cancelar</button>

Buscar

          <input id="buscar" type="text" placeholder="Nombre..."/>
          <button id="btnBuscar" type="button">Buscar</button>

Editar

            <input id="mnombre" type="text" placeholder="Nombre..."/>
            <input id="mapellidos" type="text" placeholder="Apellidos..."/>
            <input id="mdni" type="text" placeholder="Dni..." readonly="readonly" disabled="disabled" class="ocultar"/>
            <input id="mcurso" type="text" placeholder="Curso..."/>
            <input id="mtelefono" type="tel" placeholder="Teléfono..."/>
            <input id="mdireccion" type="text" placeholder="Dirección..."/>

Seleccione una foto...

            <input id="mfoto" type="file" accept="image/*" class="ocultar"/>

            <button id="mbtnEnviar" type="button">Guardar</button>
            <button id="mbtnCancelar" type="button">Cancelar</button>

          <button id="btnMas" type="button">Mostrar más...</button>
          <button id="btnTodos" type="button">Mostrar todos</button>

Copyright IES Oretania 2º DAW Jesús Tejada Pérez Curso 2016/2017


text:
using System.Linq;
using System;

namespace MeasureMap.Tracers.Metrics.DefaultMetrics
{
    internal class ThreadMetricsCollection : MetricsCollection<ThreadMetric, IThreadMetric>
    {
        public ThreadMetricsCollection()
        {
            Add(ThreadMetric.ThreadId, new ThreadMetricFactory(ThreadMetric.ThreadId, MetricCategory.Warmup, r => r.ThreadId));
            Add(ThreadMetric.Iterations, new ThreadMetricFactory(ThreadMetric.Iterations, MetricCategory.Setup, r => r.Iterations.Count()));
            Add(ThreadMetric.TotalTime, new ThreadMetricFactory(ThreadMetric.TotalTime, MetricCategory.Duration, r => r.TotalTime.ToString(), TextAlign.Right));
            Add(ThreadMetric.Throughput, new ThreadMetricFactory(ThreadMetric.Throughput, MetricCategory.Duration, r => $"{r.Throughput()}/s", TextAlign.Right));
            Add(ThreadMetric.AverageTime, new ThreadMetricFactory(ThreadMetric.AverageTime, MetricCategory.Duration, r => r.AverageTime, TextAlign.Right));
            Add(ThreadMetric.AverageNanoseconds, new ThreadMetricFactory(ThreadMetric.AverageNanoseconds, MetricCategory.Duration, r => $"{r.AverageTicks.ToNanoseconds()} ns", TextAlign.Right));
            Add(ThreadMetric.AverageMicroseconds, new ThreadMetricFactory(ThreadMetric.AverageMicroseconds, MetricCategory.Duration, r => $"{r.AverageTicks.ToMicroseconds()} μs", TextAlign.Right));
            Add(ThreadMetric.AverageMilliseconds, new ThreadMetricFactory(ThreadMetric.AverageMilliseconds, MetricCategory.Duration, r => $"{r.AverageTicks.ToMilliseconds()} ms", TextAlign.Right));
            Add(ThreadMetric.AverageTicks, new ThreadMetricFactory(ThreadMetric.AverageTicks, MetricCategory.Duration, r => r.AverageTicks, TextAlign.Right));
            Add(ThreadMetric.Fastest, new ThreadMetricFactory(ThreadMetric.Fastest, MetricCategory.Duration, r => TimeSpan.FromTicks(r.Fastest.Ticks), TextAlign.Right));
            Add(ThreadMetric.Slowest, new ThreadMetricFactory(ThreadMetric.Slowest, MetricCategory.Duration, r => TimeSpan.FromTicks(r.Slowest.Ticks), TextAlign.Right));
            Add(ThreadMetric.MemoryInitialSize, new ThreadMetricFactory(ThreadMetric.MemoryInitialSize, MetricCategory.Memory, r => r.InitialSize, TextAlign.Right));
            Add(ThreadMetric.MemoryEndSize, new ThreadMetricFactory(ThreadMetric.MemoryEndSize, MetricCategory.Memory, r => r.EndSize, TextAlign.Right));
            Add(ThreadMetric.MemoryIncrease, new ThreadMetricFactory(ThreadMetric.MemoryIncrease, MetricCategory.Memory, r => r.Increase, TextAlign.Right));
        }
    }
}


text:
<?php

namespace PhalconRest\Mvc;

interface RestViewInterface
{

    public function setFormat($mime);

}


text:
<?php

declare(strict_types=1);

namespace App\Resolver;

use Doctrine\ORM\EntityManagerInterface;
use App\Interactors\NotificationInteractor;
use App\Resolver\Interfaces\NotificationResolverInterface;

/**
 * Class NotificationResolver
 *
 * @author Guillaume Loulier <contact@guillaumeloulier.fr>
 */
class NotificationResolver implements NotificationResolverInterface
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManagerInterface;

    /**
     * NotificationResolver constructor.
     *
     * @param EntityManagerInterface $entityManagerInterface
     */
    public function __construct(EntityManagerInterface $entityManagerInterface)
    {
        $this->entityManagerInterface = $entityManagerInterface;
    }

    /**
     * {@inheritdoc}
     */
    public function getNotifications(\ArrayAccess $arguments): array
    {
        switch ($arguments) {
            case $arguments->offsetExists('id') && $arguments->offsetExists('userId'):
                return [
                    $this->entityManagerInterface
                         ->getRepository(NotificationInteractor::class)
                         ->findOneBy([
                             'id' => (int) $arguments->offsetGet('id'),
                             'user' => (int) $arguments->offsetGet('userId')
                         ])
                ];
                break;
            case $arguments->offsetExists('id'):
                return [
                    $this->entityManagerInterface
                         ->getRepository(NotificationInteractor::class)
                         ->findOneBy([
                             'id' => (int) $arguments->offsetGet('id')
                         ])
                ];
                break;
            default:
                return [
                    $this->entityManagerInterface
                         ->getRepository(NotificationInteractor::class)
                         ->findAll()
                ];
                break;
        }
    }
}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="Fullscreen" parent="AppTheme">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:actionMenuTextColor">@android:color/white</item>
    </style>

    <style name="comment">
        <item name="android:windowEnterAnimation">@anim/comment_open</item>
        <item name="android:windowExitAnimation">@anim/comment_close</item>
    </style>

</resources>