text:
<?php

/**
 * @file
 * Contains \Drupal\devel\Controller\DevelController.
 */

namespace Drupal\devel\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;

/**
 * Returns responses for devel module routes.
 */
class DevelController extends ControllerBase {

  /**
   * Clears all caches, then redirects to the previous page.
   */
  public function cacheClear() {
    drupal_flush_all_caches();
    drupal_set_message('Cache cleared.');
    return $this->redirect('<front>');
  }

  public function menuItem() {
    $item = menu_get_item(current_path());
    return kdevel_print_object($item);
  }

  public function themeRegistry() {
    $hooks = theme_get_registry();
    ksort($hooks);
    return array('#markup' => kprint_r($hooks, TRUE));
  }

  /**
   * Builds the elements info overview page.
   *
   * @return array
   *   Array of page elements to render.
   */
  public function elementsPage() {
    $element_info_manager = \Drupal::service('element_info');

    $elements_info = array();
    foreach ($element_info_manager->getDefinitions() as $element_type => $definition) {
      $elements_info[$element_type] = $definition + $element_info_manager->getInfo($element_type);
    }

    ksort($elements_info);

    return array('#markup' => kdevel_print_object($elements_info));
  }

  /**
   * Builds the fields info overview page.
   *
   * @return array
   *   Array of page elements to render.
   */
  public function fieldInfoPage() {
    $fields = FieldStorageConfig::loadMultiple();
    ksort($fields);
    $output['fields'] = array('#markup' => kprint_r($fields, TRUE, $this->t('Fields')));

    $field_instances = FieldConfig::loadMultiple();
    ksort($field_instances);
    $output['instances'] = array('#markup' => kprint_r($field_instances, TRUE, $this->t('Instances')));

    $bundles = $this->entityManager()->getAllBundleInfo();
    ksort($bundles);
    $output['bundles'] = array('#markup' => kprint_r($bundles, TRUE, $this->t('Bundles')));

    $field_types = \Drupal::service('plugin.manager.field.field_type')->getUiDefinitions();
    ksort($field_types);
    $output['field_types'] = array('#markup' => kprint_r($field_types, TRUE, $this->t('Field types')));

    $formatter_types = \Drupal::service('plugin.manager.field.formatter')->getDefinitions();
    ksort($formatter_types);
    $output['formatter_types'] = array('#markup' => kprint_r($formatter_types, TRUE, $this->t('Formatter types')));

    $widget_types = \Drupal::service('plugin.manager.field.widget')->getDefinitions();
    ksort($widget_types);
    $output['widget_types'] = array('#markup' => kprint_r($widget_types, TRUE, $this->t('Widget types')));

    return $output;
  }

  /**
   * Builds the entity types overview page.
   *
   * @return array
   *   Array of page elements to render.
   */
  public function entityInfoPage() {
    $types = $this->entityManager()->getEntityTypeLabels();
    ksort($types);
    $result = array();
    foreach (array_keys($types) as $type) {
      $definition = $this->entityManager()->getDefinition($type);
      $reflected_definition = new \ReflectionClass($definition);
      $props = array();
      foreach ($reflected_definition->getProperties() as $property) {
        $property->setAccessible(TRUE);
        $value = $property->getValue($definition);
        $props[$property->name] = $value;
      }
      $result[$type] = $props;
    }

    return array('#markup' => kprint_r($result, TRUE));
  }

  /**
   * Builds the state variable overview page.
   *
   * @return array
   *   Array of page elements to render.
   */
  public function stateSystemPage() {
    $output['#attached']['library'][] = 'system/drupal.system.modules';

    $output['filters'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('table-filter', 'js-show'),
      ),
    );

    $output['filters']['text'] = array(
      '#type' => 'search',
      '#title' => $this->t('Search'),
      '#size' => 30,
      '#placeholder' => $this->t('Enter state name'),
      '#attributes' => array(
        'class' => array('table-filter-text'),
        'data-table' => '.devel-state-list',
        'autocomplete' => 'off',
        'title' => $this->t('Enter a part of the state name to filter by.'),
      ),
    );

    $can_edit = $this->currentUser()->hasPermission('administer site configuration');

    $header = array(
      'name' => $this->t('Name'),
      'value' => $this->t('Value'),
    );

    if ($can_edit) {
      $header['edit'] = $this->t('Operations');
    }

    $rows = array();
    // State class doesn't have getAll method so we get all states from the
    // KeyValueStorage.
    foreach ($this->keyValue('state')->getAll() as $state_name => $state) {
      $rows[$state_name] = array(
        'name' => array(
          'data' => $state_name,
          'class' => 'table-filter-text-source',
        ),
        'value' => array(
          'data' => kprint_r($state, TRUE),
        ),
      );

      if ($can_edit) {
        $operations['edit'] = array(
          'title' => $this->t('Edit'),
          'url' => Url::fromRoute('devel.system_state_edit', array('state_name' => $state_name)),
        );
        $rows[$state_name]['edit'] = array(
          'data' => array('#type' => 'operations', '#links' => $operations),
        );
      }
    }

    $output['states'] = array(
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => $this->t('No state variables found.'),
      '#attributes' => array(
        'class' => array('devel-state-list'),
      ),
    );

    return $output;
  }

  /**
   * Builds the session overview page.
   *
   * @return array
   *   Array of page elements to render.
   */
  public function session() {
    $output['description'] = array(
      '#markup' => '<p>' . $this->t('Here are the contents of your $_SESSION variable.') . '</p>',
    );
    $output['session'] = array(
      '#type' => 'table',
      '#header' => array($this->t('Session name'), $this->t('Session ID')),
      '#rows' => array(array(session_name(), session_id())),
      '#empty' => $this->t('No session available.'),
    );
    $output['data'] = array(
      '#markup' => kprint_r($_SESSION, TRUE),
    );

    return $output;
  }

  /**
   * Prints the loaded structure of the current entity.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *    A RouteMatch object.
   *
   * @return array
   *    Array of page elements to render.
   */
  public function entityLoad(RouteMatchInterface $route_match) {
    $output = array();

    $parameter_name = $route_match->getRouteObject()->getOption('_devel_entity_type_id');
    $entity = $route_match->getParameter($parameter_name);

    if ($entity && $entity instanceof EntityInterface) {
      $output = array('#markup' => kdevel_print_object($entity));
    }

    return $output;
  }

  /**
   * Prints the render structure of the current entity.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *    A RouteMatch object.
   *
   * @return array
   *    Array of page elements to render.
   */
  public function entityRender(RouteMatchInterface $route_match) {
    $output = array();

    $parameter_name = $route_match->getRouteObject()->getOption('_devel_entity_type_id');
    $entity = $route_match->getParameter($parameter_name);

    if ($entity && $entity instanceof EntityInterface) {
      $entity_type_id = $entity->getEntityTypeId();
      $view_hook = $entity_type_id . '_view';

      $build = array();
      // If module implements own {entity_type}_view
      if (function_exists($view_hook)) {
        $build = $view_hook($entity);
      }
      // If entity has view_builder handler
      elseif ($this->entityManager()->hasHandler($entity_type_id, 'view_builder')) {
        $build = $this->entityManager()->getViewBuilder($entity_type_id)->view($entity);
      }

      $output = array('#markup' => kdevel_print_object($build));
    }

    return $output;
  }

}


text:
'use strict';

let SimpleCacheProvider;

describe('SimpleCacheProvider', () => {
  beforeEach(() => {
    jest.resetModules();
    SimpleCacheProvider = require('simple-cache-provider');
  });

  it('throws a promise if the requested value is not in the cache', async () => {
    const {createCache, createResource} = SimpleCacheProvider;

    function loadUpperCase(text) {
      return Promise.resolve(text.toUpperCase());
    }
    const readUpperCase = createResource(loadUpperCase);
    const cache = createCache();

    let suspender;
    try {
      readUpperCase(cache, 'hello');
    } catch (v) {
      suspender = v;
    }

    await suspender;
    const result = readUpperCase(cache, 'hello');
    expect(result).toBe('HELLO');
  });

  it('throws an error on the subsequent read if the promise is rejected', async () => {
    const {createCache, createResource} = SimpleCacheProvider;

    let shouldFail = true;
    function loadUpperCase(text) {
      if (shouldFail) {
        // Rejects on the first try
        shouldFail = false;
        return Promise.reject(new Error('oh no'));
      } else {
        // Succeeds the second time
        return Promise.resolve(text.toUpperCase());
      }
    }
    const readUpperCase = createResource(loadUpperCase);
    const cache = createCache();

    let suspender;
    try {
      readUpperCase(cache, 'hello');
    } catch (v) {
      suspender = v;
    }

    let error;
    try {
      await suspender;
    } catch (e) {
      error = e;
    }
    expect(() => readUpperCase(cache, 'hello')).toThrow(error);
    expect(error.message).toBe('oh no');

    // On a subsequent read, it should complete successfully.
    try {
      readUpperCase(cache, 'hello');
    } catch (v) {
      suspender = v;
    }
    await suspender;
    const result = readUpperCase(cache, 'hello');
    expect(result).toBe('HELLO');
  });

  it('can preload data ahead of time', async () => {
    const {createCache, createResource} = SimpleCacheProvider;

    function loadUpperCase(text) {
      return Promise.resolve(text.toUpperCase());
    }
    const readUpperCase = createResource(loadUpperCase);
    const cache = createCache();

    readUpperCase.preload(cache, 'hello');
    // Wait for next tick
    await Promise.resolve();
    const result = readUpperCase(cache, 'hello');
    expect(result).toBe('HELLO');
  });

  it('does not throw if preloaded promise rejects', async () => {
    const {createCache, createResource} = SimpleCacheProvider;

    function loadUpperCase(text) {
      return Promise.reject(new Error('uh oh'));
    }
    const readUpperCase = createResource(loadUpperCase);
    const cache = createCache();

    readUpperCase.preload(cache, 'hello');
    // Wait for next tick
    await Promise.resolve();

    expect(() => readUpperCase(cache, 'hello')).toThrow('uh oh');
  });

  it('accepts custom hash function', async () => {
    const {createCache, createResource} = SimpleCacheProvider;

    function loadSum([a, b]) {
      return Promise.resolve(a + b);
    }
    function hash([a, b]) {
      return `${a + b}`;
    }
    const readSum = createResource(loadSum, hash);
    const cache = createCache();

    readSum.preload(cache, [5, 5]);
    readSum.preload(cache, [1, 2]);
    await Promise.resolve();

    expect(readSum(cache, [5, 5])).toEqual(10);
    expect(readSum(cache, [1, 2])).toEqual(3);
    // The fact that the next line returns synchronously and doesn't throw, even
    // though [3, 7] was not preloaded, proves that the hashing function works.
    expect(readSum(cache, [3, 7])).toEqual(10);
  });

  it('warns if resourceType is a string or number', () => {
    const {createCache} = SimpleCacheProvider;

    spyOnDev(console, 'error');
    const cache = createCache();

    function fn() {
      cache.preload('foo', 'uppercaseA', () => Promise.resolve('A'));
      cache.preload(123, 'productOf9And2', () => Promise.resolve(18));
    }

    if (__DEV__) {
      expect(fn).toWarnDev([
        'Invalid resourceType: Expected a symbol, object, or function, but ' +
          'instead received: foo. Strings and numbers are not permitted as ' +
          'resource types.',
        'Invalid resourceType: Expected a symbol, object, or function, but ' +
          'instead received: 123. Strings and numbers are not permitted as ' +
          'resource types.',
      ]);
    } else {
      fn();
    }
  });

  it('warns if non-primitive key is passed to a resource without a hash function', () => {
    const {createCache, createResource} = SimpleCacheProvider;

    spyOnDev(console, 'error');

    function loadSum([a, b]) {
      return Promise.resolve(a + b);
    }

    const readSum = createResource(loadSum);
    const cache = createCache();

    function fn() {
      readSum.preload(cache, [5, 5]);
    }

    if (__DEV__) {
      expect(fn).toWarnDev([
        'preload: Invalid key type. Expected a string, number, symbol, or ' +
          'boolean, but instead received: 5,5\n\n' +
          'To use non-primitive values as keys, you must pass a hash ' +
          'function as the second argument to createResource().',
      ]);
    } else {
      fn();
    }
  });
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace PHPExiftool\Driver\Tag\MXF;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class VC1SingleSequence extends AbstractTag
{

    protected $Id = '060e2b34.0101.010c.04010604.02000000';

    protected $Name = 'VC-1SingleSequence';

    protected $FullName = 'MXF::Main';

    protected $GroupName = 'MXF';

    protected $g0 = 'MXF';

    protected $g1 = 'MXF';

    protected $g2 = 'Video';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'VC-1 Single Sequence';

}


text:
/** This class defines a simple dialog that presents a message
  * to the user.  You can set the window title, icon, and label to customize
  * the presentation of the window.
  */
qx.Class.define("admin.dialog.MessageDialog", {
	extend : admin.dialog.OKDialog,

	/** You may pass in window title, icon, and label values.
	  */
	construct : function ( title, icon, label) {
		this.icon = icon;
		this.label = label;

		// Call the parent constructor:
		this.base( arguments, title );

	},

	members : {

		/** This method is used to allow child classes to override the size
		  * of this dialog box.
		  */
		doSetSpace : function () {
			this.setWidth(450);
			this.setHeight(150);
		},

		/** This method is used to allow child classes to add objects to our
		  * main layout.
		  */
		doFormLayout : function ( layout ) {
			this.displayAtom = new qx.ui.basic.Atom(this.label, this.icon );
			this.displayAtom.setRich( true );
			this.displayAtom.setSelectable(true);
			layout.add(this.displayAtom);
		}

	},

	destruct : function() {
		//this._disposeObjects(  );

	}

});


text:
int main()
{
	while(1){	std::cout << "Bad things are currently happening."; };
	return 0;
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../libc/type.__u16.html">

Redirecting to ../../../../libc/type.__u16.html...


text:
title: "helper function to sync sparkinstall project to sparklyr"
aliases:
  - reference/sparklyr/latest/spark_install_sync.html
---

Arguments

See: https://github.com/rstudio/spark-install

spark_install_sync(project_path)

Arguments

    <colgroup>
      <col class="name" />
      <col class="desc" />
    </colgroup>

      project_path

The path to the sparkinstall project


text:
from __future__ import unicode_literals

import functools
import io
import os
import os.path
import subprocess
import sys

import mock
import pytest

from pre_commit.commands.install_uninstall import install
from pre_commit.commands.run import _get_skips
from pre_commit.commands.run import _has_unmerged_paths
from pre_commit.commands.run import get_changed_files
from pre_commit.commands.run import run
from pre_commit.ordereddict import OrderedDict
from pre_commit.output import sys_stdout_write_wrapper
from pre_commit.runner import Runner
from pre_commit.util import cmd_output
from pre_commit.util import cwd
from testing.auto_namedtuple import auto_namedtuple
from testing.fixtures import add_config_to_repo
from testing.fixtures import make_consuming_repo

@pytest.yield_fixture
def repo_with_passing_hook(tmpdir_factory):
    git_path = make_consuming_repo(tmpdir_factory, 'script_hooks_repo')
    with cwd(git_path):
        yield git_path

@pytest.yield_fixture
def repo_with_failing_hook(tmpdir_factory):
    git_path = make_consuming_repo(tmpdir_factory, 'failing_hook_repo')
    with cwd(git_path):
        yield git_path

def stage_a_file():
    cmd_output('touch', 'foo.py')
    cmd_output('git', 'add', 'foo.py')

def get_write_mock_output(write_mock):
    return b''.join(call[0][0] for call in write_mock.write.call_args_list)

def _get_opts(
        all_files=False,
        files=(),
        color=False,
        verbose=False,
        hook=None,
        no_stash=False,
        origin='',
        source='',
        allow_unstaged_config=False,
):
    # These are mutually exclusive
    assert not (all_files and files)
    return auto_namedtuple(
        all_files=all_files,
        files=files,
        color=color,
        verbose=verbose,
        hook=hook,
        no_stash=no_stash,
        origin=origin,
        source=source,
        allow_unstaged_config=allow_unstaged_config,
    )

def _do_run(repo, args, environ={}):
    runner = Runner(repo)
    write_mock = mock.Mock()
    write_fn = functools.partial(sys_stdout_write_wrapper, stream=write_mock)
    ret = run(runner, args, write=write_fn, environ=environ)
    printed = get_write_mock_output(write_mock)
    return ret, printed

def _test_run(repo, options, expected_outputs, expected_ret, stage):
    if stage:
        stage_a_file()
    args = _get_opts(**options)
    ret, printed = _do_run(repo, args)
    assert ret == expected_ret, (ret, expected_ret, printed)
    for expected_output_part in expected_outputs:
        assert expected_output_part in printed

def test_run_all_hooks_failing(
        repo_with_failing_hook, mock_out_store_directory
):
    _test_run(
        repo_with_failing_hook,
        {},
        (
            b'Failing hook',
            b'Failed',
            b'hookid: failing_hook',
            b'Fail\nfoo.py\n',
        ),
        1,
        True,
    )

def test_arbitrary_bytes_hook(tmpdir_factory, mock_out_store_directory):
    git_path = make_consuming_repo(tmpdir_factory, 'arbitrary_bytes_repo')
    with cwd(git_path):
        _test_run(git_path, {}, (b'\xe2\x98\x83\xb2\n',), 1, True)

@pytest.mark.parametrize(
    ('options', 'outputs', 'expected_ret', 'stage'),
    (
        ({}, (b'Bash hook', b'Passed'), 0, True),
        ({'verbose': True}, (b'foo.py\nHello World',), 0, True),
        ({'hook': 'bash_hook'}, (b'Bash hook', b'Passed'), 0, True),
        ({'hook': 'nope'}, (b'No hook with id `nope`',), 1, True),
        (
            {'all_files': True, 'verbose': True},
            (b'foo.py',),
            0,
            True,
        ),
        (
            {'files': ('foo.py',), 'verbose': True},
            (b'foo.py',),
            0,
            True,
        ),
        ({}, (b'Bash hook', b'(no files to check)', b'Skipped'), 0, False),
    )
)
def test_run(
        repo_with_passing_hook,
        options,
        outputs,
        expected_ret,
        stage,
        mock_out_store_directory,
):
    _test_run(repo_with_passing_hook, options, outputs, expected_ret, stage)

@pytest.mark.parametrize(
    ('origin', 'source', 'expect_failure'),
    (
        ('master', 'master', False),
        ('master', '', True),
        ('', 'master', True),
    )
)
def test_origin_source_error_msg(
        repo_with_passing_hook, origin, source, expect_failure,
        mock_out_store_directory,
):
    args = _get_opts(origin=origin, source=source)
    ret, printed = _do_run(repo_with_passing_hook, args)
    warning_msg = b'Specify both --origin and --source.'
    if expect_failure:
        assert ret == 1
        assert warning_msg in printed
    else:
        assert ret == 0
        assert warning_msg not in printed

@pytest.mark.parametrize(
    ('no_stash', 'all_files', 'expect_stash'),
    (
        (True, True, False),
        (True, False, False),
        (False, True, False),
        (False, False, True),
    ),
)
def test_no_stash(
        repo_with_passing_hook,
        no_stash,
        all_files,
        expect_stash,
        mock_out_store_directory,
):
    stage_a_file()
    # Make unstaged changes
    with open('foo.py', 'w') as foo_file:
        foo_file.write('import os\n')

    args = _get_opts(no_stash=no_stash, all_files=all_files)
    ret, printed = _do_run(repo_with_passing_hook, args)
    assert ret == 0
    warning_msg = b'[WARNING] Unstaged files detected.'
    if expect_stash:
        assert warning_msg in printed
    else:
        assert warning_msg not in printed

@pytest.mark.parametrize(('output', 'expected'), (('some', True), ('', False)))
def test_has_unmerged_paths(output, expected):
    mock_runner = mock.Mock()
    mock_runner.cmd_runner.run.return_value = (1, output, '')
    assert _has_unmerged_paths(mock_runner) is expected

def test_merge_conflict(in_merge_conflict, mock_out_store_directory):
    ret, printed = _do_run(in_merge_conflict, _get_opts())
    assert ret == 1
    assert b'Unmerged files.  Resolve before committing.' in printed

def test_merge_conflict_modified(in_merge_conflict, mock_out_store_directory):
    # Touch another file so we have unstaged non-conflicting things
    assert os.path.exists('dummy')
    with open('dummy', 'w') as dummy_file:
        dummy_file.write('bar\nbaz\n')

    ret, printed = _do_run(in_merge_conflict, _get_opts())
    assert ret == 1
    assert b'Unmerged files.  Resolve before committing.' in printed

def test_merge_conflict_resolved(in_merge_conflict, mock_out_store_directory):
    cmd_output('git', 'add', '.')
    ret, printed = _do_run(in_merge_conflict, _get_opts())
    for msg in (
            b'Checking merge-conflict files only.', b'Bash hook', b'Passed',
    ):
        assert msg in printed

@pytest.mark.parametrize(
    ('environ', 'expected_output'),
    (
        ({}, set([])),
        ({'SKIP': ''}, set([])),
        ({'SKIP': ','}, set([])),
        ({'SKIP': ',foo'}, set(['foo'])),
        ({'SKIP': 'foo'}, set(['foo'])),
        ({'SKIP': 'foo,bar'}, set(['foo', 'bar'])),
        ({'SKIP': ' foo , bar'}, set(['foo', 'bar'])),
    ),
)
def test_get_skips(environ, expected_output):
    ret = _get_skips(environ)
    assert ret == expected_output

def test_skip_hook(repo_with_passing_hook, mock_out_store_directory):
    ret, printed = _do_run(
        repo_with_passing_hook, _get_opts(), {'SKIP': 'bash_hook'},
    )
    for msg in (b'Bash hook', b'Skipped'):
        assert msg in printed

def test_hook_id_not_in_non_verbose_output(
        repo_with_passing_hook, mock_out_store_directory
):
    ret, printed = _do_run(repo_with_passing_hook, _get_opts(verbose=False))
    assert b'[bash_hook]' not in printed

def test_hook_id_in_verbose_output(
        repo_with_passing_hook, mock_out_store_directory,
):
    ret, printed = _do_run(repo_with_passing_hook, _get_opts(verbose=True))
    assert b'[bash_hook] Bash hook' in printed

def test_multiple_hooks_same_id(
        repo_with_passing_hook, mock_out_store_directory,
):
    with cwd(repo_with_passing_hook):
        # Add bash hook on there again
        with io.open('.pre-commit-config.yaml', 'a+') as config_file:
            config_file.write('    - id: bash_hook\n')
        cmd_output('git', 'add', '.pre-commit-config.yaml')
        stage_a_file()

    ret, output = _do_run(repo_with_passing_hook, _get_opts())
    assert ret == 0
    assert output.count(b'Bash hook') == 2

def test_non_ascii_hook_id(
        repo_with_passing_hook, mock_out_store_directory, tmpdir_factory,
):
    with cwd(repo_with_passing_hook):
        install(Runner(repo_with_passing_hook))
        # Don't want to write to home directory
        env = dict(os.environ, PRE_COMMIT_HOME=tmpdir_factory.get())
        _, stdout, _ = cmd_output(
            sys.executable, '-m', 'pre_commit.main', 'run', '☃',
            env=env, retcode=None,
        )
        assert 'UnicodeDecodeError' not in stdout
        # Doesn't actually happen, but a reasonable assertion
        assert 'UnicodeEncodeError' not in stdout

def test_stdout_write_bug_py26(
        repo_with_failing_hook, mock_out_store_directory, tmpdir_factory,
):
    with cwd(repo_with_failing_hook):
        # Add bash hook on there again
        with io.open(
            '.pre-commit-config.yaml', 'a+', encoding='UTF-8',
        ) as config_file:
            config_file.write('        args: ["☃"]\n')
        cmd_output('git', 'add', '.pre-commit-config.yaml')
        stage_a_file()

        install(Runner(repo_with_failing_hook))

        # Don't want to write to home directory
        env = dict(os.environ, PRE_COMMIT_HOME=tmpdir_factory.get())
        # Have to use subprocess because pytest monkeypatches sys.stdout
        _, stdout, _ = cmd_output(
            'git', 'commit', '-m', 'Commit!',
            # git commit puts pre-commit to stderr
            stderr=subprocess.STDOUT,
            env=env,
            retcode=None,
        )
        assert 'UnicodeEncodeError' not in stdout
        # Doesn't actually happen, but a reasonable assertion
        assert 'UnicodeDecodeError' not in stdout

def test_get_changed_files():
    files = get_changed_files(
        '78c682a1d13ba20e7cb735313b9314a74365cd3a',
        '3387edbb1288a580b37fe25225aa0b856b18ad1a',
    )
    assert files == ['CHANGELOG.md', 'setup.py']

def test_lots_of_files(mock_out_store_directory, tmpdir_factory):
    # windows xargs seems to have a bug, here's a regression test for
    # our workaround
    git_path = make_consuming_repo(tmpdir_factory, 'python_hooks_repo')
    with cwd(git_path):
        # Override files so we run against them
        with io.open('.pre-commit-config.yaml', 'a+') as config_file:
            config_file.write('        files: ""\n')

        # Write a crap ton of files
        for i in range(400):
            filename = '{0}{1}'.format('a' * 100, i)
            open(filename, 'w').close()

        cmd_output('bash', '-c', 'git add .')
        install(Runner(git_path))

        # Don't want to write to home directory
        env = dict(os.environ, PRE_COMMIT_HOME=tmpdir_factory.get())
        cmd_output(
            'git', 'commit', '-m', 'Commit!',
            # git commit puts pre-commit to stderr
            stderr=subprocess.STDOUT,
            env=env,
        )

def test_local_hook_passes(
        repo_with_passing_hook, mock_out_store_directory,
):
    config = OrderedDict((
        ('repo', 'local'),
        ('hooks', (OrderedDict((
            ('id', 'pylint'),
            ('name', 'PyLint'),
            ('entry', 'python -m pylint.__main__'),
            ('language', 'system'),
            ('files', r'\.py$'),
        )), OrderedDict((
            ('id', 'do_not_commit'),
            ('name', 'Block if "DO NOT COMMIT" is found'),
            ('entry', 'DO NOT COMMIT'),
            ('language', 'pcre'),
            ('files', '^(.*)$'),
        ))))
    ))
    add_config_to_repo(repo_with_passing_hook, config)

    with io.open('dummy.py', 'w') as staged_file:
        staged_file.write('"""TODO: something"""\n')
    cmd_output('git', 'add', 'dummy.py')

    _test_run(
        repo_with_passing_hook,
        options={},
        expected_outputs=[b''],
        expected_ret=0,
        stage=False
    )

def test_local_hook_fails(
        repo_with_passing_hook, mock_out_store_directory,
):
    config = OrderedDict((
        ('repo', 'local'),
        ('hooks', [OrderedDict((
            ('id', 'no-todo'),
            ('name', 'No TODO'),
            ('entry', 'grep -iI todo'),
            ('expected_return_value', 1),
            ('language', 'system'),
            ('files', ''),
        ))])
    ))
    add_config_to_repo(repo_with_passing_hook, config)

    with io.open('dummy.py', 'w') as staged_file:
        staged_file.write('"""TODO: something"""\n')
    cmd_output('git', 'add', 'dummy.py')

    _test_run(
        repo_with_passing_hook,
        options={},
        expected_outputs=[b''],
        expected_ret=1,
        stage=False
    )

def test_allow_unstaged_config_option(
        repo_with_passing_hook, mock_out_store_directory,
):
    with cwd(repo_with_passing_hook):
        with io.open('.pre-commit-config.yaml', 'a+') as config_file:
            # writing a newline should be relatively harmless to get a change
            config_file.write('\n')

    args = _get_opts(allow_unstaged_config=True)
    ret, printed = _do_run(repo_with_passing_hook, args)
    assert b'You have an unstaged config file' in printed
    assert b'have specified the --allow-unstaged-config option.' in printed
    assert ret == 0

def modify_config(path):
    with cwd(path):
        with io.open('.pre-commit-config.yaml', 'a+') as config_file:
            # writing a newline should be relatively harmless to get a change
            config_file.write('\n')

def test_no_allow_unstaged_config_option(
    repo_with_passing_hook, mock_out_store_directory,
):
    modify_config(repo_with_passing_hook)
    args = _get_opts(allow_unstaged_config=False)
    ret, printed = _do_run(repo_with_passing_hook, args)
    assert b'Your .pre-commit-config.yaml is unstaged.' in printed
    assert ret == 1

def test_no_stash_suppresses_allow_unstaged_config_option(
        repo_with_passing_hook, mock_out_store_directory,
):
    modify_config(repo_with_passing_hook)
    args = _get_opts(allow_unstaged_config=False, no_stash=True)
    ret, printed = _do_run(repo_with_passing_hook, args)
    assert b'Your .pre-commit-config.yaml is unstaged.' not in printed

def test_all_files_suppresses_allow_unstaged_config_option(
        repo_with_passing_hook, mock_out_store_directory,
):
    modify_config(repo_with_passing_hook)
    args = _get_opts(all_files=True)
    ret, printed = _do_run(repo_with_passing_hook, args)
    assert b'Your .pre-commit-config.yaml is unstaged.' not in printed

def test_files_suppresses_allow_unstaged_config_option(
        repo_with_passing_hook, mock_out_store_directory,
):
    modify_config(repo_with_passing_hook)
    args = _get_opts(files=['.pre-commit-config.yaml'])
    ret, printed = _do_run(repo_with_passing_hook, args)
    assert b'Your .pre-commit-config.yaml is unstaged.' not in printed


text:
/**
 * Onshape REST API
 * The Onshape REST API consumed by all clients.
 *
 * OpenAPI spec version: 1.93
 * Contact: api-support@onshape.zendesk.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

import { BTOccurrence } from './bTOccurrence';

export class BTAssemblyTransformDefinitionParams {
    'transform'?: Array<number>;
    'occurrences'?: Array<BTOccurrence>;
    'isRelative'?: boolean;

    static discriminator: string | undefined = undefined;

    static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [
        {
            "name": "transform",
            "baseName": "transform",
            "type": "Array<number>"
        },
        {
            "name": "occurrences",
            "baseName": "occurrences",
            "type": "Array<BTOccurrence>"
        },
        {
            "name": "isRelative",
            "baseName": "isRelative",
            "type": "boolean"
        }    ];

    static getAttributeTypeMap() {
        return BTAssemblyTransformDefinitionParams.attributeTypeMap;
    }
}


text:
package play.filters.csrf;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import play.mvc.With;

/** This action requires a CSRF check. */
@With(RequireCSRFCheckAction.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface RequireCSRFCheck {

  /**
   * Calls a implementation class for handling the CSRF error.
   *
   * @see play.filters.csrf.CSRFErrorHandler
   * @return the subtype of CSRFErrorHandler
   */
  Class<? extends CSRFErrorHandler> error() default CSRFErrorHandler.DefaultCSRFErrorHandler.class;
}


text:
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'gewt' project.
// Copyright 2018 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// 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 de.esoco.ewt.style;

import de.esoco.ewt.component.TabPanel;

/********************************************************************
 * An enumeration of integer style flags that can be set on a style data
 * instance to control the appearance and/or behavior of a component.
 *
 * @author eso
 */
public enum StyleFlag
{
	/** Default attribute, e.g. for default buttons */
	DEFAULT,

	/** Signals that a component is not resizable */
	FIXED_SIZE,

	/** Signals that a component is read only/not editable */
	READ_ONLY,

	/** Text or sub-elements may wrap or not wrap */
	WRAP, NO_WRAP,

	/** Enables multi-selection for components that support item selection */
	MULTISELECT,

	/** Allow dragging inside the component (e.g. in ScrollPanels) */
	DRAGGING,

	//- Render styles ---------------------------

	/** Enables flat appearance (e.g. ToolBars) */
	FLAT,

	/** Disables the default border around a component (if supported) */
	NO_BORDER,

	/** Enables a default border around a component (if supported) */
	BORDER,

	//- Border styles ---------------------------

	/** Border style: raised bevel (as used for buttons) */
	BEVEL_RAISED,

	/** Border style: lowered bevel (as used for pressed buttons) */
	BEVEL_LOWERED,

	/** Border style: etched-out line */
	ETCHED_OUT,

	/** Border style: etched-in line */
	ETCHED_IN,

	//- ScrollBar styles ------------------------

	/** Horizontal scrollbar always on */
	SCROLLBAR_HORIZONTAL_ON,

	/** Horizontal scrollbar always off */
	SCROLLBAR_HORIZONTAL_OFF,

	/** Vertical scrollbar always on */
	SCROLLBAR_VERTICAL_ON,

	/** Vertical scrollbars always off */
	SCROLLBAR_VERTICAL_OFF,

	//- Rendering alignments ----------
	/** Horizontally left-aligned */
	HORIZONTAL_ALIGN_LEFT,

	/** Horizontally centered */
	HORIZONTAL_ALIGN_CENTER,

	/** Horizontally right-aligned */
	HORIZONTAL_ALIGN_RIGHT,

	/** Vertically top-aligned */
	VERTICAL_ALIGN_TOP,

	/** Vertically centered */
	VERTICAL_ALIGN_CENTER,

	/** Vertically bottom-aligned */
	VERTICAL_ALIGN_BOTTOM,

	//- Component-specific styles ---------------

	/** Renders a label as a hyperlink */
	HYPERLINK,

	/** A text should be treated as a resource string */
	RESOURCE,

	/**
	 * Bottom placement of the tabs in a {@link TabPanel} (currently not
	 * supported on GEWT)
	 */
	TAB_BOTTOM,

	/**
	 * When set on a date component defines that also time adjustment controls
	 * should be available.
	 */
	DATE_TIME;
}


text:
    Name:

        <input type="text" id="name" ng-model="yourName" placeholder="Enter a name here" class="form-control">

    Hello {{yourName}}!


text:
function w = ccn_compute_weights_np ( n, np, p )

%*****************************************************************************80
%
%% CCN_COMPUTE_WEIGHTS_NP: weights for nested Clenshaw Curtis rule.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    07 March 2011
%
%  Author:
%
%    John Burkardt
%
%  Parameters:
%
%    Input, integer N, the order of the rule.
%
%    Input, integer ( kind = 4 ) NP, the number of parameters.
%
%    Input, real ( kind = 8 ) P(NP), the parameters.
%
%    Output, real W(N), the weights.
%
  w = ccn_compute_weights ( n );

  return
end


text:
require "spec_helper"

describe WordSearch::Solver do
  let(:plane_file) do
    tempfile = Tempfile.new
    tempfile.write "hi\nxx"
    tempfile.rewind
    tempfile
  end

  it "benchmarks a solution" do
    WordSearch::Solver.any_instance.stubs(
      :users_solution
    ).returns({ "hi" => { 0 => [0, 1], 1 => [1, 1] } })

    solver = WordSearch::Solver.new(
      Tempfile.new, "spec/support/solver_words.csv", plane_file
    )
    expect(solver.perform).to be_a Benchmark::Tms
  end

  it "returns an invalid message if answer is incorrect" do
    WordSearch::Solver.any_instance.stubs(:users_solution).returns({})
    WordSearch::Solver.any_instance.stubs(:solved?).returns(false)

    solver = WordSearch::Solver.new(
      Tempfile.new, "spec/support/solver_words.csv", plane_file
    )
    expect(solver.perform).to be "Word Search incorrectly solved"
  end
end


text:
import Component from '@ember/component';
import { computed } from '@ember/object';

export default Component.extend({
  classNames: ['popover-confirm'],
  iconClass: computed('filename', function () {
    const { filename } = this;

    if (filename) {
      const regex = /\.([0-9a-z]+)$/i;
      const match = filename.match(regex);
      const extension = match && match[1];

      if (extension) {
        return `glyphicon-${extension.toLowerCase()}`;
      }
    }

    return undefined;
  }),

  actions: {
    confirm() {
      this.onConfirm();
    },

    cancel() {
      this.onCancel();
    },
  },
});


text:
using System;
using log4net;

namespace Adapt.Analyzer.Core.General
{
    public interface ILogger
    {
        void InfoFormat(string message, params object[] args);
        void ExceptionFormat(string message, Exception exception, params object[] args);
    }

    public class Logger : ILogger
    {
        private readonly ILog _log;

        public Logger()
            : this(LogManager.GetLogger("Adapt.Analyzer"))
        {

        }

        public Logger(ILog log)
        {
            _log = log;
        }

        public void InfoFormat(string message, params object[] args)
        {
            _log.InfoFormat(message, args);
        }

        public void ExceptionFormat(string message, Exception exception, params object[] args)
        {
            _log.ErrorFormat(message, args);
            _log.Error(exception);
        }
    }
}


text:
from django.contrib.auth.models import Permission
from django.test import TestCase
from django.contrib.contenttypes.models import ContentType

from oscar.core.loading import get_model
from oscar.test.factories import PartnerFactory, PermissionFactory, UserFactory
from oscar.apps.dashboard.partners import views

class TestPartnerUserUnlinkView(TestCase):
    def test_remove_dashboard_permission(self):
        user = UserFactory(is_staff=False)
        permission = PermissionFactory(
            codename='dashboard_access',
            content_type=ContentType.objects.get(
                app_label='partner', model='partner'))
        user.user_permissions.add(permission)
        partner = PartnerFactory()
        partner.users.add(user)

        view = views.PartnerUserUnlinkView()
        view.unlink_user(user, partner)

        assert partner.users.count() == 0
        assert Permission.objects.filter(pk=permission.pk).exists()


text:
macro :xml do
	dispatch do |node|
		name = node[:name]
		valid_xml_element name
		max_parameters 1
		if Glyph["options.xml_blacklist"] && name.to_s.in?(Glyph['options.xml_blacklist']) then
			""
		else
			attributes # evaluate attributes
			xml_attributes = node.children.select{|n| n.is_a?(Glyph::AttributeNode)}.map do |e|
				if valid_xml_attribute(e[:name]) then
					attr_v = e[:value].blank? ? e.evaluate(node, :attrs => true) : e[:value]
					%|#{e[:name]}="#{attr_v}"|
				else
					nil
				end
			end.compact.join(" ")
			xml_attributes = " "+xml_attributes unless xml_attributes.blank?
			end_first_tag = node.param(0) ? ">" : ""
			end_tag = node.param(0) ? "</#{name}>" : " />"
			if node.param(0) then
				param_0 = node.param(0)[:value].blank? ? node.param(0).evaluate(node, :params => true) : node.param(0)[:value]
				if (node.param(0)&0) && (node.param(0)&0)[:name] then
					contents = "\n#{param_0}\n"
				else
					contents = param_0
				end
			else
				# no parameters
				contents = ""
			end
			%{<#{name}#{xml_attributes}#{end_first_tag}#{contents}#{end_tag}}
		end
	end
end


text:
A few tests are available for the taiko ranking and other taiko stuff. The tests are the following python files:
* tr_test_convert.py
* tr_test_stars
* tr_test_mapset

There is also linear_fun.py which is a small tool to check how looks the piecewise linear functions used in the taiko ranking.

### Test convert
For checking if the autoconvert algorithm is correct. Use the following command line to run the test:

`./tr_test_convert.py yaml/convert/test_convert.yaml`

They are basicely unit test only on sliders. Even if it looks quite good at the moment, osux convertion algorithm differs from the real one on some maps.

### Test stars
For checking star rating based on a given output order. If the beatmaps are not in the same order the number of errors is computed using Levenshtein's distance. First you will have to generate the beatmaps with:

`./generate_beatmaps.py`

Then you can run all the test like this:

`./tr_test_convert.py yaml/test_generated_main.yaml`

### Test mapset
For checking star rating in a mapset without a given output order. The program guess the expecting output based on the difficulty names: Inner Oni > Oni > Muzukashi...

`./tr_test_mapset.py "path/to/dir/"`

The program is recursive and will search for directories inside the argument. It is useful as it creates a lot of tests but I think they are easy tests. Well, it's still better than nothing.


text:
package com.gmail.blueboxware.libgdxplugin.filetypes.skin;

import com.intellij.psi.tree.IElementType;
import com.intellij.psi.PsiElement;
import com.intellij.lang.ASTNode;
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.impl.*;

public interface SkinElementTypes {

  IElementType ARRAY = new SkinElementType("ARRAY");
  IElementType CLASS_NAME = new SkinElementType("CLASS_NAME");
  IElementType CLASS_SPECIFICATION = new SkinElementType("CLASS_SPECIFICATION");
  IElementType OBJECT = new SkinElementType("OBJECT");
  IElementType PROPERTY = new SkinElementType("PROPERTY");
  IElementType PROPERTY_NAME = new SkinElementType("PROPERTY_NAME");
  IElementType PROPERTY_VALUE = new SkinElementType("PROPERTY_VALUE");
  IElementType RESOURCE = new SkinElementType("RESOURCE");
  IElementType RESOURCES = new SkinElementType("RESOURCES");
  IElementType RESOURCE_NAME = new SkinElementType("RESOURCE_NAME");
  IElementType STRING_LITERAL = new SkinElementType("STRING_LITERAL");
  IElementType VALUE = new SkinElementType("VALUE");

  IElementType BLOCK_COMMENT = new SkinTokenType("BLOCK_COMMENT");
  IElementType COLON = new SkinTokenType(":");
  IElementType COMMA = new SkinTokenType(",");
  IElementType DOUBLE_QUOTED_STRING = new SkinTokenType("DOUBLE_QUOTED_STRING");
  IElementType LINE_COMMENT = new SkinTokenType("LINE_COMMENT");
  IElementType L_BRACKET = new SkinTokenType("[");
  IElementType L_CURLY = new SkinTokenType("{");
  IElementType R_BRACKET = new SkinTokenType("]");
  IElementType R_CURLY = new SkinTokenType("}");
  IElementType UNQUOTED_STRING = new SkinTokenType("UNQUOTED_STRING");

  class Factory {
    public static PsiElement createElement(ASTNode node) {
      IElementType type = node.getElementType();
      if (type == ARRAY) {
        return new SkinArrayImpl(node);
      }
      else if (type == CLASS_NAME) {
        return new SkinClassNameImpl(node);
      }
      else if (type == CLASS_SPECIFICATION) {
        return new SkinClassSpecificationImpl(node);
      }
      else if (type == OBJECT) {
        return new SkinObjectImpl(node);
      }
      else if (type == PROPERTY) {
        return new SkinPropertyImpl(node);
      }
      else if (type == PROPERTY_NAME) {
        return new SkinPropertyNameImpl(node);
      }
      else if (type == PROPERTY_VALUE) {
        return new SkinPropertyValueImpl(node);
      }
      else if (type == RESOURCE) {
        return new SkinResourceImpl(node);
      }
      else if (type == RESOURCES) {
        return new SkinResourcesImpl(node);
      }
      else if (type == RESOURCE_NAME) {
        return new SkinResourceNameImpl(node);
      }
      else if (type == STRING_LITERAL) {
        return new SkinStringLiteralImpl(node);
      }
      throw new AssertionError("Unknown element type: " + type);
    }
  }
}


text:
<?xml version="1.0"?>
<InterchangeStudentAssessment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ed-fi.org/0100"
                                  xsi:schemaLocation="http://ed-fi.org/0100 ../../sli/edfi-schema/src/main/resources/edfiXsd-SLI/SLI-Interchange-AssessmentMetadata.xsd">
    <Action ActionType="DELETE" Cascade="false" Force="false">

<StudentAssessment>
  <AdministrationDate>2002-09-11</AdministrationDate>
    <AdministrationEndDate>2000-08-24</AdministrationEndDate>

    <SerialNumber>2 code</SerialNumber>
  <AdministrationLanguage>English</AdministrationLanguage>
  <AdministrationEnvironment>Classroom</AdministrationEnvironment>
    <SpecialAccommodations>
      <SpecialAccommodation>Dyslexia Bundled</SpecialAccommodation>
    </SpecialAccommodations>

    <LinguisticAccommodations>
      <LinguisticAccommodation>Linguistic Accommodations allowed but not used</LinguisticAccommodation>
    </LinguisticAccommodations>
  <RetestIndicator>Primary Administration</RetestIndicator>
    <ReasonNotTested>Foreign exchange student waiver</ReasonNotTested>
  <ScoreResults AssessmentReportingMethod="Scale score">
    <Result>46</Result>
  </ScoreResults>
    <GradeLevelWhenAssessed>Eleventh grade</GradeLevelWhenAssessed>
    <PerformanceLevels>
      <CodeValue>2 code</CodeValue>
      <PerformanceLevelMet>false</PerformanceLevelMet>
    </PerformanceLevels>
  <StudentReference>
    <StudentIdentity>
      <StudentUniqueStateId>2</StudentUniqueStateId>
    </StudentIdentity>
  </StudentReference>
  <AssessmentReference>
      <AssessmentIdentity>
          <AssessmentTitle>2002-Seventh grade Assessment 1</AssessmentTitle>
          <GradeLevelAssessed>Seventh grade</GradeLevelAssessed>
      </AssessmentIdentity>
  </AssessmentReference>
</StudentAssessment>

    </Action>
</InterchangeStudentAssessment>


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
from nlpfromscratch.vocab import  MultiVocab
from nlpfromscratch.evaluation import metrics, set_scores
import os

curr_path = os.path.dirname(os.path.realpath(__file__))
data_dir = os.path.join(curr_path, 'sample')

class TestEvaluation(tf.test.TestCase):

  def test_init_and_set_scores(self):

    tp_map = { 'A':3, 'B':2, 'C':4, 'O':10}
    fp_map = { 'A':1, 'B':6, 'C':0, 'O':2}
    fn_map = { 'A':4, 'B':1, 'C':0, 'O':4}

    labels = tp_map.keys()

    metrics(labels)

    expected_num_vars = ( len(labels) + 1 ) * 3
    with self.test_session() as sess:
      sess.run(tf.global_variables_initializer())
      metric_vars = tf.get_collection('metrics')
      self.assertAllEqual(expected_num_vars, len(metric_vars))

      for m in metric_vars:
        self.assertEqual(0.0, m.eval())

      set_scores(tp_map, fp_map, fn_map, labels, sess)

      metric_vars = tf.get_collection('metrics')

      for m in metric_vars:
        self.assertNotEqual(0.0, m.eval())

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


text:
'use strict';

var hovertemplateAttrs = require('../../plots/template_attributes').hovertemplateAttrs;
var texttemplateAttrs = require('../../plots/template_attributes').texttemplateAttrs;
var extendFlat = require('../../lib/extend').extendFlat;
var scatterAttrs = require('../scatter/attributes');
var baseAttrs = require('../../plots/attributes');
var lineAttrs = scatterAttrs.line;

module.exports = {
    mode: scatterAttrs.mode,

    real: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        description: [
            'Sets the real component of the data, in units of normalized impedance',
            'such that real=1, imag=0 is the center of the chart.'
        ].join(' ')
    },

    imag: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        description: [
            'Sets the imaginary component of the data, in units of normalized impedance',
            'such that real=1, imag=0 is the center of the chart.'
        ].join(' ')
    },

    text: scatterAttrs.text,
    texttemplate: texttemplateAttrs({editType: 'plot'}, {
        keys: ['real', 'imag', 'text']
    }),
    hovertext: scatterAttrs.hovertext,

    line: {
        color: lineAttrs.color,
        width: lineAttrs.width,
        dash: lineAttrs.dash,
        backoff: lineAttrs.backoff,
        shape: extendFlat({}, lineAttrs.shape, {
            values: ['linear', 'spline']
        }),
        smoothing: lineAttrs.smoothing,
        editType: 'calc'
    },
    connectgaps: scatterAttrs.connectgaps,

    marker: scatterAttrs.marker,
    cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, {dflt: false}),

    textposition: scatterAttrs.textposition,
    textfont: scatterAttrs.textfont,

    fill: extendFlat({}, scatterAttrs.fill, {
        values: ['none', 'toself', 'tonext'],
        dflt: 'none',
        description: [
            'Sets the area to fill with a solid color.',
            'Use with `fillcolor` if not *none*.',
            'scattersmith has a subset of the options available to scatter.',
            '*toself* connects the endpoints of the trace (or each segment',
            'of the trace if it has gaps) into a closed shape.',
            '*tonext* fills the space between two traces if one completely',
            'encloses the other (eg consecutive contour lines), and behaves like',
            '*toself* if there is no trace before it. *tonext* should not be',
            'used if one trace does not enclose the other.'
        ].join(' ')
    }),
    fillcolor: scatterAttrs.fillcolor,

    hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
        flags: ['real', 'imag', 'text', 'name']
    }),
    hoveron: scatterAttrs.hoveron,
    hovertemplate: hovertemplateAttrs(),

    selected: scatterAttrs.selected,
    unselected: scatterAttrs.unselected
};


text:
class CreatePageTemplate < ActiveRecord::Migration[5.0]
  def change
    create_table :jambu_cms_page_templates do |t|
      t.references :jambu_cms_page, foreign_key: true
      t.references :jambu_cms_template, foreign_key: true

      t.timestamps
    end
  end
end


text:
using Miruken.Callback;

namespace Miruken.Mvc.Options
{
    using System;
    using System.Linq;
    using Views;

    public class RegionOptions : Options<RegionOptions>
    {
        public object Region    { get; set; }
        public bool?  Push      { get; set; }
        public bool?  Overlay   { get; set; }
        public bool?  Unload    { get; set; }
        public bool?  Immediate { get; set; }

        public Func<IViewLayer[], IViewLayer> Selector { get; set; }

        public IViewLayer Choose(IViewLayer[] layers)
        {
            return Selector?.Invoke(layers);
        }

        public override void MergeInto(RegionOptions other)
        {
            if (other == null) return;

            if (Region != null && other.Region == null)
                other.Region = Region;

            if (Push.HasValue && !other.Push.HasValue)
                other.Push = Push;

            if (Overlay.HasValue && !other.Overlay.HasValue)
                other.Overlay = Overlay;

            if (Unload.HasValue && !other.Unload.HasValue)
                other.Unload = Unload;

            if (Immediate.HasValue && !other.Immediate.HasValue)
                other.Immediate = Immediate;

            if (Selector != null && other.Selector == null)
                other.Selector = Selector;
        }
    }

    public static class RegionOptionsExtensions
    {
        public static IHandler Region(this IHandler handler, string region)
        {
            return new NavigationOptions
            {
                Region = new RegionOptions { Region = region }
            }.Decorate(handler);
        }

        public static IHandler PushLayer(this IHandler handler)
        {
            return new NavigationOptions
            {
                Region = new RegionOptions { Push = true }
            }.Decorate(handler);
        }

        public static IHandler Overlay(this IHandler handler)
        {
            return new NavigationOptions
            {
                Region = new RegionOptions { Overlay = true }
            }.Decorate(handler);
        }

        public static IHandler UnloadRegion(this IHandler handler)
        {
            return new NavigationOptions
            {
                Region = new RegionOptions { Unload = true }
            }.Decorate(handler);
        }

        public static IHandler DisplayImmediate(this IHandler handler)
        {
            return new NavigationOptions
            {
                Region = new RegionOptions { Immediate = true }
            }.Decorate(handler);
        }

        public static IHandler Layer(this IHandler handler, IViewLayer layer)
        {
            return new NavigationOptions
            {
                Region = new RegionOptions
                {
                    Selector = layers =>
                    {
                        if (!layers.Contains(layer))
                            throw new ArgumentException("Layer not found");
                        return layer;
                    }
                }
            }.Decorate(handler);
        }

        public static IHandler Layer(this IHandler handler, int offset)
        {
            return new NavigationOptions
            {
                Region = new RegionOptions
                {
                    Selector = layers =>
                    {
                        var index = offset < 0
                                  ? layers.Length + offset - 1
                                  : offset;
                        if (index < 0 || index >= layers.Length)
                            throw new IndexOutOfRangeException();
                        return layers[index];
                    }
                }
            }.Decorate(handler);
        }
    }
}


text:
package ubic.gemma.persistence.service.analysis.expression.coexpression;

import ubic.gemma.model.analysis.expression.coexpression.CoexpCorrelationDistribution;
import ubic.gemma.model.analysis.expression.coexpression.CoexpressionAnalysis;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.persistence.service.analysis.AnalysisDao;

import java.util.Collection;

/**
 * @see ubic.gemma.model.analysis.expression.coexpression.CoexpressionAnalysis
 */
public interface CoexpressionAnalysisDao extends AnalysisDao<CoexpressionAnalysis> {

    CoexpCorrelationDistribution getCoexpCorrelationDistribution( ExpressionExperiment expressionExperiment );

    Collection<Long> getExperimentsWithAnalysis( Collection<Long> idsToFilter );

    Boolean hasCoexpCorrelationDistribution( ExpressionExperiment ee );

}


text:
#pragma once

#include <folly/detail/Futex.h>
#include <folly/synchronization/ParkingLot.h>

namespace folly {
namespace detail {
namespace atomic_notification {
/**
 * We use Futex<std::atomic> as the alias that has the lowest performance
 * overhead with respect to atomic notifications.  Assert that
 * atomic_uint_fast_wait_t is the same as Futex<std::atomic>
 */
static_assert(std::is_same<atomic_uint_fast_wait_t, Futex<std::atomic>>{}, "");

/**
 * Implementation and specializations for the atomic_wait() family of
 * functions
 */
inline std::cv_status toCvStatus(FutexResult result) {
  return (result == FutexResult::TIMEDOUT) ? std::cv_status::timeout
                                           : std::cv_status::no_timeout;
}
inline std::cv_status toCvStatus(ParkResult result) {
  return (result == ParkResult::Timeout) ? std::cv_status::timeout
                                         : std::cv_status::no_timeout;
}

// ParkingLot instantiation for futex management
extern ParkingLot<std::uint32_t> parkingLot;

template <template <typename...> class Atom, typename... Args>
void atomic_wait_impl(
    const Atom<std::uint32_t, Args...>* atomic, std::uint32_t old) {
  futexWait(atomic, old);
  return;
}

template <template <typename...> class Atom, typename Integer, typename... Args>
void atomic_wait_impl(const Atom<Integer, Args...>* atomic, Integer old) {
  static_assert(!std::is_same<Integer, std::uint32_t>{}, "");
  parkingLot.park(
      atomic, -1, [&] { return atomic->load() == old; }, [] {});
}

template <
    template <typename...>
    class Atom,
    typename... Args,
    typename Clock,
    typename Duration>
std::cv_status atomic_wait_until_impl(
    const Atom<std::uint32_t, Args...>* atomic,
    std::uint32_t expected,
    const std::chrono::time_point<Clock, Duration>& deadline) {
  return toCvStatus(futexWaitUntil(atomic, expected, deadline));
}

template <
    template <typename...>
    class Atom,
    typename Integer,
    typename... Args,
    typename Clock,
    typename Duration>
std::cv_status atomic_wait_until_impl(
    const Atom<Integer, Args...>* atomic,
    Integer expected,
    const std::chrono::time_point<Clock, Duration>& deadline) {
  static_assert(!std::is_same<Integer, std::uint32_t>{}, "");
  return toCvStatus(parkingLot.park_until(
      atomic, -1, [&] { return atomic->load() == expected; }, [] {}, deadline));
}

template <template <typename...> class Atom, typename... Args>
void atomic_notify_one_impl(const Atom<std::uint32_t, Args...>* atomic) {
  futexWake(atomic, 1);
  return;
}

template <template <typename...> class Atom, typename Integer, typename... Args>
void atomic_notify_one_impl(const Atom<Integer, Args...>* atomic) {
  static_assert(!std::is_same<Integer, std::uint32_t>{}, "");
  parkingLot.unpark(atomic, [&](const auto& data) {
    FOLLY_SAFE_DCHECK(data == std::numeric_limits<std::uint32_t>::max(), "");
    return UnparkControl::RemoveBreak;
  });
}

template <template <typename...> class Atom, typename... Args>
void atomic_notify_all_impl(const Atom<std::uint32_t, Args...>* atomic) {
  futexWake(atomic);
  return;
}

template <template <typename...> class Atom, typename Integer, typename... Args>
void atomic_notify_all_impl(const Atom<Integer, Args...>* atomic) {
  static_assert(!std::is_same<Integer, std::uint32_t>{}, "");
  parkingLot.unpark(atomic, [&](const auto& data) {
    FOLLY_SAFE_DCHECK(data == std::numeric_limits<std::uint32_t>::max(), "");
    return UnparkControl::RemoveContinue;
  });
}

template <typename Integer>
void tag_invoke(
    atomic_wait_fn, const std::atomic<Integer>* atomic, Integer expected) {
  atomic_wait_impl(atomic, expected);
}

template <typename Integer, typename Clock, typename Duration>
std::cv_status tag_invoke(
    atomic_wait_until_fn,
    const std::atomic<Integer>* atomic,
    Integer expected,
    const std::chrono::time_point<Clock, Duration>& deadline) {
  return atomic_wait_until_impl(atomic, expected, deadline);
}

template <typename Integer>
void tag_invoke(atomic_notify_one_fn, const std::atomic<Integer>* atomic) {
  atomic_notify_one_impl(atomic);
}

template <typename Integer>
void tag_invoke(atomic_notify_all_fn, const std::atomic<Integer>* atomic) {
  atomic_notify_all_impl(atomic);
}
} // namespace atomic_notification
} // namespace detail
} // namespace folly


text:
   <title>Rivet Apache Directives</title>

	   <para>
	      Rivet directives are used within the Apache httpd server
	      configuration to set up the environment where Rivet script
	      will be run.  Their precedence is as follows:
	      <command>RivetDirConf</command>,
	      <command>RivetUserConf</command>,
	      <command>RivetServerConf</command>, meaning that DirConf will
	      override UserConf, which will in turn override ServerConf.
	   </para>
		<para>

		</para>

	   <variablelist>
   		<varlistentry>
			<term>
				<cmdsynopsis>
			   	<command>RivetServerConf</command>
			   	<group choice="req">
				      <arg>CacheSize</arg>
				      <arg>ServerInitScript</arg>
				      <arg>GlobalInitScript</arg>
				      <arg>ChildInitScript</arg>
				      <arg>ChildExitScript</arg>
				      <arg>BeforeScript</arg>
				      <arg>AfterScript</arg>
				      <arg>ErrorScript</arg>
				      <arg>AbortScript</arg>
				      <arg>AfterEveryScript</arg>
				      <arg>UploadDirectory</arg>
				      <arg>UploadMaxSize</arg>
				      <arg>UploadFilesToVar</arg>
				      <arg>SeparateChannels</arg>
				      <arg>SeparateVirtualInterps</arg>
				      <arg>HonorHeaderOnlyRequests</arg>
	    			</group>
			  </cmdsynopsis>
			</term>
			<listitem>
				<para>
					<command>RivetServerConf</command> specifies a global
			    	option that is valid for the whole server.  If you have a
			    	virtual host, in some cases, the option specified in the
			    	virtualhost takes precedence over the 'global' version.
				</para>
			</listitem>
			<listitem>
				<variablelist>
		   		<varlistentry>
		      		<term>
							<cmdsynopsis>
					  			<arg choice="plain">CacheSize</arg>
					  			<arg><replaceable>size</replaceable></arg>
							</cmdsynopsis>
		      		</term>
				   	<listitem>
							<para>
							  Sets the size of the internal page cache, where
							  <option><replaceable>size</replaceable></option> is
							  the number of byte-compiled pages to be cached for
							  future use.  Default is
							  <command>MaxRequestsPerChild</command> / 5, or 50,
							  if <command>MaxRequestsPerChild</command> is 0.
							</para>
							<para>
							  This option is completely global, even when using
							  separate, per-virtual host interpreters.
							</para>
						</listitem>
		   		</varlistentry>

		   		<varlistentry>
		   			<term>
		   				<cmdsynopsis>
				   			<arg choice="plain">ServerInitScript</arg>
				   			<arg><replaceable>script</replaceable></arg>
		   				</cmdsynopsis>
		   			</term>
		   			<listitem>
				   		<para>
				   			Tcl script which is to run when the master interpreter is created.
				   			Namespaces, variables and packages loaded during this stage will
				   			be copied later on in the startup process, when child
				   			processes are created.
				   		</para>
				   		<para>
	                        This option is only available at the global level.
				   		</para>
				   		<para>
						    	The directive <command>ServerInitScript</command> plays a special
						    	role since the script runs within the master interpreter,
						    	an interpreter created before the Apache parent process spawns
						    	the children that actually will serve the requests coming from
						    	the network. During this stage Apache is still running as a
						    	single process, so this is the right place for doing
						    	initializations or loading packages. Since this
						    	script will be running in a single process environment (from the
						    	Apache point of view) <command>ServerInitScript</command>
						    	is also the right place for doing anything needs to avoid
					        	resource concurrency among processes (e.g. the creation and
						    	initialization of an IPC system)
	   					</para>

		   			</listitem>
					</varlistentry>

	   		<varlistentry>
			      <term>
						<cmdsynopsis>
						  <arg choice="plain">GlobalInitScript</arg>
						  <arg><replaceable>script</replaceable></arg>
						</cmdsynopsis>
			      </term>
			      <listitem>
						<para>
						  Tcl script run as part of a child process initialization.
						  If the option <option>SeparateVirtualInterp</option> is not used this is
						  the right place where file handles, database connections or sockets can
						  be opened.
						  The argument <replaceable><option>script</option></replaceable>
						  is an actual Tcl script, so to run a file, you would
						  do: <programlisting>RivetServerConf GlobalInitScript "source /var/www/foobar.tcl"</programlisting>
						</para>
						<para>
						  This option is ignored in virtual hosts.
						</para>
			      </listitem>
	  			</varlistentry>

			  	<varlistentry>
			      <term>
						<cmdsynopsis>
						  <arg choice="plain">ChildInitScript</arg>
						  <arg><replaceable>script</replaceable></arg>
						</cmdsynopsis>
			      </term>
			      <listitem>
						<para>
						  Script to be evaluated when each Apache child
						  process is initialized. This is the recommended
						  place to load modules, create global variables, open
						  connections to other facilities (such as databases)
						  and so on.
						</para>
						<para>
						  In virtual hosts, this script is run in addition to
						  any global childinitscript.
		                  When <command>SeparateVirtualInterp</command>
		                  any <command>ChildInitScript</command> placed within a
		                  <option><VirtualHost ...>....</VirtualHost></option>
		                  will be that Virtual Host specific ininitalization
						</para>
			      </listitem>
				</varlistentry>

				<varlistentry>
		      	<term>
						<cmdsynopsis>
					  		<arg choice="plain">ChildExitScript</arg>
					  		<arg><replaceable>script</replaceable></arg>
						</cmdsynopsis>
		      	</term>
		      	<listitem>
						<para>
						  Script to be evaluated when each Apache child
						  process exits. This is the logical place to clean
						  up resources created in <option>ChildInitScript</option>,
						  if necessary.
						</para>
						<para>
						  In virtual hosts, this script is run in addition to
						  any global childexitscript.

		              When <command>SeparateVirtualInterp</command>
		              any <command>ChildExitScript</command> placed within a
		              <option><VirtualHost ...>....</VirtualHost></option>
		              will be that Virtual Host specific exit handler
						</para>
		      	</listitem>
				</varlistentry>

		   	<varlistentry>
		      	<term>
						<cmdsynopsis>
					  		<arg choice="plain">BeforeScript</arg>
					  		<arg><replaceable>script</replaceable></arg>
						</cmdsynopsis>
		      	</term>
		      	<listitem>
						<para>
						  Script to be evaluated before each server parsed
						  (.rvt) page.  This can be used to create a standard
						  header, for instance.  It could also be used to load
						  code that you need for every page, if you don't want
						  to put it in a <option>GlobalInitScript</option>
						  <option>ChildInitScript</option> when you are first
						  developing a web site.
						  <note>
						    This code is evaluated at the global level, not
						    inside the request namespace where pages are
						    evaluated.
						  </note>
						</para>
						<para>
						  In virtual hosts, this option takes precedence over
						  the global setting.
						</para>
		    		</listitem>
				</varlistentry>

	   		<varlistentry>
	      		<term>
						<cmdsynopsis>
						  <arg choice="plain">AfterScript</arg>
						  <arg><replaceable>script</replaceable></arg>
						</cmdsynopsis>
	      		</term>
	      		<listitem>
						<para>
						  Script to be called after each server parsed (.rvt) page.
						</para>
						<para>
						  In virtual hosts, this option takes precedence over
						  the global setting.
						</para>
	      		</listitem>
	    		</varlistentry>

		    <varlistentry>
		      <term>
					<cmdsynopsis>
					  <arg choice="plain">ErrorScript</arg>
					  <arg><replaceable>script</replaceable></arg>
					</cmdsynopsis>
		      </term>
		      <listitem>
					<para>
					  When Rivet encounters an error in a script, it
					  constructs an HTML page with some information about
					  the error, and the script that was being
					  evaluated. If an <option>ErrorScript</option> is
					  specified, it is possible to create custom error
					  pages.  This may be useful if you want to make sure
					  that users never view your source code.
					</para>
					<para>
					  In virtual hosts, this option takes precedence over
					  the global setting.
					</para>
		      </listitem>
		    </varlistentry>

	    <varlistentry>
	      <term>
				<cmdsynopsis>
				  <arg choice="plain">AfterEveryScript</arg>
				  <arg><replaceable>script</replaceable></arg>
				</cmdsynopsis>
	      </term>
	      <listitem>
				<para>
					<option>AfterEveryScript</option> is a script that is to
					be run anyway before requests processing ends. This script
					is therefore run both when the content generation script
					completes successfully and when its execution is interrupted
					by <xref linkend="abort_page" />. The code in this script
					can understand whether it's running after the page was
					interrupted by calling <xref linkend="abort_page" />
					with the argument <arg>-aborting</arg>. The command
					will return 1 if an abort_page call took place
					earlier in the request processing.
				</para>
	      </listitem>
	    </varlistentry>

		<varlistentry>
			<term>
				<cmdsynopsis>
					<arg choice="plain">AbortScript</arg>
					<arg><replaceable>script</replaceable></arg>
				</cmdsynopsis>
			</term>
			<listitem>
				<para>
					The execution of a can be interrupted by
					invoking <xref linkend="abort_page" />. If
					an <option>AbortScript</option> is defined for the page
					being generated, control is passed to it. <option>AbortScript</option>
					is the right place where specific actions can be taken
					to catch resources left dangling by the sudden interruption.
				</para>
			</listitem>
		</varlistentry>

	   <varlistentry>
	      <term>
				<cmdsynopsis>
				  <arg choice="plain">UploadDirectory</arg>
				  <arg><replaceable>directory</replaceable></arg>
				</cmdsynopsis>
	      </term>
	      <listitem>
				<para>Directory to place uploaded files.</para>
				<para>
		  			In virtual hosts, this option takes precedence over
		  			the global setting.
				</para>
	      </listitem>
	  </varlistentry>

	  <varlistentry>
	      <term>
		<cmdsynopsis>
		  <arg choice="plain">UploadMaxSize</arg>
		  <arg><replaceable>size</replaceable></arg>
		</cmdsynopsis>
	      </term>
	      <listitem>
		<para>Maximum size for uploaded files.</para>
		<para>
		  In virtual hosts, this option takes precedence over
		  the global setting.
		</para>
	      </listitem>
	    </varlistentry>

	    <varlistentry>
	      <term>
		<cmdsynopsis>
		  <arg choice="plain">UploadFilesToVar</arg>
		  <group choice="req"><arg>yes</arg><arg>no</arg></group>
		</cmdsynopsis>
	      </term>
	      <listitem>
		<para>
		  This option controls whether it is possible to
		  upload files to a Tcl variable.  If you have a size
		  limit, and don't have to deal with large files, this
		  might be more convenient than sending the data to a
		  file on disk.
		</para>
	      </listitem>
	    </varlistentry>

	    <varlistentry>
	      <term>
		     <cmdsynopsis>
		       <arg choice="plain">SeparateChannels</arg>
		       <group choice="req">
		          <arg>yes</arg>
		          <arg>no</arg>
		       </group>
		     </cmdsynopsis>
		  </term>
	      <listitem>
      		<para>
      			Internally mod_rivet creates a new Tcl channel (Rivet channel) which is configured
      			as <command>stdout</command> and registered to each existing interpreter.
      			There is no need of multiple channels in a single thread as each thread can
      			serve only one request at a time. But if you are deploying mod_rivet in a
      			complex environment running unrelated applications developed by
      			different teams, it could be the case to have <command>SeparateVirtualInterps</command>
      			set. If you want to enhance the environment separation you may also
      			set <command>SeparateChannels</command> to force mod_rivet to create
      			a channel per each Tcl interpreter thus enabling single application
      			code to change the Rivet channel parameters without affecting other
      			applications (even though changing the Tcl channel parameters is a rare
      			necessity). Setting this options increases the system overheads as each
      			Rivet channel needs to allocate its own control structures and internal
      			buffers.
      		</para>
      		<note>
      			This option is implemented in order to have fine-grained control over mod_rivet. In
      			nearly all practical cases you won't need to change Rivet Channel (stdout) settings
      			for different applications by calling <command>fconfigure stdout ....</command>.
      			This option is, by nature, only available at the global level and has effect only if
   		      also <command>SeparateVirtualInterps</command> is set
   		   </note>
	      </listitem>
	    </varlistentry>

	    <varlistentry>
	      <term>
		     <cmdsynopsis>
		       <arg choice="plain">SeparateVirtualInterps</arg>
		       <group choice="req">
		          <arg>yes</arg>
		          <arg>no</arg>
		       </group>
		     </cmdsynopsis>
		  </term>
	      <listitem>
      		<para>
      		  If on, Rivet will create a separate Tcl interpreter
      		  for each Apache virtual host.  This is useful in an
      		  ISP type situation where it is desirable to separate
      		  clients into separate interpreters, so that they
      		  don't accidentally interfere with one another.
      		</para>
   		    <note>
   		      This option is, by nature, only available at the
   		      global level. By enabling <command>SeparateVirtualInterps</command>
   		      you must rely only on <command>ChildInitScript</command> to
   		      initialize the interpreters. Don't expect the
   		      initialization done in <command>ServerInitScript</command> and
   		      <command>GlobalInitScript</command> to be handed down to the
   		      slave interpreters that are private to each configured
   		      virtual host.
   		   </note>
	      </listitem>
	    </varlistentry>

	    <varlistentry>
	      <term>
		<cmdsynopsis>
		  <arg choice="plain">HonorHeaderOnlyRequests</arg>
		  <group choice="req">
		    <arg>yes</arg>
		    <arg>no</arg>
		  </group>
		</cmdsynopsis>
	      </term>
	      <listitem>
		<para>
		  If a HEAD requests is issued by the client Rivet detects
		  this case and sends back to the client a standard header
		  response. If the real header has to be examined (e.g.
		  for debugging) you can turn this options on.
		</para>
		<para>This option is, by nature, only available at the global level</para>
	      </listitem>
	    </varlistentry>
	  </variablelist>
	</listitem>
      </varlistentry>
      	<varlistentry>
			<term>
			  <cmdsynopsis>
			    <command>RivetDirConf</command>
			    <group choice="req">
			      <arg>BeforeScript</arg>
			      <arg>AfterScript</arg>
			      <arg>ErrorScript</arg>
			      <arg>UploadDirectory</arg>
                  <arg>AfterEveryScript</arg>
			    </group>
			  </cmdsynopsis>
			</term>
			<listitem>
			  <para>
			    These options are the same as for
			    <command>RivetServerConf</command>, except that they are
			    only valid for the directory where they are specified, and
			    its subdirectories.  It may be specified in <command>Directory</command>
			    sections.
			  </para>
			</listitem>
      </varlistentry>
      	<varlistentry>
			<term>
			  <cmdsynopsis>
			    <command>RivetUserConf</command>
			    <group choice="req">
			      <arg>BeforeScript</arg>
			      <arg>AfterScript</arg>
			      <arg>ErrorScript</arg>
			      <arg>UploadDirectory</arg>
                  <arg>AfterEveryScript</arg>
			    </group>
			  </cmdsynopsis>
			</term>
			<listitem>
			  <para>
			    These options are the same as for
			    <command>RivetServerConf</command>, except that they are
			    only valid for the directory where they are specified, and
			    its subdirectories.
			  </para>
			</listitem>
      </varlistentry>
		</variablelist>


text:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
class QAbstractItemModel;
class QAbstractItemView;
class QItemSelectionModel;
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow();

private slots:
    void openFile(const QString &path = QString());
    void saveFile();

private:
    void setupModel();
    void setupViews();

    QAbstractItemModel *model;
    QAbstractItemView *pieChart;
    QItemSelectionModel *selectionModel;
};

#endif


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Handles actions related to GIS MULTILINESTRING objects
 *
 * @package PhpMyAdmin-GIS
 */

if (! defined('PHPMYADMIN')) {
    exit;
}

/**
 * Handles actions related to GIS MULTILINESTRING objects
 *
 * @package PhpMyAdmin-GIS
 */
class PMA_GIS_Multilinestring extends PMA_GIS_Geometry
{
    // Hold the singleton instance of the class
    private static $_instance;

    /**
     * A private constructor; prevents direct creation of object.
     *
     * @access private
     */
    private function __construct()
    {
    }

    /**
     * Returns the singleton.
     *
     * @return PMA_GIS_Multilinestring the singleton
     * @access public
     */
    public static function singleton()
    {
        if (!isset(self::$_instance)) {
            $class = __CLASS__;
            self::$_instance = new $class;
        }

        return self::$_instance;
    }

    /**
     * Scales each row.
     *
     * @param string $spatial spatial data of a row
     *
     * @return array an array containing the min, max values for x and y coordinates
     * @access public
     */
    public function scaleRow($spatial)
    {
        $min_max = array();

        // Trim to remove leading 'MULTILINESTRING((' and trailing '))'
        $multilinestirng = /*overload*/mb_substr(
            $spatial,
            17,
            /*overload*/mb_strlen($spatial) - 19
        );
        // Separate each linestring
        $linestirngs = explode("),(", $multilinestirng);

        foreach ($linestirngs as $linestring) {
            $min_max = $this->setMinMax($linestring, $min_max);
        }

        return $min_max;
    }

    /**
     * Adds to the PNG image object, the data related to a row in the GIS dataset.
     *
     * @param string $spatial    GIS MULTILINESTRING object
     * @param string $label      Label for the GIS MULTILINESTRING object
     * @param string $line_color Color for the GIS MULTILINESTRING object
     * @param array  $scale_data Array containing data related to scaling
     * @param object $image      Image object
     *
     * @return object the modified image object
     * @access public
     */
    public function prepareRowAsPng($spatial, $label, $line_color,
        $scale_data, $image
    ) {
        // allocate colors
        $black = imagecolorallocate($image, 0, 0, 0);
        $red   = hexdec(/*overload*/mb_substr($line_color, 1, 2));
        $green = hexdec(/*overload*/mb_substr($line_color, 3, 2));
        $blue  = hexdec(/*overload*/mb_substr($line_color, 4, 2));
        $color = imagecolorallocate($image, $red, $green, $blue);

        // Trim to remove leading 'MULTILINESTRING((' and trailing '))'
        $multilinestirng = /*overload*/mb_substr(
            $spatial,
            17,
            /*overload*/mb_strlen($spatial) - 19
        );
        // Separate each linestring
        $linestirngs = explode("),(", $multilinestirng);

        $first_line = true;
        foreach ($linestirngs as $linestring) {
            $points_arr = $this->extractPoints($linestring, $scale_data);
            foreach ($points_arr as $point) {
                if (! isset($temp_point)) {
                    $temp_point = $point;
                } else {
                    // draw line section
                    imageline(
                        $image, $temp_point[0], $temp_point[1],
                        $point[0], $point[1], $color
                    );
                    $temp_point = $point;
                }
            }
            unset($temp_point);
            // print label if applicable
            if (isset($label) && trim($label) != '' && $first_line) {
                imagestring(
                    $image, 1, $points_arr[1][0],
                    $points_arr[1][1], trim($label), $black
                );
            }
            $first_line = false;
        }
        return $image;
    }

    /**
     * Adds to the TCPDF instance, the data related to a row in the GIS dataset.
     *
     * @param string $spatial    GIS MULTILINESTRING object
     * @param string $label      Label for the GIS MULTILINESTRING object
     * @param string $line_color Color for the GIS MULTILINESTRING object
     * @param array  $scale_data Array containing data related to scaling
     * @param TCPDF  $pdf        TCPDF instance
     *
     * @return TCPDF the modified TCPDF instance
     * @access public
     */
    public function prepareRowAsPdf($spatial, $label, $line_color, $scale_data, $pdf)
    {
        // allocate colors
        $red   = hexdec(/*overload*/mb_substr($line_color, 1, 2));
        $green = hexdec(/*overload*/mb_substr($line_color, 3, 2));
        $blue  = hexdec(/*overload*/mb_substr($line_color, 4, 2));
        $line  = array('width' => 1.5, 'color' => array($red, $green, $blue));

        // Trim to remove leading 'MULTILINESTRING((' and trailing '))'
        $multilinestirng = /*overload*/mb_substr(
            $spatial,
            17, /*overload*/mb_strlen($spatial) - 19
        );
        // Separate each linestring
        $linestirngs = explode("),(", $multilinestirng);

        $first_line = true;
        foreach ($linestirngs as $linestring) {
            $points_arr = $this->extractPoints($linestring, $scale_data);
            foreach ($points_arr as $point) {
                if (! isset($temp_point)) {
                    $temp_point = $point;
                } else {
                    // draw line section
                    $pdf->Line(
                        $temp_point[0], $temp_point[1], $point[0], $point[1], $line
                    );
                    $temp_point = $point;
                }
            }
            unset($temp_point);
            // print label
            if (isset($label) && trim($label) != '' && $first_line) {
                $pdf->SetXY($points_arr[1][0], $points_arr[1][1]);
                $pdf->SetFontSize(5);
                $pdf->Cell(0, 0, trim($label));
            }
            $first_line = false;
        }
        return $pdf;
    }

    /**
     * Prepares and returns the code related to a row in the GIS dataset as SVG.
     *
     * @param string $spatial    GIS MULTILINESTRING object
     * @param string $label      Label for the GIS MULTILINESTRING object
     * @param string $line_color Color for the GIS MULTILINESTRING object
     * @param array  $scale_data Array containing data related to scaling
     *
     * @return string the code related to a row in the GIS dataset
     * @access public
     */
    public function prepareRowAsSvg($spatial, $label, $line_color, $scale_data)
    {
        $line_options = array(
            'name'        => $label,
            'class'       => 'linestring vector',
            'fill'        => 'none',
            'stroke'      => $line_color,
            'stroke-width'=> 2,
        );

        // Trim to remove leading 'MULTILINESTRING((' and trailing '))'
        $multilinestirng = /*overload*/mb_substr(
            $spatial,
            17,
            /*overload*/mb_strlen($spatial) - 19
        );
        // Separate each linestring
        $linestirngs = explode("),(", $multilinestirng);

        $row = '';
        foreach ($linestirngs as $linestring) {
            $points_arr = $this->extractPoints($linestring, $scale_data);

            $row .= '<polyline points="';
            foreach ($points_arr as $point) {
                $row .= $point[0] . ',' . $point[1] . ' ';
            }
            $row .= '"';
            $line_options['id'] = $label . rand();
            foreach ($line_options as $option => $val) {
                $row .= ' ' . $option . '="' . trim($val) . '"';
            }
            $row .= '/>';
        }

        return $row;
    }

    /**
     * Prepares JavaScript related to a row in the GIS dataset
     * to visualize it with OpenLayers.
     *
     * @param string $spatial    GIS MULTILINESTRING object
     * @param int    $srid       Spatial reference ID
     * @param string $label      Label for the GIS MULTILINESTRING object
     * @param string $line_color Color for the GIS MULTILINESTRING object
     * @param array  $scale_data Array containing data related to scaling
     *
     * @return string JavaScript related to a row in the GIS dataset
     * @access public
     */
    public function prepareRowAsOl($spatial, $srid, $label, $line_color, $scale_data)
    {
        $style_options = array(
            'strokeColor' => $line_color,
            'strokeWidth' => 2,
            'label'       => $label,
            'fontSize'    => 10,
        );
        if ($srid == 0) {
            $srid = 4326;
        }
        $row = $this->getBoundsForOl($srid, $scale_data);

        // Trim to remove leading 'MULTILINESTRING((' and trailing '))'
        $multilinestirng = /*overload*/mb_substr(
            $spatial,
            17,
            /*overload*/mb_strlen($spatial) - 19
        );
        // Separate each linestring
        $linestirngs = explode("),(", $multilinestirng);

        $row .= 'vectorLayer.addFeatures(new OpenLayers.Feature.Vector('
            . 'new OpenLayers.Geometry.MultiLineString('
            . $this->getLineArrayForOpenLayers($linestirngs, $srid)
            . '), null, ' . json_encode($style_options) . '));';
        return $row;
    }

    /**
     * Generate the WKT with the set of parameters passed by the GIS editor.
     *
     * @param array  $gis_data GIS data
     * @param int    $index    Index into the parameter object
     * @param string $empty    Value for empty points
     *
     * @return string WKT with the set of parameters passed by the GIS editor
     * @access public
     */
    public function generateWkt($gis_data, $index, $empty = '')
    {
        $data_row = $gis_data[$index]['MULTILINESTRING'];

        $no_of_lines = isset($data_row['no_of_lines'])
            ? $data_row['no_of_lines'] : 1;
        if ($no_of_lines < 1) {
            $no_of_lines = 1;
        }

        $wkt = 'MULTILINESTRING(';
        for ($i = 0; $i < $no_of_lines; $i++) {
            $no_of_points = isset($data_row[$i]['no_of_points'])
                ? $data_row[$i]['no_of_points'] : 2;
            if ($no_of_points < 2) {
                $no_of_points = 2;
            }
            $wkt .= '(';
            for ($j = 0; $j < $no_of_points; $j++) {
                $wkt .= ((isset($data_row[$i][$j]['x'])
                    && trim($data_row[$i][$j]['x']) != '')
                    ? $data_row[$i][$j]['x'] : $empty)
                    . ' ' . ((isset($data_row[$i][$j]['y'])
                    && trim($data_row[$i][$j]['y']) != '')
                    ? $data_row[$i][$j]['y'] : $empty) . ',';
            }
            $wkt = /*overload*/mb_substr($wkt, 0, /*overload*/mb_strlen($wkt) - 1);
            $wkt .= '),';
        }
        $wkt = /*overload*/mb_substr($wkt, 0, /*overload*/mb_strlen($wkt) - 1);
        $wkt .= ')';
        return $wkt;
    }

    /**
     * Generate the WKT for the data from ESRI shape files.
     *
     * @param array $row_data GIS data
     *
     * @return string the WKT for the data from ESRI shape files
     * @access public
     */
    public function getShape($row_data)
    {
        $wkt = 'MULTILINESTRING(';
        for ($i = 0; $i < $row_data['numparts']; $i++) {
            $wkt .= '(';
            foreach ($row_data['parts'][$i]['points'] as $point) {
                $wkt .= $point['x'] . ' ' . $point['y'] . ',';
            }
            $wkt = /*overload*/mb_substr($wkt, 0, /*overload*/mb_strlen($wkt) - 1);
            $wkt .= '),';
        }
        $wkt = /*overload*/mb_substr($wkt, 0, /*overload*/mb_strlen($wkt) - 1);
        $wkt .= ')';
        return $wkt;
    }

    /**
     * Generate parameters for the GIS data editor from the value of the GIS column.
     *
     * @param string $value Value of the GIS column
     * @param int    $index Index of the geometry
     *
     * @return array params for the GIS data editor from the value of the GIS column
     * @access public
     */
    public function generateParams($value, $index = -1)
    {
        $params = array();
        if ($index == -1) {
            $index = 0;
            $data = PMA_GIS_Geometry::generateParams($value);
            $params['srid'] = $data['srid'];
            $wkt = $data['wkt'];
        } else {
            $params[$index]['gis_type'] = 'MULTILINESTRING';
            $wkt = $value;
        }

        // Trim to remove leading 'MULTILINESTRING((' and trailing '))'
        $multilinestirng = /*overload*/mb_substr(
            $wkt,
            17,
            /*overload*/mb_strlen($wkt) - 19
        );
        // Seperate each linestring
        $linestirngs = explode("),(", $multilinestirng);
        $params[$index]['MULTILINESTRING']['no_of_lines'] = count($linestirngs);

        $j = 0;
        foreach ($linestirngs as $linestring) {
            $points_arr = $this->extractPoints($linestring, null);
            $no_of_points = count($points_arr);
            $params[$index]['MULTILINESTRING'][$j]['no_of_points'] = $no_of_points;
            for ($i = 0; $i < $no_of_points; $i++) {
                $params[$index]['MULTILINESTRING'][$j][$i]['x'] = $points_arr[$i][0];
                $params[$index]['MULTILINESTRING'][$j][$i]['y'] = $points_arr[$i][1];
            }
            $j++;
        }
        return $params;
    }
}
?>


text:
module Gws::Schedule::CalendarFormat
  extend ActiveSupport::Concern

  # event options
  # http://fullcalendar.io/docs/event_data/Event_Object/
  def calendar_format(user, site)
    data = { id: id.to_s, start: start_at, end: end_at, allDay: allday? }

    #data[:readable] = allowed?(:read, user, site: site)
    data[:readable] = readable?(user, site: site)
    data[:editable] = allowed?(:edit, user, site: site)

    data[:title] = I18n.t("gws/schedule.private_plan")
    if data[:readable]
      data[:title] = name

      if html.present?
        data[:sanitizedHtml] = ::ApplicationController.helpers.sanitize(html, tags: []).squish.truncate(120)
      end
    end

    #data[:termLabel] = Gws::Schedule::PlansController.helpers.term(self)
    data[:startDateLabel] = date_label(start_at)
    data[:startTimeLabel] = time_label(start_at)
    data[:endDateLabel] = date_label(end_at)
    data[:endTimeLabel] = time_label(end_at)
    data[:allDayLabel] = label(:allday)

    coloring = color.present? ? self : try(:category)

    if allday? || start_at.to_date != end_at.to_date
      data[:className] = 'fc-event-range'
      data[:backgroundColor] = coloring.color if coloring
      data[:textColor] = coloring.text_color if coloring
    else
      data[:className] = 'fc-event-point'
      data[:textColor] = coloring.color if coloring
    end

    if allday?
      data[:start] = start_at.to_date
      data[:end] = (end_at + 1.day).to_date
      data[:className] += ' fc-event-allday'
    end

    if repeat_plan_id
      data[:title]      = " #{data[:title]}"
      data[:className] += ' fc-event-repeat'
    end

    if (data[:readable] && private_plan?(user)) || data[:title] == I18n.t("gws/schedule.private_plan")
      data[:className] += ' fc-event-private'
    end

    if approval_check_plan?
      data[:className] += " fc-event-approval-#{approval_state}"
    end

    if self.try(:category)
      data[:className] += " fc-event-category"
      data[:category] = category.name
    end

    if self.try(:facilities).present?
      data[:className] += " fc-event-facility"
      data[:facility] = facilities.first.try(:name)
    end

    data
  end

  def set_attendance_classes(data, cur_user, attendance_user_id)
    return data if !attendance_check_plan?

    if attendance_absence_all?
      data[:className] += " fc-event-user-attendance-absence"
      return data
    end

    attendance = attendances.where(user_id: attendance_user_id).order_by(created: 1).first
    attendance_state = attendance.try(:attendance_state) || 'unknown'
    data[:className] += " fc-event-user-attendance-#{attendance_state}"

    if attendance_state == "absence"
      return nil if cur_user.id != attendance_user_id

      data[:className] += ' hide'
    end

    data
  end
end


text:
describe('$.fn', function () {
    describe('getElement method', function () {
        it('should return elements by the name of the element', function () {
            // Arrange.
            setFixtures('\

\

\

\

\

\

\

\

\

\
            ');

            // Act.
            var $elements = $('.product').getElement('name');

            // Assert.
            expect($elements.length).toEqual(2);
            expect($elements[0].id).toEqual('name2');
            expect($elements[1].id).toEqual('name3');
        });

        it('should return elements by the name of the element and the modifier', function () {
            // Arrange.
            setFixtures('\

\

\

\

\

\

\

\

\

\

\

\

\
            ');

            // Act.
            var $elements = $('.product').getElement('name', 'is-selected');

            // Assert.
            expect($elements.length).toEqual(2);
            expect($elements[0].id).toEqual('name3');
            expect($elements[1].id).toEqual('name4');
        });

        it('should return elements by the name of the element and a string of modifiers', function () {
            // Arrange.
            setFixtures('\

\

\

\

\

\

\

\

\

\

\

\

\

\
            ');

            // Act.
            var $elements = $('.product').getElement('name', 'is-selected size_xs');

            // Assert.
            expect($elements.length).toEqual(2);
            expect($elements[0].id).toEqual('name3');
            expect($elements[1].id).toEqual('name5');
        });

        it('should return elements by the name of the element, the name of the modifier and the value of the modifier', function () {
            // Arrange.
            setFixtures('\

\

\

\

\

\

\

\

\

\

\

\

\

\
            ');

            // Act.
            var $elements = $('.product').getElement('name', 'size', 'xs');

            // Assert.
            expect($elements.length).toEqual(2);
            expect($elements[0].id).toEqual('name3');
            expect($elements[1].id).toEqual('name4');
        });
    });
});