text:
"""Tests for sparse ops."""

from absl.testing import parameterized
import numpy as np

from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import test_util
# Need array_grad to register gradient for Identity.
from tensorflow.python.ops import array_grad  # pylint: disable=unused-import
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_sparse_ops
from tensorflow.python.ops import gradient_checker_v2 as gradient_checker
from tensorflow.python.ops import math_ops
# Need sparse_grad to register gradient for SparseToDense.
from tensorflow.python.ops import sparse_grad  # pylint: disable=unused-import
from tensorflow.python.ops import sparse_ops
from tensorflow.python.platform import googletest

@test_util.run_all_in_graph_and_eager_modes
class SparseOpsTest(test_util.TensorFlowTestCase, parameterized.TestCase):

  def testSparseEye(self):
    def test_one(n, m, as_tensors):
      expected = np.eye(n, m)
      if as_tensors:
        m = constant_op.constant(m)
        n = constant_op.constant(n)
      s = sparse_ops.sparse_eye(n, m)
      d = sparse_ops.sparse_to_dense(s.indices, s.dense_shape, s.values)
      self.assertAllEqual(self.evaluate(d), expected)

    for n in range(2, 10, 2):
      for m in range(2, 10, 2):
        # Test with n and m as both constants and tensors.
        test_one(n, m, True)
        test_one(n, m, False)

  def testDenseFromConstantToSparse(self):
    expected_constant = np.reshape(np.arange(24, dtype=np.int64), (3, 4, 2))
    tensor = constant_op.constant(expected_constant)
    sparse = sparse_ops.from_dense(tensor)
    dense = sparse_ops.sparse_to_dense(sparse.indices, sparse.dense_shape,
                                       sparse.values)
    constant = self.evaluate(dense)
    self.assertAllEqual(expected_constant, constant)

  def testTransposePreservesShape(self):
    with ops.Graph().as_default():
      t = sparse_tensor.SparseTensor(indices=[[0, 0]],
                                     values=[0.],
                                     dense_shape=[3, 4])
      self.assertTrue(t.shape.is_fully_defined)
      transposed = sparse_ops.sparse_transpose(t)
      self.assertAllEqual(transposed.shape, [4, 3])

  def testSparseExpandDims(self):
    for rank in range(1, 4):
      # Create a dummy input. When rank=3, shape=[2, 4, 6].
      shape = np.arange(1, rank + 1) * 2
      before = np.arange(np.prod(shape)).reshape(shape)

      # Make entries sparse.
      before *= np.random.binomial(1, .2, before.shape)
      dense_shape = before.shape
      indices = np.array(np.where(before)).T
      values = before[before != 0]

      # Try every possible valid value of axis.
      for axis in range(-rank - 1, rank):
        expected_after = np.expand_dims(before, axis)

        for axis_as_tensor in [False, True]:
          dense_shape_t = constant_op.constant(dense_shape, dtype=dtypes.int64)
          indices_t = constant_op.constant(indices)
          values_t = constant_op.constant(values)
          before_t = sparse_tensor.SparseTensor(
              indices=indices_t, values=values_t, dense_shape=dense_shape_t)

          if axis_as_tensor:
            axis = constant_op.constant(axis)

          s = sparse_ops.sparse_expand_dims(before_t, axis)
          d = sparse_ops.sparse_to_dense(s.indices, s.dense_shape, s.values)
          self.assertAllEqual(self.evaluate(d), expected_after)

  @parameterized.parameters([
      (math_ops.abs, [1.0, -1.0, 3.0, -4.0], [1.0, 1.0, 3.0, 4.0]),
      (math_ops.negative, [1.0, -1.0, 3.0, -4.0], [-1.0, 1.0, -3.0, 4.0]),
      (math_ops.sign, [3.0, -2.0, 0.0, -4.0], [1.0, -1.0, 0.0, -1.0]),
      (math_ops.square, [1.0, -1.0, 3.0, -4.0], [1.0, 1.0, 9.0, 16.0]),
  ])
  def testUnarySparseDispatch(self, op, values, expected):
    st = sparse_tensor.SparseTensor(
        indices=[[0, 0], [0, 1], [2, 0], [2, 4]],
        values=values,
        dense_shape=[3, 6])
    result = op(st)
    result_value = self.evaluate(result)
    self.assertAllEqual(result_value.indices, st.indices)
    self.assertAllEqual(result_value.values, expected)
    self.assertAllEqual(result_value.dense_shape, st.dense_shape)

  def testSparseToDenseGradient(self):

    def f(sparse_values, default_value):
      st = sparse_tensor.SparseTensor(
          indices=[[0, 3, 6], [1, 4, 7], [2, 5, 8]],
          values=sparse_values,
          dense_shape=[3, 6, 9])
      return sparse_ops.sparse_tensor_to_dense(st, default_value)

    grads = gradient_checker.compute_gradient(
        f, [constant_op.constant([1.0, 2.0, 3.0]),
            constant_op.constant(0.0)])
    epsilon = 1e-4
    self.assertLess(gradient_checker.max_error(*grads), epsilon)

  def testSparseTensorToDenseString(self):
    sp = sparse_tensor.SparseTensor(
        indices=[[0, 0], [1, 2]], values=['a', 'b'], dense_shape=[2, 3])
    dense = sparse_ops.sparse_tensor_to_dense(sp)
    expected_dense = [[b'a', b'', b''], [b'', b'', b'b']]
    result_dense = self.evaluate(dense)
    self.assertAllEqual(expected_dense, result_dense)

  def testDenseSparseTensorMatMul(self):

    np.random.seed(42)
    dense_numpy_array = np.random.rand(3, 3)
    independent_dense_tf = constant_op.constant(
        dense_numpy_array, dtype='float32')

    sp = sparse_tensor.SparseTensor(
        indices=[[0, 0], [1, 2]], values=[4., 8.], dense_shape=[3, 3])
    dense_of_sparse = sparse_ops.sparse_to_dense(sp.indices, sp.shape,
                                                 sp.values)

    result = sparse_ops.sparse_tensor_dense_matmul(
        independent_dense_tf, sp, adjoint_a=False, adjoint_b=False)
    expected = math_ops.matmul(independent_dense_tf, dense_of_sparse)
    self.assertAllEqual(expected, result)

    result = sparse_ops.sparse_tensor_dense_matmul(
        independent_dense_tf, sp, adjoint_a=False, adjoint_b=True)
    expected = math_ops.matmul(independent_dense_tf,
                               array_ops.transpose(dense_of_sparse))
    self.assertAllEqual(expected, result)

    result = sparse_ops.sparse_tensor_dense_matmul(
        independent_dense_tf, sp, adjoint_a=True, adjoint_b=False)
    expected = math_ops.matmul(
        array_ops.transpose(independent_dense_tf), dense_of_sparse)
    self.assertAllEqual(expected, result)

    result = sparse_ops.sparse_tensor_dense_matmul(
        independent_dense_tf, sp, adjoint_a=True, adjoint_b=True)
    expected = math_ops.matmul(
        array_ops.transpose(independent_dense_tf),
        array_ops.transpose(dense_of_sparse))
    self.assertAllEqual(expected, result)

  def testMapValues(self):
    # supplying no sparse tensor should result in ValueError
    with self.assertRaises(ValueError):
      sparse_ops.map_values(math_ops.abs, 0.0)

    sp = sparse_ops.from_dense([[0.0, 1.0, 0.0], [-2.0, 1.0, 0.0]])

    # helper function to check equality of sparse tensor
    def assert_sparse_equal(expected, result):
      self.assertAllEqual(expected.values, result.values, msg='Values differ')
      self.assertAllEqual(
          expected.indices, result.indices, msg='Indices differ')
      self.assertAllEqual(
          expected.dense_shape, result.dense_shape, msg='Shapes differ')

    # check for a single sparse argument
    expected = sparse_ops.from_dense([[0.0, 1.0, 0.0], [2.0, 1.0, 0.0]])
    result = sparse_ops.map_values(math_ops.abs, sp)
    assert_sparse_equal(expected, result)

    # check correct passing of keyword argument, and handling of two sparse
    # arguments at the same time
    def mapping(arg1, arg2, kwarg):
      self.assertEqual(kwarg, 'kwarg')
      return arg1 + arg2

    result = sparse_ops.map_values(mapping, sp, sp, kwarg='kwarg')
    expected = sparse_ops.from_dense([[0.0, 2.0, 0.0], [-4.0, 2.0, 0.0]])
    assert_sparse_equal(expected, result)

    # check that index mismatches are correctly detected even if the `value`s
    # have compatible shape
    sp_incomp = sparse_ops.from_dense([[0.0, 1.0, 0.0], [-2.0, 0.0, 1.0]])
    with self.assertRaises((errors.InvalidArgumentError, ValueError)):
      result = sparse_ops.map_values(mapping, sp, sp_incomp, kwarg='kwarg')
      self.evaluate(result)

    # check that shape mismatches are correctly detected
    sp_incomp = sparse_tensor.SparseTensor(sp.indices, sp.values, (25, 25))
    with self.assertRaises((errors.InvalidArgumentError, ValueError)):
      result = sparse_ops.map_values(mapping, sp, sp_incomp, kwarg='kwarg')
      self.evaluate(result)

  def testConstantStringToSparse(self):
    # Test case for GitHub issue 40633.
    tensor = constant_op.constant(list('ababa'))
    sparse = sparse_ops.from_dense(tensor)
    result = self.evaluate(sparse)
    self.assertAllEqual([[0], [1], [2], [3], [4]], result.indices)
    self.assertAllEqual([b'a', b'b', b'a', b'b', b'a'], result.values)
    self.assertAllEqual([5], result.dense_shape)

@test_util.run_all_in_graph_and_eager_modes
class RawOpsTest(test_util.TensorFlowTestCase, parameterized.TestCase):

  def testSparseFillEmptyRowsGrad(self):
    reverse_index_map = [2, 1]
    grad_values = [0, 1, 2, 3]
    d_values, d_default_value = self.evaluate(
        gen_sparse_ops.SparseFillEmptyRowsGrad(
            reverse_index_map=reverse_index_map, grad_values=grad_values))
    self.assertAllEqual([2, 1], d_values)
    self.assertEqual(3, d_default_value)

  def testSparseFillEmptyRowsGradNegativeIndexMapValue(self):
    reverse_index_map = [2, -1]
    grad_values = [0, 1, 2, 3]
    with self.assertRaisesRegex(
        errors.InvalidArgumentError,
        r'Elements in reverse index must be in \[0, 4\)'):
      self.evaluate(
          gen_sparse_ops.SparseFillEmptyRowsGrad(
              reverse_index_map=reverse_index_map, grad_values=grad_values))

  def testSparseFillEmptyRowsGradLargeIndexMapValue(self):
    reverse_index_map = [2, 10]
    grad_values = [0, 1, 2, 3]
    with self.assertRaisesRegex(
        errors.InvalidArgumentError,
        r'Elements in reverse index must be in \[0, 4\)'):
      self.evaluate(
          gen_sparse_ops.SparseFillEmptyRowsGrad(
              reverse_index_map=reverse_index_map, grad_values=grad_values))

  def testSparseFillEmptyRowsGradMatrix(self):
    reverse_index_map = [0, 1]
    grad_values = [[0, 1], [2, 3]]
    # Note: Eager mode and graph mode throw different errors here. Graph mode
    # will fail with a ValueError from the shape checking logic, while Eager
    # will fail with an InvalidArgumentError from the kernel itself.
    if context.executing_eagerly():
      with self.assertRaisesRegex(errors.InvalidArgumentError,
                                  r'grad_values must be a vector'):
        self.evaluate(
            gen_sparse_ops.SparseFillEmptyRowsGrad(
                reverse_index_map=reverse_index_map, grad_values=grad_values))
    else:
      with self.assertRaisesRegex(ValueError,
                                  r'Shape must be rank 1 but is rank 2'):
        self.evaluate(
            gen_sparse_ops.SparseFillEmptyRowsGrad(
                reverse_index_map=reverse_index_map, grad_values=grad_values))

  def testSparseConcatStaticShape(self):
    if context.executing_eagerly():
      self.skipTest('sparse_spaceholder is only available in graph context.')
    input_a = array_ops.sparse_placeholder(dtypes.float32, shape=(2, 1))
    input_b = array_ops.sparse_placeholder(dtypes.float32, shape=(2, 2))

    result = sparse_ops.sparse_concat_v2(axis=1, sp_inputs=[input_a, input_b])
    self.assertEqual(result.shape, [2, 3])

if __name__ == '__main__':
  googletest.main()


text:
require "tmpdir"

module Stevedore
  class CommandLineError < StandardError #:nodoc:
  end

  private

  def self.run(command, expected_outcodes = 0)
    output = `#{command}`
    unless [expected_outcodes].flatten.include?($?.exitstatus)
      raise CommandLineError, "Error while running #{command}"
    end
    output.force_encoding('UTF-8')
  end
end

require "stevedore/pdf"

redpajama_set_name: RedPajamaGithub


text:
class ThrownValue
  def initialize(name, value, ctx)
    @name = name
    @value = value
    @context = ctx
  end

  attr_reader :name
  attr_reader :value

  def message
    "A thrown value from Kernel#throw"
  end

  def backtrace
    if @context.kind_of? MethodContext
      @context = Backtrace.backtrace(@context)
    end

    return @context
  end

  def set_backtrace(obj)
    @context = obj
  end

  def exception(msg)
    true
  end

  def self.register(sym)
    cur = Thread.current[:__catches__]
    if cur.nil?
      cur = []
      Thread.current[:__catches__] = cur
    end

    cur << sym

    begin
      yield
    ensure
      cur.pop
    end
  end

  def self.available?(sym)
    cur = Thread.current[:__catches__]
    return false if cur.nil?
    cur.include? sym
  end
end

module Kernel
  def catch(sym)
    begin
      ThrownValue.register(sym) do
        yield
      end
    rescue ThrownValue => val
      return val.value if val.name == sym
      Rubinius.asm(val) do |v|
        v.bytecode(self)
        raise_exc
      end
    end
  end
  module_function :catch

  def throw(sym, value = nil)
    unless ThrownValue.available? sym
      raise NameError.new("uncaught throw `#{sym}'", sym.to_sym)
    end

    exc = ThrownValue.new(sym, value, MethodContext.current.sender)
    Rubinius.asm(exc) do |v|
      v.bytecode(self)
      raise_exc
    end
  end
  module_function :throw
end


text:
UdeS Node Orchestrator Boilerplate
==================================
![Node](https://img.shields.io/badge/node-6.10.1-brightgreen.svg)

## Introduction
This is a boilerplate for instantiating an orchestrator using the
`udes-node-orchestrator` library. It has a very minimalistic example.

## Prerequisites
* [Node](https://nodejs.org) 6.10.1 (it is recommended to install it via
[NVM](https://github.com/creationix/nvm))
* Ensure you have a development environment setup to use the orchestrator.
Since it uses a socket you cannot run it on a local machine.

## Getting started
### Setup development machine
1. `git clone git@github.com:UdeS-STI/udes-node-orchestrator`
2. `cd udes-node-orchestrator/boilerplate`
3. `npm install`
4. Update information in `config.js` to match used server configuration.

## Usage
* Start app
  * `npm start`
* Run eslint
  * `npm run lint`


text:
[![experimental](http://badges.github.io/stability-badges/dist/experimental.svg)](http://github.com/badges/stability-badges)

A command-line tool to find broken `require` and `import` paths in a source directory. For example, when you are requiring a file which has been moved or deleted.

For example, if you have a `src` folder with the following `indx.js`

```js
// points to a file that does not exist
const a = require('./some/broken/path.js')

// also looks for ES6 imports
import './another/broken/path.js'

// a valid file
import './does-exist.js'
```

Now, we can run the tool on our `src` directory:

```sh
list-broken-requires src
```

Output:

```sh
/path/to/src/index.js
  './some/broken/path.js'
  './another/broken/path.js'

Broken requires: 2
```

Example:

![image](http://i.imgur.com/EYebaDI.png)

## Install

```sh
npm install -g list-broken-requires
```

## Usage

#### CLI

```
Usage:
  list-broken-requires [dir]
```

Where `dir` defaults to the current working directory.

## See Also

- [dependency-check](https://www.npmjs.com/package/dependency-check)

## License

MIT, see [LICENSE.md](http://github.com/Jam3/list-broken-requires/blob/master/LICENSE.md) for details.


text:
<?xml version='1.0' encoding='UTF-8'?>
<settings xsi:schemaLocation='http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd'
          xmlns='http://maven.apache.org/SETTINGS/1.0.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>

    <servers>
        <server>
            <id>grayshirts-public</id>
            <username>${env.BINTRAY_USERNAME}</username>
            <password>${env.BINTRAY_PASSWORD}</password>
        </server>
    </servers>

    <profiles>
        <profile>
            <repositories>
                <repository>
                    <snapshots>
                        <enabled>false</enabled>
                    </snapshots>
                    <id>central</id>
                    <name>bintray</name>
                    <url>http://jcenter.bintray.com</url>
                </repository>
            </repositories>
            <pluginRepositories>
                <pluginRepository>
                    <snapshots>
                        <enabled>false</enabled>
                    </snapshots>
                    <id>central</id>
                    <name>bintray-plugins</name>
                    <url>http://jcenter.bintray.com</url>
                </pluginRepository>
            </pluginRepositories>
            <id>bintray</id>
        </profile>
    </profiles>
    <activeProfiles>
        <activeProfile>bintray</activeProfile>
    </activeProfiles>
</settings>


text:
import generateMetaTitle from './generateMetaTitle'
import generateMetaDescription from './generateMetaDescription'
import generateMetaImage from './generateMetaImage'

export default function generateMetaInfo (defaultMeta, post, options) {
  const opts = {
    lang: 'de',
    locale: 'de_CH',
    ...options
  }
  const title = generateMetaTitle(defaultMeta, post)
  const ogTitle = post && post.og_title && post.og_enabled ? post.og_title : title
  const description = generateMetaDescription(defaultMeta, post)
  const image = generateMetaImage(defaultMeta, post)
  const metaInfo = {
    title: title,
    htmlAttrs: {
      lang: opts.lang
    },
    meta: [
      { name: 'description', content: description },
      // { name: 'keywords', content: post.keywords },
      // { name: 'author', content: post.author },
      // canonical
      { property: 'og:locale', content: opts.locale },
      { property: 'og:site_name', content: defaultMeta.og_site_name },
      { property: 'og:type', content: 'website' },
      { property: 'og:title', content: ogTitle },
      { property: 'og:description', content: description },
      { name: 'twitter:title', content: ogTitle },
      { name: 'twitter:description', content: description },
      { name: 'twitter:card', content: 'summary_large_image' }
      // { name: 'twitter:site', content: '@publisher_handle' },
      // { name: 'twitter:creator', content: '@designathon15' },
    ]
  }

  if (image) {
    metaInfo.meta.push(
      { property: 'og:image', content: image },
      { name: 'twitter:image', content: image }
    )
  }

  return metaInfo
}


text: this.MentionedMessage = new Mongo.Collection('rocketchat_mentioned_message');


text:
/** @file GltfMaterial.h
 *  @brief glTF-specific material macros
 *  These will be made generic at some future date
 */

#ifndef AI_GLTFMATERIAL_H_INC
#define AI_GLTFMATERIAL_H_INC

#ifdef __GNUC__
#   pragma GCC system_header
#endif

#include <assimp/material.h>

#define AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE aiTextureType_UNKNOWN, 0
#define AI_MATKEY_GLTF_ALPHAMODE "$mat.gltf.alphaMode", 0, 0
#define AI_MATKEY_GLTF_ALPHACUTOFF "$mat.gltf.alphaCutoff", 0, 0

#define _AI_MATKEY_GLTF_MAPPINGNAME_BASE "$tex.mappingname"
#define _AI_MATKEY_GLTF_MAPPINGID_BASE "$tex.mappingid"
#define _AI_MATKEY_GLTF_MAPPINGFILTER_MAG_BASE "$tex.mappingfiltermag"
#define _AI_MATKEY_GLTF_MAPPINGFILTER_MIN_BASE "$tex.mappingfiltermin"
#define _AI_MATKEY_GLTF_SCALE_BASE "$tex.scale"
#define _AI_MATKEY_GLTF_STRENGTH_BASE "$tex.strength"

#define AI_MATKEY_GLTF_MAPPINGNAME(type, N) _AI_MATKEY_GLTF_MAPPINGNAME_BASE, type, N
#define AI_MATKEY_GLTF_MAPPINGID(type, N) _AI_MATKEY_GLTF_MAPPINGID_BASE, type, N
#define AI_MATKEY_GLTF_MAPPINGFILTER_MAG(type, N) _AI_MATKEY_GLTF_MAPPINGFILTER_MAG_BASE, type, N
#define AI_MATKEY_GLTF_MAPPINGFILTER_MIN(type, N) _AI_MATKEY_GLTF_MAPPINGFILTER_MIN_BASE, type, N
#define AI_MATKEY_GLTF_TEXTURE_SCALE(type, N) _AI_MATKEY_GLTF_SCALE_BASE, type, N
#define AI_MATKEY_GLTF_TEXTURE_STRENGTH(type, N) _AI_MATKEY_GLTF_STRENGTH_BASE, type, N

#endif


text:
/*
 * Extension.cpp
 *
 *  Created on: 2013/11/04
 *      Author: mugwort_rc
 */

#include "extensions/Extension.h"

#include <QStringList>

namespace  markdown {

Extension::Extension(const Config &config) :
    config(config)
{}

Extension::~Extension()
{}

QString Extension::getConfig(const QString &key, const QString &default_val) const
{
    if ( this->config.contains(key) ) {
        return this->config[key].at(0);
    }
    return default_val;
}

void Extension::setConfig(const QString &key, const QStringList &value)
{
    this->config[key] = value;
}

} // end of namespace markdown


text:
<img align="left" width="120" title="RSRL logo" src="https://github.com/tspooner/rsrl/raw/master/logo.png">

# RSRL ([api](https://docs.rs/rsrl/))

[![Crates.io](https://img.shields.io/crates/v/rsrl.svg)](https://crates.io/crates/rsrl)
[![Build Status](https://travis-ci.org/tspooner/rsrl.svg?branch=master)](https://travis-ci.org/tspooner/rsrl)
[![Coverage Status](https://coveralls.io/repos/github/tspooner/rsrl/badge.svg?branch=master)](https://coveralls.io/github/tspooner/rsrl?branch=master)

> Reinforcement learning should be _fast_, _safe_ and _easy to use_.

## Overview

``rsrl`` provides generic constructs for reinforcement learning (RL)
experiments in an extensible framework with efficient implementations of
existing methods for rapid prototyping.

## Installation

```toml
[dependencies]
rsrl = "0.8"
```

Note that `rsrl` enables the `blas` feature of its [`ndarray`] dependency, so
if you're building a binary, you additionally need to specify a BLAS backend
compatible with `ndarray`. For example, you can add these dependencies:

[`ndarray`]: https://crates.io/crates/ndarray

```toml
blas-src = { version = "0.2.0", default-features = false, features = ["openblas"] }
openblas-src = { version = "0.6.0", default-features = false, features = ["cblas", "system"] }
```

See `ndarray`'s [README](https://github.com/rust-ndarray/ndarray#how-to-use-with-cargo)
for more information.

## Usage
The code below shows how one could use `rsrl` to evaluate a QLearning agent
using a linear function approximator with Fourier basis projection to solve the
canonical mountain car problem.

> See [examples/](https://github.com/tspooner/rsrl/tree/master/rsrl/examples) for
> more...

```rust
let env = MountainCar::default();
let n_actions = env.action_space().card().into();

let mut rng = StdRng::seed_from_u64(0);
let (mut ql, policy) = {
    let basis = Fourier::from_space(5, env.state_space()).with_bias();
    let q_func = make_shared(LFA::vector(basis, SGD(0.001), n_actions));
    let policy = Greedy::new(q_func.clone());

    (QLearning {
        q_func,
        gamma: 0.9,
    }, policy)
};

for e in 0..200 {
    // Episode loop:
    let mut j = 0;
    let mut env = MountainCar::default();
    let mut action = policy.sample(&mut rng, env.emit().state());

    for i in 0.. {
        // Trajectory loop:
        j = i;

        let t = env.transition(action);

        ql.handle(&t).ok();
        action = policy.sample(&mut rng, t.to.state());

        if t.terminated() {
            break;
        }
    }

    println!("Batch {}: {} steps...", e + 1, j + 1);
}

let traj = MountainCar::default().rollout(|s| policy.mode(s), Some(500));

println!("OOS: {} states...", traj.n_states());
```

## Contributing
Pull requests are welcome. For major changes, please open an issue first to
discuss what you would like to change.

Please make sure to update tests as appropriate and adhere to the angularjs
commit message conventions (see
[here](https://gist.github.com/stephenparish/9941e89d80e2bc58a153)).

## License
[MIT](https://choosealicense.com/licenses/mit/)


text:
package utils

/**
  * Created by toidiu on 12/4/16.
  */
object StatusUtils {

  case class PostFileStatus(backend: String, success: Boolean)

}


text:
'use strict';

const Os = require('os');
const Nes = require('nes');

module.exports = { register };

function register (manager, options, callback) {
  const commander = new Commander(Object.assign(options, { manager }));

  manager.client.setCommander(commander);
  callback();
}

function Commander (options) {
  this._id = null;
  this._client = new Nes.Client(options.host);
  this._client.onError = options.manager.error;
}

Commander.prototype.connect = function connect (manager, callback) {
  const self = this;
  const client = self._client;

  if (client === null) {
    return callback(new Error('client not connected'));
  }

  client.connect({ auth: {} }, function connectCb (err) {
    if (err) {
      return callback(err);
    }

    // Don't hold the event loop open
    client._ws._socket.unref();
    client._heartbeat.unref();

    const commands = manager.list();
    const info = {
      pid: process.pid,
      argv: process.argv,
      version: process.version,
      hostname: Os.hostname()
    };

    function messageHandler (message) {
      manager.execute(message);
    }

    // Register with the server
    client.request({ path: 'register', payload: { commands, info } }, function registerCb (err, payload) {
      if (err) {
        return callback(err);
      }

      self._id = payload.clientId;

      // Subscribe to commands from the server
      client.subscribe('/command', messageHandler, callback);
    });
  });
};

Commander.prototype.respond = function respond (message, callback) {
  this._client.request({ path: 'respond', payload: message }, callback);
};


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Exercício 1 - JavaScript</title>

  <link rel="stylesheet" href="plugins/bootstrap-3.3.7-dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="plugins/bootstrap-3.3.7-dist/css/bootstrap-theme.min.css">

    <form class="form-horizontal" onsubmit="enviar(event)" role="form">
      <legend>Exercício 1 - JavaScript</legend>

        Nome:

          <input type="text" class="form-control" id="nome" name="nome">

        Sobrenome:

          <input type="text" class="form-control" name="sobrenome" id="sobrenome">

        Idade:

          <input type="number" class="form-control" name="idade" id="idade">

        <button class="btn btn-primary">Submit</button>
        <button type="button" class="btn btn-primary" onclick="enviar()">Clique</button>

    </form>


text:
// ==========================================================================
//  Author:   Jonathan Sandoe
//
//  Copyright (c) 2015 by The Concord Consortium, Inc. All rights reserved.
//
//  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.
// ==========================================================================

sc_require('models/data_item');

/** @class DataSet
 *
 * An indexed array of the DataItems in a DataContext.
 *
 *
 * DataItem attribute Values can be retrieved or modified by item index and
 * Attribute id.
 * Item indices, once assigned to a DataItem, are not reused.
 */
DG.DataSet = SC.Object.extend((function() // closure
/** @scope DG.DataSet.prototype */ {

  return {
    /**
     *  An array of data in the data set.
     * @type {[DG.DataItem]}
     */
    dataItems: null,

    /**
     * Attributes defined for this DataSet in the
     * order for the dataItems value array.
     *
     * @type {[DG.Attribute]}
     */
    attrs: null,

    /**
     * Order of registered collections. This ordering
     * is established by insertion and removal of collections. Collections are not moved,
     * but are created at a position relative to other groups.
     *
     * ToDo: make into a cacheable method that derives values from collection
     * ToDO: attributes.
     *
     * @type {[DG.Collection]}
     */
    collectionOrder: null,

    init: function () {
      this.dataItems = [];
      this.attrs = [];
      this.collectionOrder = [];
      this._clientToItemIndexMap = [];
    },

    /**
     * The rightmost collection.
     * @type {DG.Collection}
     */
    baseCollection: function () {
      var collections = this.get('collectionOrder');
      return collections[collections.length - 1];
    }.property('collectionOrder[]').cacheable(),

    /**
     * Inserts a group in the mapping before the existing group 'followerGroup'.
     * If no followerGroup, appends group.
     *
     * @param {DG.Collection} collection
     * @param {DG.Collection|null} followerCollection
     */
    registerCollection: function (collection, followerCollection) {
      if (followerCollection) {
        var insertLoc = this.collectionOrder.indexOf(followerCollection);
        if (insertLoc >= 0) {
          this.collectionOrder.insertAt(insertLoc, collection);
        } else {
          DG.logWarn('Inserting group, cannot find followerGroup');
          this.collectionOrder.push(collection);
        }
      } else {
        this.collectionOrder.push(collection);
      }
    },

    /**
     *
     * @param {DG.Collection} collection
     */
    unregisterCollection: function( collection) {
      var tIndex = this.collectionOrder.indexOf(collection);
      if( tIndex >= 0)
        this.collectionOrder.splice(tIndex, 1);
    },

    /**
     * Adds attributes. Ideally this is an initialization step, but may be called
     * at any time.
     *
     * TODO: consider making attribute resolution happen dynamically through
     * TODO: the collection list, and not through the mechanism here.
     *
     * @param {[DG.Attribute]|DG.Attribute} newAttributes An array or a single attribute.
     */
    addAttributes: function (newAttributes) {
      var attrs = Array.isArray(newAttributes)? newAttributes : [newAttributes];
      attrs.forEach(function (attr) {
        if (attr.constructor === DG.Attribute) {
          if (!this.attrs.contains(attr)) {
            this.attrs.push(attr);
          } else {
            DG.logWarn('Duplicate add of attribute.');
          }
        } else {
          DG.logWarn('Attempt to add non-attribute to Data Set for Context: ' +
              this.dataContextRecord.id);
        }
      }.bind(this));
    },

    hasAttribute: function( iAttr) {
      return this.attrs.contains( iAttr);
    },

    /**
     * Delete attribute from data set.
     *
     * Note we do not modify the underlying data set which is kept as a map from
     * attribute id. The orphan attribute data does not get saved nor restored.
     *
     * @param attr {DG.Attribute}
     */
    deleteAttribute: function (attr) {
      var ix = this.attrs.findIndex(function (a) {return a === attr;});
      if (ix >= 0) {
        this.attrs.splice(ix, 1);
      }
    },

    /**
     * Adds a dataItem provided as an array of values, a map of attribute keys to values,
     * or as a DG.DataItem.
     *
     * @param {DG.DataItem|{}|[*]} data  A data item, a map of attribute
     * keys to values, or an array of values indexed in attribute order.
     * @return {DG.DataItem} the item.
     */
    addDataItem: function (data, beforeItemID) {
      var dataItem;
      var ix;

      data = data || {};

      if (data.constructor === DG.DataItem) {
        dataItem = data;
        if (!dataItem.id) {
          dataItem.id = DG.DataUtilities.createUniqueID();
        }
      } else if (typeof data === 'object') {
        // the object may be just values or an object with id and values
        if (data.values && typeof data.values === 'object') {
          data.dataSet = this;
          if (!data.id) {
            data.id = DG.DataUtilities.createUniqueID();
          }
          data.values = DG.DataUtilities.canonicalizeAttributeValues(this.attrs, data.values);
          dataItem = DG.DataItem.create(data);
        } else {
          dataItem = DG.DataItem.create({
            id: DG.DataUtilities.createUniqueID(),
            dataSet: this,
            values: DG.DataUtilities.canonicalizeAttributeValues(this.attrs,
                data)
          });
        }
      }

      if (dataItem) {
        ix = this.dataItems.push(dataItem) - 1; // push returns new array length.
                                    // We want the index of the last element
        dataItem.itemIndex = ix;

        if (beforeItemID == null) {
          dataItem._clientIndex = this._clientToItemIndexMap.push(ix) - 1;
        }
        else {
          var beforeClientIndex = this.getDataItemClientIndexByID(beforeItemID);

          // give the new item its client index
          dataItem._clientIndex = beforeClientIndex;

          // update client indices for existing items being pushed back
          this._clientToItemIndexMap.forEach(function(itemIndex) {
                                                var item = this.dataItems[itemIndex];
                                                if (item._clientIndex >= beforeClientIndex)
                                                  ++ item._clientIndex;
                                              }.bind(this));
          // splice in the new client index
          this._clientToItemIndexMap.splice(beforeClientIndex, 0, ix);
        }
      }
      return  dataItem;
    },

    updateItem: function (iItemID, iValues) {
      var iItemValues = DG.DataUtilities.canonicalizeAttributeValues(this.get('attrs'), iValues);
      var iItem = this.getDataItemByID(iItemID);
      iItem.updateData(iItemValues);
      return iItem;
    },

    /**
     * Sorts the items by the specified attribute using the specified compare function.
     * @return {number[]} the original client index map (for use with undo, for instance)
     */
    sortItems: function(attributeID, accessFunc, valueCompareFunc) {
      var compareFunc = function(itemIndex1, itemIndex2) {
                          var item1 = this.dataItems[itemIndex1],
                              item2 = this.dataItems[itemIndex2],
                              value1 = accessFunc(item1.id, attributeID),
                              value2 = accessFunc(item2.id, attributeID),
                              result = valueCompareFunc(value1, value2);
                          return result || (item1._clientIndex - item2._clientIndex);
                        }.bind(this);
      // copy the array, sort the copy
      var clientIndexMap = this._clientToItemIndexMap.slice().sort(compareFunc);
      // install the new map
      return this.setClientIndexMap(clientIndexMap);
    },

    /**
     * Returns a copy of the current client index map.
     * @return {number[]} the original client index map (for use with undo, for instance)
     */
    getClientIndexMapCopy: function() {
      return this._clientToItemIndexMap.slice();
    },

    /**
     * Installs the specified client index map.
     * @return {number[]} the original client index map (for use with undo, for instance)
     */
    setClientIndexMap: function(clientIndexMap) {
      var originalMap = this._clientToItemIndexMap;
      clientIndexMap.forEach(function(itemIndex, clientIndex) {
                              this.dataItems[itemIndex]._clientIndex = clientIndex;
                            }.bind(this));
      this._clientToItemIndexMap = clientIndexMap;
      return originalMap;
    },

    /**
     * Marks an item for deletion.
     * @param {DG.DataItem} iItem
     * @param {boolean} iSetAside whether to delete or set aside
     * @return {DG.DataItem} the deleted item.
     */
    deleteDataItem: function (iItem, iSetAside) {
      if (iItem) {
        iItem.deleted = true;
        iItem.setAside = iSetAside;
      }
      return iItem;
    },

    /**
     * Marks an item for deletion.
     * @param {integer} iItemIndex
     * @param {boolean} iSetAside whether to delete or set aside
     * @return {DG.DataItem} the deleted item.
     */
    deleteDataItemByIndex: function (iItemIndex, iSetAside) {
      var index = this._clientToItemIndexMap[iItemIndex],
          item = this.getDataItem(index);
      return item ? this.deleteDataItem(item, iSetAside) : null;
    },

    /**
     * Undeletes a dataItem if possible. It may not be possible, as clean will remove
     * deleted items.
     * @param itemIndex
     * @return {[*]|undefined} the restored DataItem.
     */
    undeleteDataItem: function (itemIndex) {
      var index = this._clientToItemIndexMap[itemIndex],
          item;
      if (index >= 0 && index < this.dataItems.length) {
        item = this.dataItems[index];
        item.deleted = false;
      }
      return item;
    },

    restoreSetAsideItems: function () {
      var restoredItems = [];
      this.dataItems.forEach(function (item) {
        if (item.setAside) {
          restoredItems.push(item);
          item.deleted = false;
          item.setAside = false;
        }
      });
      return restoredItems;
    },

    getSetAsideCount: function () {
      var count = 0;
      this.dataItems.forEach(function (item) {
        if (item.setAside) { count++; }
      });
      return count;
    },

    /**
     * Permanently removes deleted dataItems and reclaims space.
     * @return {number} Count of dataItems retrieved.
     */
    cleanDeletedDataItems: function () {
      this.dataItems.forEach(function(item, ix) {
        if (item.deleted) {
          delete this.dataItems[ix];
        }
      }.bind(this));
    },

    /**
     * Retrieves or sets an attribute value for a DataItem.
     *
     * @param {integer} itemIndex a non-negative integer
     * @param {integer} attributeID a non-negative integer
     * @param {string|number} value a legal attribute value
     * @return {string|number} a legal attribute value
     */
    value: function(itemIndex, attributeID, value) {
      var index = this._clientToItemIndexMap[itemIndex],
          item, ret;
      if (index >= 0 && index < this.dataItems.length) {
        item = this.dataItems[index];
        if (item && !item.deleted) {
          if (value) {
            item.values[attributeID] = value;
          }
          ret = item.values[attributeID];
        }
      }
      return ret;
    },

    getDataItemCount: function() {
      return this.getDataItems().length;
    },

    getDataItems: function() {
      return this._clientToItemIndexMap
          .map(function(index) { return this.dataItems[index]; }.bind(this))
          .filter(function (item) {return !item.deleted;});
    },

    /**
     * Retrieves an existing DataItem by index.
     *
     * @param {integer} itemIndex
     * @return {DG.DataItem|undefined}
     */
    getDataItem: function (itemIndex) {
      var index = this._clientToItemIndexMap[itemIndex],
          item;
      if (index >= 0 && index < this.dataItems.length) {
        item = this.dataItems[index];
        if (!item.deleted) {
          return item;
        }
      }
    },

    /**
     * Retrieves a DataItem by its given ID.
     * @param {*} itemID
     * @returns {DG.DataItem|undefined}
     */
    getDataItemByID: function (itemID) {
      return this.dataItems.find(function(item) { return item.id === itemID; });
    },

    parseSearchQuery: function (queryString) {
      if (queryString === '*') {
        return {
          valid: true,
          op: '*'
        };
      }
      // for now this is a simple single expression of "left op right" where op is a comparison operator
      // this could be expanded (along with the testCaseAgainstQuery method below) using the shunting yard algorithm
      var matches = queryString.match(/([^=!<>]+)(==|!=|<=|<|>=|>)([^=!<>]+)/),
          trim = function (s) { return s.replace(/^\s+|\s+$/, ''); },
          parsedQuery = {
            valid: !!matches,
            left: matches && trim(matches[1]),
            op: matches && matches[2],
            right: matches && trim(matches[3])
          },
          attrs = this.attrs,
          parseOperand = function (value) {
            var numberValue = Number(value),
                parsedValue = value === 'true' ? true :
                    (value === 'false' ? false :
                    (isNaN(numberValue) ? value : numberValue));
            return {
              value: parsedValue,
              attr: attrs.find(function (attr) {return attr.name === value;}),
              name: value
            };
          };

      parsedQuery.left = parseOperand(parsedQuery.left);
      parsedQuery.right = parseOperand(parsedQuery.right);

      // valid queries must have at least one side with a defined attribute
      parsedQuery.valid = !!(parsedQuery.valid && (parsedQuery.left.attr || parsedQuery.right.attr));

      return parsedQuery;
    },

    testItemAgainstQuery: function (iItem, parsedQuery) {
      var getValue = function (token) {
            return token.attr ? iItem.getValue(token.attr.id) : token.value;
          },
          leftValue = parsedQuery.left && getValue(parsedQuery.left),
          rightValue = parsedQuery.right && getValue(parsedQuery.right);

      if (!parsedQuery.valid) {
        return false;
      }

      switch (parsedQuery.op) {
        case '*': return true;
// eslint-disable-next-line eqeqeq
        case '==': return leftValue == rightValue; // jshint ignore:line
// eslint-disable-next-line eqeqeq
        case '!=': return leftValue != rightValue; // jshint ignore:line
        case '<':  return leftValue <   rightValue;
        case '<=': return leftValue <=  rightValue;
        case '>=': return leftValue >=  rightValue;
        case '>':  return leftValue >   rightValue;
        default:   return false;
      }
    },

    getItemsBySearch: function (queryString) {
      var parsedQuery = this.parseSearchQuery(queryString);

      // return null to signal an invalid query
      if (!parsedQuery.valid) {
        return null;
      }

      return this.dataItems.filter(function (iItem) {

        return (!iItem.deleted) && this.testItemAgainstQuery(iItem, parsedQuery);
      }.bind(this));

    },

    /**
     * Retrieves the client index of the DataItem wth the specified ID.
     * @param {*} itemID
     * @returns {number}
     */
    getDataItemClientIndexByID: function (itemID) {
      return this._clientToItemIndexMap.findIndex(function(itemIndex) {
                                                    var item = this.dataItems[itemIndex];
                                                    return item && (item.id === itemID);
                                                  }.bind(this));
    },

    moveDataItemByID: function (itemID, order) {
      var clientIndex = this.getDataItemClientIndexByID(itemID);
      var itemIndex = this._clientToItemIndexMap[clientIndex];
      if ((clientIndex != null) && (order != null)) {
        var newIndexMap = this._clientToItemIndexMap.slice();
        newIndexMap.splice(clientIndex, 1);
        switch (order) {
          case 'first':
            newIndexMap.unshift(itemIndex);
            break;
          case 'last':
            newIndexMap.push(itemIndex);
            break;
          default:
            newIndexMap.splice(order, 0, itemIndex);
            break;
        }
        this.setClientIndexMap(newIndexMap);
      }
    },

    compareItemsByClientIndex: function(item1, item2) {
      return item1._clientIndex - item2._clientIndex;
    },

    /**
     * This method is called as a part of restoring a DataContext, to add
     * SetAside items to the DataSet.
     * @param itemSpecs
     */
    createSetAsideItems: function (itemSpecs) {
      itemSpecs.forEach(function (itemData) {
        var item = this.addDataItem(itemData);
        this.deleteDataItem(item, true);
      }.bind(this));
    },

    archiveSetAsideItems: function () {
      return this.dataItems.filter(function (item) {
          return item.setAside;
        }).map(function (item) {
          return {id: item.id, values: item.toArchive().values};
        });
      },
    /**
     * Returns a serializable version of this object.
     * @returns {{dataItems: [DG.DataItem]}}
     */
    toArchive: function () {
      return {
        dataItems: this.dataItems.filterProperty('deleted', false).map(function (item) {
          return {
            values: item.values,
            id: item.id,
            itemIndex: item.itemIndex
          };
        })
      };
    }

  };
})());


text:
package xfer

import (
	"bytes"
	"encoding/gob"
	"fmt"
	"sort"

	"github.com/davecgh/go-spew/spew"
	"github.com/mndrix/ps"
	"github.com/ugorji/go/codec"

	"$GITHUB_URI/test/reflect"
)

// PluginSpec is shared between the Probe, App, and UI. It is the plugin's
// self-proclaimed description.
type PluginSpec struct {
	ID string `json:"id"`

	// Label is a human-readable name of the plugin
	Label string `json:"label"`

	Description string `json:"description,omitempty"`

	// Interfaces is a list of things this plugin can be used for (e.g. "reporter")
	Interfaces []string `json:"interfaces"`

	APIVersion string `json:"api_version,omitempty"`

	Status string `json:"status,omitempty"`
}

// PluginSpecs is a set of plugin specs keyed on ID. Clients must use
// the Add method to add plugin specs
type PluginSpecs struct {
	psMap ps.Map
}

// EmptyPluginSpecs is the empty set of plugin specs.
var EmptyPluginSpecs = PluginSpecs{ps.NewMap()}

// MakePluginSpecs makes a new PluginSpecs with the given plugin specs.
func MakePluginSpecs(specs ...PluginSpec) PluginSpecs {
	return EmptyPluginSpecs.Add(specs...)
}

// Add adds the specs to the PluginSpecs. Add is the only valid way to grow a
// PluginSpecs. Add returns the PluginSpecs to enable chaining.
func (n PluginSpecs) Add(specs ...PluginSpec) PluginSpecs {
	result := n.psMap
	if result == nil {
		result = ps.NewMap()
	}
	for _, spec := range specs {
		result = result.Set(spec.ID, spec)
	}
	return PluginSpecs{result}
}

// Merge combines the two PluginSpecss and returns a new result.
func (n PluginSpecs) Merge(other PluginSpecs) PluginSpecs {
	nSize, otherSize := n.Size(), other.Size()
	if nSize == 0 {
		return other
	}
	if otherSize == 0 {
		return n
	}
	result, iter := n.psMap, other.psMap
	if nSize < otherSize {
		result, iter = iter, result
	}
	iter.ForEach(func(key string, otherVal interface{}) {
		result = result.Set(key, otherVal)
	})
	return PluginSpecs{result}
}

// Lookup the spec by 'key'
func (n PluginSpecs) Lookup(key string) (PluginSpec, bool) {
	if n.psMap != nil {
		value, ok := n.psMap.Lookup(key)
		if ok {
			return value.(PluginSpec), true
		}
	}
	return PluginSpec{}, false
}

// Keys is a list of all the keys in this set.
func (n PluginSpecs) Keys() []string {
	if n.psMap == nil {
		return nil
	}
	k := n.psMap.Keys()
	sort.Strings(k)
	return k
}

// Size is the number of specs in the set
func (n PluginSpecs) Size() int {
	if n.psMap == nil {
		return 0
	}
	return n.psMap.Size()
}

// ForEach executes f for each spec in the set. Nodes are traversed in sorted
// order.
func (n PluginSpecs) ForEach(f func(PluginSpec)) {
	for _, key := range n.Keys() {
		if val, ok := n.psMap.Lookup(key); ok {
			f(val.(PluginSpec))
		}
	}
}

// Copy is a noop
func (n PluginSpecs) Copy() PluginSpecs {
	return n
}

func (n PluginSpecs) String() string {
	keys := []string{}
	if n.psMap == nil {
		n = EmptyPluginSpecs
	}
	psMap := n.psMap
	if psMap == nil {
		psMap = ps.NewMap()
	}
	for _, k := range psMap.Keys() {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	buf := bytes.NewBufferString("{")
	for _, key := range keys {
		val, _ := psMap.Lookup(key)
		fmt.Fprintf(buf, "%s: %s, ", key, spew.Sdump(val))
	}
	fmt.Fprintf(buf, "}")
	return buf.String()
}

// DeepEqual tests equality with other PluginSpecss
func (n PluginSpecs) DeepEqual(i interface{}) bool {
	d, ok := i.(PluginSpecs)
	if !ok {
		return false
	}

	if n.Size() != d.Size() {
		return false
	}
	if n.Size() == 0 {
		return true
	}

	equal := true
	n.psMap.ForEach(func(k string, val interface{}) {
		if otherValue, ok := d.psMap.Lookup(k); !ok {
			equal = false
		} else {
			equal = equal && reflect.DeepEqual(val, otherValue)
		}
	})
	return equal
}

func (n PluginSpecs) toIntermediate() []PluginSpec {
	intermediate := make([]PluginSpec, 0, n.Size())
	n.ForEach(func(spec PluginSpec) {
		intermediate = append(intermediate, spec)
	})
	return intermediate
}

func (n PluginSpecs) fromIntermediate(specs []PluginSpec) PluginSpecs {
	return MakePluginSpecs(specs...)
}

// CodecEncodeSelf implements codec.Selfer
func (n *PluginSpecs) CodecEncodeSelf(encoder *codec.Encoder) {
	if n.psMap != nil {
		encoder.Encode(n.toIntermediate())
	} else {
		encoder.Encode(nil)
	}
}

// CodecDecodeSelf implements codec.Selfer
func (n *PluginSpecs) CodecDecodeSelf(decoder *codec.Decoder) {
	in := []PluginSpec{}
	if err := decoder.Decode(&in); err != nil {
		return
	}
	*n = PluginSpecs{}.fromIntermediate(in)
}

// MarshalJSON shouldn't be used, use CodecEncodeSelf instead
func (PluginSpecs) MarshalJSON() ([]byte, error) {
	panic("MarshalJSON shouldn't be used, use CodecEncodeSelf instead")
}

// UnmarshalJSON shouldn't be used, use CodecDecodeSelf instead
func (*PluginSpecs) UnmarshalJSON(b []byte) error {
	panic("UnmarshalJSON shouldn't be used, use CodecDecodeSelf instead")
}

// GobEncode implements gob.Marshaller
func (n PluginSpecs) GobEncode() ([]byte, error) {
	buf := bytes.Buffer{}
	err := gob.NewEncoder(&buf).Encode(n.toIntermediate())
	return buf.Bytes(), err
}

// GobDecode implements gob.Unmarshaller
func (n *PluginSpecs) GobDecode(input []byte) error {
	in := []PluginSpec{}
	if err := gob.NewDecoder(bytes.NewBuffer(input)).Decode(&in); err != nil {
		return err
	}
	*n = PluginSpecs{}.fromIntermediate(in)
	return nil
}

// PluginSpecsByID implements sort.Interface, so we can sort the specs by the
// ID field.
type PluginSpecsByID []PluginSpec

// Len is part of sort.Interface.
func (p PluginSpecsByID) Len() int {
	return len(p)
}

// Swap is part of sort.Interface.
func (p PluginSpecsByID) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

// Less is part of sort.Interface.
func (p PluginSpecsByID) Less(i, j int) bool {
	return p[i].ID < p[j].ID
}


text:
int main()
{
    {
    typedef std::multimap<int, double, transparent_less_private> M;

    TEST_IGNORE_NODISCARD M().lower_bound(C2Int{5});
    }
}
#endif


text:
class DeepFlowDllExport PassThrough : public Node {
public:
	PassThrough(deepflow::NodeParam *param);
	int minNumInputs() override { return 1; }
	int minNumOutputs() override { return 1; }
	std::string op_name() const override { return "pass_through"; }
	void init() override;
	void forward() override;
	void backward() override;
	std::string to_cpp() const override;
private:
	bool _stop_gradients = true;
};


text:
package edu.uw.apl.commons.tsk4j.filesys;

import java.io.InputStream;
import java.io.IOException;
import java.util.*;

import edu.uw.apl.commons.tsk4j.base.Utils;

public class MD5Test extends junit.framework.TestCase {

	public void test1() throws Exception {
		String path = "/dev/sda1";
		FileSystem fs = new FileSystem( path );
		walk( fs );
		fs.close();
	}

	private void walk( FileSystem fs ) throws Exception {
		MetaWalk.Callback cb = new MetaWalk.Callback() {
				public int apply( WalkFile f ) {
					if( true && false )
						return Walk.WALK_CONT;
					Meta m = f.meta();
					//					System.out.println( m.addr() + " " + m.size() );
					boolean includeSlackSpace = false;
					InputStream is = f.getInputStream( includeSlackSpace );
					try {
						String md5 = Utils.md5sum( is );
						is.close();
						System.out.println( m.addr() + " " + md5 );
						return Walk.WALK_CONT;
					} catch( IOException ioe ) {
						return Walk.WALK_STOP;
					}
				}
			};
		int flags = Meta.FLAG_ALLOC;
		fs.metaWalk( fs.rootINum(), fs.rootINum()+128, flags, cb );
	}
}

// eof


text:
require 'test_helper'
require 'generators/shopify_app/controllers/controllers_generator'

class ControllersGeneratorTest < Rails::Generators::TestCase
  tests ShopifyApp::Generators::ControllersGenerator
  destination File.expand_path("../tmp", File.dirname(__FILE__))
  setup :prepare_destination

  test "copies ShopifyApp controllers to the host application" do
    run_generator
    assert_directory "app/controllers"
    assert_file "app/controllers/sessions_controller.rb"
    assert_file "app/controllers/authenticated_controller.rb"
  end

end


text:
package feed

import (
	"context"

	"go-common/app/service/main/archive/model/archive"
	"go-common/library/log"
)

// ArchivesWithPlayer archives witch player
func (s *Service) ArchivesWithPlayer(c context.Context, aids []int64, qn int, platform string, fnver, fnval int) (res map[int64]*archive.ArchiveWithPlayer, err error) {
	if res, err = s.arc.ArchivesWithPlayer(c, aids, qn, platform, fnver, fnval); err != nil {
		log.Error("%+v", err)
	}
	if len(res) != 0 {
		return
	}
	am, err := s.arc.Archives(c, aids)
	if err != nil {
		return
	}
	if len(am) == 0 {
		return
	}
	res = make(map[int64]*archive.ArchiveWithPlayer, len(am))
	for aid, a := range am {
		res[aid] = &archive.ArchiveWithPlayer{Archive3: archive.BuildArchive3(a)}
	}
	return
}


text:
/* jshint undef: true, unused: true */
/* global define: false */
define(['jquery', 'domReady', 'modules/reveal', 'browser', 'velocity', 'inview', 'placeholder'], function($, domReady, Reveal, bowser){
	"use strict";

	var Component = {

		init: function () {
			this.bindUiActions();
		},

		bindUiActions: function () {
			if (bowser.msie || bowser.firefox) {
				$('html').addClass('no-parallax');
			}

			if (bowser.msie) {
				$('*').css('background-attachment', 'scroll');
			}

			domReady(function () {
				Reveal.init();
				Component.hidePreloader();
			});
		},
		hidePreloader: function () {
			$('.preloader-block').velocity({
				translateY: ['-100%', '0'],
				translateZ: '0'
			}, 1000, 'ease', function () {
				$(window).trigger('pageLoaded');
			});

			if ($('video.cover-el').length) {
				$('video.cover-el').trigger('play');

				$('.volume-toggle').click(function() {
					$(this).toggleClass('pe-7s-volume2 pe-7s-volume1');
					var v = $('video.cover-el');
					v.prop('muted', !v.prop('muted'));
				});
			}
		}
	};

	Component.init();
});


text:
import * as React from 'react';
import { UISchemaElement, VerticalLayout } from '@jsonforms/core';
import { JsonFormsStateProvider } from '@jsonforms/react';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import Enzyme, { mount, ReactWrapper } from 'enzyme';
import VerticalLayoutRenderer, { verticalLayoutTester } from '../../src/layouts/VerticalLayout';
import { initCore } from '../util';

Enzyme.configure({ adapter: new Adapter() });

test('tester', () => {
  expect(verticalLayoutTester(undefined, undefined)).toBe(-1);
  expect(verticalLayoutTester(null, undefined)).toBe(-1);
  expect(verticalLayoutTester({ type: 'Foo' }, undefined)).toBe(-1);
  expect(verticalLayoutTester({ type: 'VerticalLayout' }, undefined)).toBe(1);
});

describe('Vertical layout', () => {

  let wrapper: ReactWrapper;

  afterEach(() => wrapper.unmount());

  test('render with undefined elements', () => {
    const uischema: UISchemaElement = {
      type: 'VerticalLayout'
    };
    const core = initCore({}, uischema, {});
    wrapper = mount(
      <JsonFormsStateProvider initState={{ core }}>
        <VerticalLayoutRenderer uischema={uischema} />
      </JsonFormsStateProvider>
    );

    expect(wrapper.find('.vertical-layout')).toBeDefined();
  });

  test('render with null elements', () => {
    const uischema: VerticalLayout = {
      type: 'VerticalLayout',
      elements: null
    };
    const core = initCore({}, uischema, {});
    wrapper = mount(
      <JsonFormsStateProvider initState={{ core }}>
        <VerticalLayoutRenderer uischema={uischema} />
      </JsonFormsStateProvider>
    );

    expect(wrapper.find('.vertical-layout')).toBeDefined();
  });

  test('render with children', () => {
    const uischema: VerticalLayout = {
      type: 'VerticalLayout',
      elements: [{ type: 'Control' }, { type: 'Control' }]
    };
    const core = initCore({}, uischema, {});
    wrapper = mount(
      <JsonFormsStateProvider initState={{ core }}>
        <VerticalLayoutRenderer uischema={uischema} />
      </JsonFormsStateProvider>
    );
    const verticalLayout = wrapper.find('JsonFormsLayout').getDOMNode();

    expect(verticalLayout.tagName).toBe('DIV');
    expect(verticalLayout.children).toHaveLength(2);
  });

  test('hide', () => {
    const uischema: VerticalLayout = {
      type: 'VerticalLayout',
      elements: [{ type: 'Control' }],
    };
    const core = initCore({}, uischema, {});

    wrapper = mount(
      <JsonFormsStateProvider initState={{ core }}>
        <VerticalLayoutRenderer
          uischema={uischema}
          visible={false}
        />
      </JsonFormsStateProvider>
    );
    const verticalLayout = wrapper.find('JsonFormsLayout').getDOMNode() as HTMLDivElement;
    expect(verticalLayout.hidden).toBe(true);
  });

  test('show by default', () => {
    const uischema: VerticalLayout = {
      type: 'VerticalLayout',
      elements: [{ type: 'Control' }],
    };
    const core = initCore({}, uischema, {});

    wrapper = mount(
      <JsonFormsStateProvider initState={{ core }}>
        <VerticalLayoutRenderer uischema={uischema} />
      </JsonFormsStateProvider>
    );
    const verticalLayout = wrapper.find('JsonFormsLayout').getDOMNode() as HTMLDivElement;
    expect(verticalLayout.hidden).toBe(false);
  });
});


text:
package commands.EvalCommands;

import model.State;

/**
 * Use addArg(Arg a) once to add 1 argument to this command. doCommand() returns
 * Arg1 multiplied by negative 1
 */
public class Minus extends EvalCommand {

	public Minus(State state) {
		super(1, state, "Minus");
	}

	/**
	 * @return Arg1*(-1)
	 */
	public double doCommand() {
		return -1 * myArgs.get(0).getDoubleArg();
	}
}


text:
			<img src="<?php echo base_url() ?>external/img/upcoming.jpg" alt="" class="img_fondo_secciones">

						<img src="<?php echo base_url() ?>external/img/icon4.jpg" alt="" class="img-responsive" style="margin: 0 auto;padding: 2em 0;">

Lorem Ipsum Dolor

						Consectetur adipiscing elit

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum voluptatem quis temporibus, earum, unde molestias optio eveniet magnam. Nihil magnam cum, nostrum natus, labore illum voluptas consequatur magni deserunt. Sint.

						<img src="<?php echo base_url() ?>external/img/events.jpg" alt="" class="img-responsive">

Lorem Ipsum Dolor

						Consectetur adipiscing elit

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam id elit consequat felis sagittis pulvinar sit amet at diam. Donec sodales nec augue eu gravida. Integer bibendum enim sit amet varius maximus. Vestibulum sapien ex, varius nec bibendum a, eleifend sit amet odio.

SPEAKERS

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nam id elit consequat felis sagittis pulvinar sit amet at diam.

							<img class="img-circle" src="<?php echo base_url() ?>external/img/avatar2.jpg" alt="" style="height: 200px;">

Claudia Sepúlveda Astengo

							COMM & Marketing

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam id elit consequat felis sagittis pulvinar sit amet at diam.

					<button type="button" class="btn btn-primary btn-lg">Find Out More</button>

							<img class="img-responsive" src="<?php echo base_url() ?>external/img/events_1.jpg" alt="" style="width: 100%;">

LAUNCH EVENT

							<img class="img-responsive" src="<?php echo base_url() ?>external/img/events_2.jpg" alt="" style="width: 100%;">

2014 XMAS PARTY

							<img class="img-responsive" src="<?php echo base_url() ?>external/img/events_3.jpg" alt="" style="width: 100%;">

BNE POLO HOUSE

					<button type="button" class="btn btn-primary btn-lg">Find Out More</button>


text:
package com.assist.dg.androidassist.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.assist.dg.androidassist.R;
import com.assist.dg.androidassist.model.AssistData;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Spencer Do on 2015. 10. 28..
 */
public abstract class ListAdapter<T extends AssistData> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

  public ListAdapter(OnItemClickListener<T> l) {
    setClickListener(l);
  }

  public interface OnItemClickListener<T> {
    void onClickItem(T c);
  }

  private List<T> items = new ArrayList<>();
  private OnItemClickListener listener;

  public void setData(List<T> data) {
    this.items = data;
    notifyDataSetChanged();
  }

  public List<T> getItems() {
    return items;
  }

  public void setClickListener(OnItemClickListener l) {
    listener = l;
  }

  protected OnItemClickListener getListener() {
    return listener;
  }

  public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    TextView view = (TextView) LayoutInflater.from(parent.getContext())
        .inflate(R.layout.row_college, parent, false);
    return new ListItemTextHolder(view);
  }

  @Override public abstract void onBindViewHolder(RecyclerView.ViewHolder holder, final int position);

  @Override public int getItemCount() {
    return items.size();
  }

  public static class ListItemTextHolder extends RecyclerView.ViewHolder {

    private View base;

    public ListItemTextHolder(View itemView) {
      super(itemView);
      base = itemView;
    }

    public TextView getTitle() {
      return (TextView) base;
    }
  }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <link href='//fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="css/main.css">
  <title>AJAX with JavaScript</title>

Bring on the AJAX

            <button id="load" onclick="sendAJAX()">Bring it!</button>


text:
package net.sourceforge.pebble.web.action;

import net.sourceforge.pebble.web.view.RedirectView;

/**
 * Tests for the LoginAction class.
 *
 * @author    Simon Brown
 */
public class LoginActionTest extends SingleBlogActionTestCase {

  protected void setUp() throws Exception {
    action = new LoginAction();

    super.setUp();
  }

  public void testUserRedirectedToBlogHomePage() throws Exception {
    request.setParameter("redirectUrl", blog.getUrl());
    RedirectView view = (RedirectView)action.process(request, response);
    assertEquals(blog.getUrl(), view.getUri());
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
  <application>GCLOUD_PROJECT_ID_HERE</application>
  <service>std-java8</service>
  <version>1</version>
  <runtime>java8</runtime>
  <threadsafe>true</threadsafe>
  <instance-class>B8</instance-class>
  <manual-scaling>
    <instances>1</instances>
  </manual-scaling>
  <url-stream-handler>native</url-stream-handler>
  <system-properties>
    <property name="GOOGLE_CLOUD_PROJECT" value="GCLOUD_PROJECT_ID_HERE"/>
  </system-properties>
</appengine-web-app>


text:
import Data.List

factors :: (Integral a) => a -> [a]
factors x = filter (\ y -> x `mod` y == 0) [1 .. limit]
  where limit = ceiling $ sqrt $ fromIntegral x

isPrime x = isNothing $ find (> 1) (factors x)

primeFactors x = filter isPrime $ factors x

main = print $ last $ primeFactors 600851475143


text:
/******************************************************************

Revision history:

2010/04/20 (Sean Reifschneider)
  - Use basename(sys.argv[0]) for the default "ident".
  - Arguments to openlog() are now keyword args and are all optional.
  - syslog() calls openlog() if it hasn't already been called.

1998/04/28 (Sean Reifschneider)
  - When facility not specified to syslog() method, use default from openlog()
    (This is how it was claimed to work in the documentation)
  - Potential resource leak of o_ident, now cleaned up in closelog()
  - Minor comment accuracy fix.

95/06/29 (Steve Clift)
  - Changed arg parsing to use PyArg_ParseTuple.
  - Added PyErr_Clear() call(s) where needed.
  - Fix core dumps if user message contains format specifiers.
  - Change openlog arg defaults to match normal syslog behavior.
  - Plug memory leak in openlog().
  - Fix setlogmask() to return previous mask value.

******************************************************************/

/* syslog module */

#include "Python.h"
#include "osdefs.h"

#include <syslog.h>

/*  only one instance, only one syslog, so globals should be ok  */
static PyObject *S_ident_o = NULL;                      /*  identifier, held by openlog()  */
static char S_log_open = 0;

static PyObject *
syslog_get_argv(void)
{
    /* Figure out what to use for as the program "ident" for openlog().
     * This swallows exceptions and continues rather than failing out,
     * because the syslog module can still be used because openlog(3)
     * is optional.
     */

    Py_ssize_t argv_len;
    PyObject *scriptobj;
    char *atslash;
    PyObject *argv = PySys_GetObject("argv");

    if (argv == NULL) {
        return(NULL);
    }

    argv_len = PyList_Size(argv);
    if (argv_len == -1) {
        PyErr_Clear();
        return(NULL);
    }
    if (argv_len == 0) {
        return(NULL);
    }

    scriptobj = PyList_GetItem(argv, 0);
    if (!PyString_Check(scriptobj)) {
        return(NULL);
    }
    if (PyString_GET_SIZE(scriptobj) == 0) {
        return(NULL);
    }

    atslash = strrchr(PyString_AsString(scriptobj), SEP);
    if (atslash) {
        return(PyString_FromString(atslash + 1));
    } else {
        Py_INCREF(scriptobj);
        return(scriptobj);
    }

    return(NULL);
}

static PyObject *
syslog_openlog(PyObject * self, PyObject * args, PyObject *kwds)
{
    long logopt = 0;
    long facility = LOG_USER;
    PyObject *new_S_ident_o = NULL;
    static char *keywords[] = {"ident", "logoption", "facility", 0};

    if (!PyArg_ParseTupleAndKeywords(args, kwds,
                          "|Sll:openlog", keywords, &new_S_ident_o, &logopt, &facility))
        return NULL;

    if (new_S_ident_o) { Py_INCREF(new_S_ident_o); }

    /*  get sys.argv[0] or NULL if we can't for some reason  */
    if (!new_S_ident_o) {
        new_S_ident_o = syslog_get_argv();
        }

    Py_XDECREF(S_ident_o);
    S_ident_o = new_S_ident_o;

    /* At this point, S_ident_o should be INCREF()ed.  openlog(3) does not
     * make a copy, and syslog(3) later uses it.  We can't garbagecollect it
     * If NULL, just let openlog figure it out (probably using C argv[0]).
     */

    openlog(S_ident_o ? PyString_AsString(S_ident_o) : NULL, logopt, facility);
    S_log_open = 1;

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
syslog_syslog(PyObject * self, PyObject * args)
{
    char *message;
    int   priority = LOG_INFO;

    if (!PyArg_ParseTuple(args, "is;[priority,] message string",
                          &priority, &message)) {
        PyErr_Clear();
        if (!PyArg_ParseTuple(args, "s;[priority,] message string",
                              &message))
            return NULL;
    }

    /*  if log is not opened, open it now  */
    if (!S_log_open) {
        PyObject *openargs;

        /* Continue even if PyTuple_New fails, because openlog(3) is optional.
         * So, we can still do loggin in the unlikely event things are so hosed
         * that we can't do this tuple.
         */
        if ((openargs = PyTuple_New(0))) {
            PyObject *openlog_ret = syslog_openlog(self, openargs, NULL);
            Py_XDECREF(openlog_ret);
            Py_DECREF(openargs);
        }
    }

    Py_BEGIN_ALLOW_THREADS;
    syslog(priority, "%s", message);
    Py_END_ALLOW_THREADS;
    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
syslog_closelog(PyObject *self, PyObject *unused)
{
    if (S_log_open) {
        closelog();
        Py_XDECREF(S_ident_o);
        S_ident_o = NULL;
        S_log_open = 0;
    }
    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
syslog_setlogmask(PyObject *self, PyObject *args)
{
    long maskpri, omaskpri;

    if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri))
        return NULL;
    omaskpri = setlogmask(maskpri);
    return PyInt_FromLong(omaskpri);
}

static PyObject *
syslog_log_mask(PyObject *self, PyObject *args)
{
    long mask;
    long pri;
    if (!PyArg_ParseTuple(args, "l:LOG_MASK", &pri))
        return NULL;
    mask = LOG_MASK(pri);
    return PyInt_FromLong(mask);
}

static PyObject *
syslog_log_upto(PyObject *self, PyObject *args)
{
    long mask;
    long pri;
    if (!PyArg_ParseTuple(args, "l:LOG_UPTO", &pri))
        return NULL;
    mask = LOG_UPTO(pri);
    return PyInt_FromLong(mask);
}

/* List of functions defined in the module */

static PyMethodDef syslog_methods[] = {
    {"openlog",         (PyCFunction) syslog_openlog,           METH_VARARGS | METH_KEYWORDS},
    {"closelog",        syslog_closelog,        METH_NOARGS},
    {"syslog",          syslog_syslog,          METH_VARARGS},
    {"setlogmask",      syslog_setlogmask,      METH_VARARGS},
    {"LOG_MASK",        syslog_log_mask,        METH_VARARGS},
    {"LOG_UPTO",        syslog_log_upto,        METH_VARARGS},
    {NULL,              NULL,                   0}
};

/* Initialization function for the module */

PyMODINIT_FUNC
initsyslog(void)
{
    PyObject *m;

    /* Create the module and add the functions */
    m = Py_InitModule("syslog", syslog_methods);
    if (m == NULL)
        return;

    /* Add some symbolic constants to the module */

    /* Priorities */
    PyModule_AddIntConstant(m, "LOG_EMERG",       LOG_EMERG);
    PyModule_AddIntConstant(m, "LOG_ALERT",       LOG_ALERT);
    PyModule_AddIntConstant(m, "LOG_CRIT",        LOG_CRIT);
    PyModule_AddIntConstant(m, "LOG_ERR",         LOG_ERR);
    PyModule_AddIntConstant(m, "LOG_WARNING", LOG_WARNING);
    PyModule_AddIntConstant(m, "LOG_NOTICE",  LOG_NOTICE);
    PyModule_AddIntConstant(m, "LOG_INFO",        LOG_INFO);
    PyModule_AddIntConstant(m, "LOG_DEBUG",       LOG_DEBUG);

    /* openlog() option flags */
    PyModule_AddIntConstant(m, "LOG_PID",         LOG_PID);
    PyModule_AddIntConstant(m, "LOG_CONS",        LOG_CONS);
    PyModule_AddIntConstant(m, "LOG_NDELAY",  LOG_NDELAY);
#ifdef LOG_NOWAIT
    PyModule_AddIntConstant(m, "LOG_NOWAIT",  LOG_NOWAIT);
#endif
#ifdef LOG_PERROR
    PyModule_AddIntConstant(m, "LOG_PERROR",  LOG_PERROR);
#endif

    /* Facilities */
    PyModule_AddIntConstant(m, "LOG_KERN",        LOG_KERN);
    PyModule_AddIntConstant(m, "LOG_USER",        LOG_USER);
    PyModule_AddIntConstant(m, "LOG_MAIL",        LOG_MAIL);
    PyModule_AddIntConstant(m, "LOG_DAEMON",  LOG_DAEMON);
    PyModule_AddIntConstant(m, "LOG_AUTH",        LOG_AUTH);
    PyModule_AddIntConstant(m, "LOG_LPR",         LOG_LPR);
    PyModule_AddIntConstant(m, "LOG_LOCAL0",  LOG_LOCAL0);
    PyModule_AddIntConstant(m, "LOG_LOCAL1",  LOG_LOCAL1);
    PyModule_AddIntConstant(m, "LOG_LOCAL2",  LOG_LOCAL2);
    PyModule_AddIntConstant(m, "LOG_LOCAL3",  LOG_LOCAL3);
    PyModule_AddIntConstant(m, "LOG_LOCAL4",  LOG_LOCAL4);
    PyModule_AddIntConstant(m, "LOG_LOCAL5",  LOG_LOCAL5);
    PyModule_AddIntConstant(m, "LOG_LOCAL6",  LOG_LOCAL6);
    PyModule_AddIntConstant(m, "LOG_LOCAL7",  LOG_LOCAL7);

#ifndef LOG_SYSLOG
#define LOG_SYSLOG              LOG_DAEMON
#endif
#ifndef LOG_NEWS
#define LOG_NEWS                LOG_MAIL
#endif
#ifndef LOG_UUCP
#define LOG_UUCP                LOG_MAIL
#endif
#ifndef LOG_CRON
#define LOG_CRON                LOG_DAEMON
#endif

    PyModule_AddIntConstant(m, "LOG_SYSLOG",  LOG_SYSLOG);
    PyModule_AddIntConstant(m, "LOG_CRON",        LOG_CRON);
    PyModule_AddIntConstant(m, "LOG_UUCP",        LOG_UUCP);
    PyModule_AddIntConstant(m, "LOG_NEWS",        LOG_NEWS);
}


text:
package edu.sampleu.travel.options;

import edu.sampleu.travel.dataobject.TravelDestination;
import org.kuali.rice.core.api.criteria.QueryByCriteria;
import org.kuali.rice.core.api.criteria.QueryResults;
import org.kuali.rice.core.api.util.ConcreteKeyValue;
import org.kuali.rice.core.api.util.KeyValue;
import org.kuali.rice.krad.keyvalues.KeyValuesBase;
import org.kuali.rice.krad.service.KRADServiceLocator;

import java.util.ArrayList;
import java.util.List;

/**
 * This class provides a simple key values for travel destinations
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class TravelDestinationKeyValues extends KeyValuesBase {

    private static final long serialVersionUID = 1L;

    @Override
    public List<KeyValue> getKeyValues() {
        List<KeyValue> keyValues = new ArrayList<KeyValue>();

        QueryResults<TravelDestination> bos = KRADServiceLocator.getDataObjectService().findMatching(
                TravelDestination.class, QueryByCriteria.Builder.create().build());

        keyValues.add(new ConcreteKeyValue("", ""));
        for (TravelDestination typ : bos.getResults()) {
            keyValues.add(new ConcreteKeyValue(typ.getTravelDestinationId(), typ.getTravelDestinationName()));
        }

        return keyValues;
    }

}


text:
> :warning: **Deprecated**: This is not maintained any more, and references old versions of Java and Tomcat.

Basic [Docker](https://www.docker.com/) image to run [Apache Tomcat](http://tomcat.apache.org/).
This is based on [Alpine Linux](http://alpinelinux.org/) to keep the size minimal.

* Tomcat is installed in `/opt/tomcat`.
* It listens on port 8080.
* A user **admin** is configured, with access to the _manager_ and _host-manager_ apps.
You should remove it, or at least change its password, if you want to use this image in production.
* Documentation and examples have been removed.

### Tags

* `tomcat9-java8` or `9` or `latest`: Tomcat 9 on Oracle Java 8
* `tomcat8-java8` or `8` or `8.5`: Tomcat 8.5 on Oracle Java 8
* `tomcat7-java8` or `7`: Tomcat 7 on Oracle Java 8

Tomcat 6 and 8.0 are no longer supported, so the corresponding tags should no longer be used.

Please note that Java 7 is unsupported by Oracle, as of April 2015, so the following tags
use Java version 7u80, which has know security issues, and should not be used on a publicly accessible website:

* `tomcat8-java7`: Tomcat 8 on Oracle Java 7
* `tomcat7-java7`: Tomcat 7 on Oracle Java 7

Additionally, tags are created for each tomcat release (e.g. `8.0.24` or `8.0.24-java8`).

Note that the `7` tag used to reference `tomcat7-java7`. It now references `tomcat7-java8`
due to the end of support for java 7.

### Usage

Example:

    docker run -d -p 8080:8080 jeanblanchard/tomcat:9


text:
@import "normalize.css";
@import "basscss-grid";
@import "csskit";
@import "highlight.js/styles/tomorrow.css";
@import "./variables";
@import "./typography.css";
@import "./header.css";
@import "./footer.css";
@import "./lists.css";
@import "./forms.css";
@import "./layout.css";
@import "./sidebar.css";
@import "./post.css";
@import "./content.css";
@import "./contributor.css";


text:
import React from 'react';
import { shallow, mount } from 'enzyme';
import toJson from 'enzyme-to-json';
import SignOutButton from '../SignOutButton';

describe('<SignOutButton />', () => {
  it('should render correctly', () => {
    let wrapper = shallow(<SignOutButton/>);
    expect(toJson(wrapper)).toMatchSnapshot();
  });

  it('should fire signOutUser when clicked', () => {
     global.taskata = () => {};
     global.taskata.signOutUser = jest.fn();

     let wrapper = mount(<SignOutButton />);

     wrapper.find('button').simulate('click');
     expect(global.taskata.signOutUser).toHaveBeenCalled();
  });
});


text:
package com.amazonaws.services.ec2.model.transform;

import java.util.ArrayList;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * AnalysisPacketHeader StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AnalysisPacketHeaderStaxUnmarshaller implements Unmarshaller<AnalysisPacketHeader, StaxUnmarshallerContext> {

    public AnalysisPacketHeader unmarshall(StaxUnmarshallerContext context) throws Exception {
        AnalysisPacketHeader analysisPacketHeader = new AnalysisPacketHeader();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return analysisPacketHeader;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("destinationAddressSet", targetDepth)) {
                    analysisPacketHeader.withDestinationAddresses(new ArrayList<String>());
                    continue;
                }

                if (context.testExpression("destinationAddressSet/item", targetDepth)) {
                    analysisPacketHeader.withDestinationAddresses(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("destinationPortRangeSet", targetDepth)) {
                    analysisPacketHeader.withDestinationPortRanges(new ArrayList<PortRange>());
                    continue;
                }

                if (context.testExpression("destinationPortRangeSet/item", targetDepth)) {
                    analysisPacketHeader.withDestinationPortRanges(PortRangeStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("protocol", targetDepth)) {
                    analysisPacketHeader.setProtocol(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("sourceAddressSet", targetDepth)) {
                    analysisPacketHeader.withSourceAddresses(new ArrayList<String>());
                    continue;
                }

                if (context.testExpression("sourceAddressSet/item", targetDepth)) {
                    analysisPacketHeader.withSourceAddresses(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("sourcePortRangeSet", targetDepth)) {
                    analysisPacketHeader.withSourcePortRanges(new ArrayList<PortRange>());
                    continue;
                }

                if (context.testExpression("sourcePortRangeSet/item", targetDepth)) {
                    analysisPacketHeader.withSourcePortRanges(PortRangeStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return analysisPacketHeader;
                }
            }
        }
    }

    private static AnalysisPacketHeaderStaxUnmarshaller instance;

    public static AnalysisPacketHeaderStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new AnalysisPacketHeaderStaxUnmarshaller();
        return instance;
    }
}


text:
<?php

class Dotdigitalgroup_Email_Model_Adminhtml_Source_Addressbookspref
{

    protected function getWebsite()
    {
        $website      = Mage::app()->getWebsite();
        $websiteParam = Mage::app()->getRequest()->getParam('website');
        if ($websiteParam) {
            $website = Mage::app()->getWebsite($websiteParam);
        }

        return $website;
    }

    /**
     * get address books
     *
     * @return null
     */
    protected function getAddressBooks()
    {
        $website = $this->getWebsite();
        $client  = Mage::getModel('ddg_automation/apiconnector_client');
        $client->setApiUsername(Mage::helper('ddg')->getApiUsername($website))
            ->setApiPassword(Mage::helper('ddg')->getApiPassword($website));

        $savedAddressBooks = Mage::registry('addressbooks');
        //get saved address books from registry
        if ($savedAddressBooks) {
            $addressBooks = $savedAddressBooks;
        } else {
            // api all address books
            $addressBooks = $client->getAddressBooks();
            Mage::register('addressbooks', $addressBooks);
        }

        return $addressBooks;
    }

    /**
     * addressbook options
     *
     * @return array
     * @throws Mage_Core_Exception
     */
    public function toOptionArray()
    {
        $fields  = array();
        $website = $this->getWebsite();

        $enabled = Mage::helper('ddg')->isEnabled($website);

        //get address books options
        if ($enabled) {
            $addressBooks = $this->getAddressBooks();
            //set the error message to the select option
            if (isset($addressBooks->message)) {
                $fields[] = array('value' => 0,
                                  'label' => Mage::helper('ddg')->__(
                                      $addressBooks->message
                                  ));
            }

            $subscriberAddressBook = Mage::helper('ddg')
                ->getSubscriberAddressBook(Mage::app()->getWebsite());

            //set up fields with book id and label
            if ($addressBooks) {
                foreach ($addressBooks as $book) {
                    if (isset($book->id) && $book->visibility == 'Public'
                        && $book->id != $subscriberAddressBook
                    ) {
                        $fields[] = array('value' => $book->id,
                                          'label' => $book->name);
                    }
                }
            }
        }

        return $fields;
    }
}


text:
namespace chromeos {
namespace input_method {

namespace {

class TestableComponentExtensionIMEManager
    : public ComponentExtensionIMEManager {
 public:
  using ComponentExtensionIMEManager::GetComponentExtensionIMEId;
};

class ComponentExtensionIMEManagerTest :
    public testing::Test,
    public ComponentExtensionIMEManager::Observer {
 public:
  ComponentExtensionIMEManagerTest()
      : mock_delegate_(NULL),
        on_initialized_callcount_(0) {
  }

  virtual void SetUp() {
    ime_list_.clear();

    ComponentExtensionIME ext1;
    ext1.id = "ext1_id";
    ext1.description = "ext1_description";
    ext1.options_page_url =
        GURL("chrome-extension://" + ext1.id + "/options.html");
    ext1.path = base::FilePath("ext1_file_path");

    ComponentExtensionEngine ext1_engine1;
    ext1_engine1.engine_id = "ext1_engine1_engine_id";
    ext1_engine1.display_name = "ext1_engine_1_display_name";
    ext1_engine1.language_code = "en";
    ext1_engine1.layouts.push_back("us");
    ext1.engines.push_back(ext1_engine1);

    ComponentExtensionEngine ext1_engine2;
    ext1_engine2.engine_id = "ext1_engine2_engine_id";
    ext1_engine2.display_name = "ext1_engine2_display_name";
    ext1_engine2.language_code = "en";
    ext1_engine2.layouts.push_back("us");
    ext1.engines.push_back(ext1_engine2);

    ComponentExtensionEngine ext1_engine3;
    ext1_engine3.engine_id = "ext1_engine3_engine_id";
    ext1_engine3.display_name = "ext1_engine3_display_name";
    ext1_engine3.language_code = "ja";
    ext1_engine3.layouts.push_back("us");
    ext1.engines.push_back(ext1_engine3);

    ime_list_.push_back(ext1);

    ComponentExtensionIME ext2;
    ext2.id = "ext2_id";
    ext2.description = "ext2_description";
    ext2.path = base::FilePath("ext2_file_path");

    ComponentExtensionEngine ext2_engine1;
    ext2_engine1.engine_id = "ext2_engine1_engine_id";
    ext2_engine1.display_name = "ext2_engine_1_display_name";
    ext2_engine1.language_code = "en";
    ext2_engine1.layouts.push_back("us");
    ext2.engines.push_back(ext2_engine1);

    ComponentExtensionEngine ext2_engine2;
    ext2_engine2.engine_id = "ext2_engine2_engine_id";
    ext2_engine2.display_name = "ext2_engine2_display_name";
    ext2_engine2.language_code = "hi";
    ext2_engine2.layouts.push_back("us");
    ext2.engines.push_back(ext2_engine2);

    ComponentExtensionEngine ext2_engine3;
    ext2_engine3.engine_id = "ext2_engine3_engine_id";
    ext2_engine3.display_name = "ext2_engine3_display_name";
    ext2_engine3.language_code = "ja";
    ext2_engine3.layouts.push_back("jp");
    ext2.engines.push_back(ext2_engine3);

    ime_list_.push_back(ext2);

    ComponentExtensionIME ext3;
    ext3.id = "ext3_id";
    ext3.description = "ext3_description";
    ext1.options_page_url =
        GURL("chrome-extension://" + ext3.id + "/options.html");
    ext3.path = base::FilePath("ext3_file_path");

    ComponentExtensionEngine ext3_engine1;
    ext3_engine1.engine_id = "ext3_engine1_engine_id";
    ext3_engine1.display_name = "ext3_engine_1_display_name";
    ext3_engine1.language_code = "hi";
    ext3_engine1.layouts.push_back("us");
    ext3.engines.push_back(ext3_engine1);

    ComponentExtensionEngine ext3_engine2;
    ext3_engine2.engine_id = "ext3_engine2_engine_id";
    ext3_engine2.display_name = "ext3_engine2_display_name";
    ext3_engine2.language_code = "en";
    ext3_engine2.layouts.push_back("us");
    ext3.engines.push_back(ext3_engine2);

    ComponentExtensionEngine ext3_engine3;
    ext3_engine3.engine_id = "ext3_engine3_engine_id";
    ext3_engine3.display_name = "ext3_engine3_display_name";
    ext3_engine3.language_code = "en";
    ext3_engine3.layouts.push_back("us");
    ext3.engines.push_back(ext3_engine3);

    ime_list_.push_back(ext3);

    mock_delegate_ = new MockComponentExtIMEManagerDelegate();
    mock_delegate_->set_ime_list(ime_list_);
    component_ext_mgr_.reset(new ComponentExtensionIMEManager());
    component_ext_mgr_->AddObserver(this);
    EXPECT_FALSE(component_ext_mgr_->IsInitialized());
    component_ext_mgr_->Initialize(
        scoped_ptr<ComponentExtensionIMEManagerDelegate>(
            mock_delegate_).Pass());
    EXPECT_TRUE(component_ext_mgr_->IsInitialized());

  }

  virtual void TearDown() {
    EXPECT_EQ(1, on_initialized_callcount_);
    component_ext_mgr_->RemoveObserver(this);
  }

 protected:
  MockComponentExtIMEManagerDelegate* mock_delegate_;
  scoped_ptr<ComponentExtensionIMEManager> component_ext_mgr_;
  std::vector<ComponentExtensionIME> ime_list_;

 private:
  virtual void OnInitialized() OVERRIDE {
    ++on_initialized_callcount_;
  }

  int on_initialized_callcount_;

  DISALLOW_COPY_AND_ASSIGN(ComponentExtensionIMEManagerTest);
};

TEST_F(ComponentExtensionIMEManagerTest, LoadComponentExtensionIMETest) {
  for (size_t i = 0; i < ime_list_.size(); ++i) {
    for (size_t j = 0; j < ime_list_[i].engines.size(); ++j) {
      const std::string input_method_id =
          TestableComponentExtensionIMEManager::GetComponentExtensionIMEId(
              ime_list_[i].id,
              ime_list_[i].engines[j].engine_id);
      component_ext_mgr_->LoadComponentExtensionIME(input_method_id);
      EXPECT_EQ(ime_list_[i].id, mock_delegate_->last_loaded_extension_id());
    }
  }
  EXPECT_EQ(9, mock_delegate_->load_call_count());
}

TEST_F(ComponentExtensionIMEManagerTest, UnloadComponentExtensionIMETest) {
  for (size_t i = 0; i < ime_list_.size(); ++i) {
    for (size_t j = 0; j < ime_list_[i].engines.size(); ++j) {
      const std::string input_method_id =
          TestableComponentExtensionIMEManager::GetComponentExtensionIMEId(
              ime_list_[i].id,
              ime_list_[i].engines[j].engine_id);
      component_ext_mgr_->UnloadComponentExtensionIME(input_method_id);
      EXPECT_EQ(ime_list_[i].id, mock_delegate_->last_unloaded_extension_id());
    }
  }
  EXPECT_EQ(9, mock_delegate_->unload_call_count());
}

TEST_F(ComponentExtensionIMEManagerTest, IsWhitelistedTest) {
  EXPECT_TRUE(component_ext_mgr_->IsWhitelisted(
      TestableComponentExtensionIMEManager::GetComponentExtensionIMEId(
          ime_list_[0].id,
          ime_list_[0].engines[0].engine_id)));
  EXPECT_FALSE(component_ext_mgr_->IsWhitelisted(
      extension_ime_util::GetInputMethodID(
          ime_list_[0].id,
          ime_list_[0].engines[0].engine_id)));
  EXPECT_FALSE(component_ext_mgr_->IsWhitelisted("mozc"));
  EXPECT_FALSE(component_ext_mgr_->IsWhitelisted(
      extension_ime_util::GetInputMethodID("AAAA", "012345")));
  EXPECT_FALSE(component_ext_mgr_->IsWhitelisted(
      TestableComponentExtensionIMEManager::GetComponentExtensionIMEId(
          "AAAA", "012345")));
}

TEST_F(ComponentExtensionIMEManagerTest, IsWhitelistedExtensionTest) {
  EXPECT_TRUE(component_ext_mgr_->IsWhitelistedExtension(ime_list_[0].id));
  EXPECT_TRUE(component_ext_mgr_->IsWhitelistedExtension(ime_list_[1].id));
  EXPECT_FALSE(component_ext_mgr_->IsWhitelistedExtension("dummy"));
  EXPECT_FALSE(component_ext_mgr_->IsWhitelistedExtension(""));
}

TEST_F(ComponentExtensionIMEManagerTest, GetNameDescriptionTest) {
  for (size_t i = 0; i < ime_list_.size(); ++i) {
    for (size_t j = 0; j < ime_list_[i].engines.size(); ++j) {
      const ComponentExtensionEngine& engine
          = ime_list_[i].engines[j];

      const std::string input_method_id =
          TestableComponentExtensionIMEManager::GetComponentExtensionIMEId(
              ime_list_[i].id,
              engine.engine_id);

      EXPECT_EQ(input_method_id,
                component_ext_mgr_->GetId(ime_list_[i].id, engine.engine_id));
      EXPECT_EQ(engine.display_name,
                component_ext_mgr_->GetName(input_method_id));
      EXPECT_EQ(engine.description,
                component_ext_mgr_->GetDescription(input_method_id));
    }
  }
}

TEST_F(ComponentExtensionIMEManagerTest, ListIMEByLanguageTest) {
  const std::string hindi_layout1 =
      TestableComponentExtensionIMEManager::GetComponentExtensionIMEId(
          ime_list_[1].id, ime_list_[1].engines[1].engine_id);
  const std::string hindi_layout2 =
      TestableComponentExtensionIMEManager::GetComponentExtensionIMEId(
          ime_list_[2].id, ime_list_[2].engines[0].engine_id);

  std::vector<std::string> hindi_list
      = component_ext_mgr_->ListIMEByLanguage("hi");
  ASSERT_EQ(2UL, hindi_list.size());
  EXPECT_TRUE(hindi_list[0] == hindi_layout1 || hindi_list[0] == hindi_layout2);
  EXPECT_TRUE(hindi_list[1] == hindi_layout1 || hindi_list[1] == hindi_layout2);

  EXPECT_EQ(0UL, component_ext_mgr_->ListIMEByLanguage("ru").size());
  EXPECT_EQ(0UL, component_ext_mgr_->ListIMEByLanguage("").size());
  EXPECT_EQ(0UL, component_ext_mgr_->ListIMEByLanguage("invalid").size());
  EXPECT_EQ(5UL, component_ext_mgr_->ListIMEByLanguage("en").size());
  EXPECT_EQ(2UL, component_ext_mgr_->ListIMEByLanguage("ja").size());
}

TEST_F(ComponentExtensionIMEManagerTest, GetAllIMEAsInputMethodDescriptor) {
  input_method::InputMethodDescriptors descriptors =
      component_ext_mgr_->GetAllIMEAsInputMethodDescriptor();
  size_t total_ime_size = 0;
  for (size_t i = 0; i < ime_list_.size(); ++i) {
    total_ime_size += ime_list_[i].engines.size();
  }
  EXPECT_EQ(total_ime_size, descriptors.size());
}

}  // namespace

}  // namespace input_method
}  // namespace chromeos


text:
const path = require('path')

const { coalesce } = require('extant')

const descendant = require('foremost')('descendant')

const Registrator = require('./registrator')

const Monitor = require('./monitor')

const cluster = require('cluster')

const assert = require('assert')

const noop = require('nop')

class Listener {
    constructor (destructible, configuration) {
        this._destructible = destructible
        this._destructible.destruct(() => this.destroyed = true)
        this.destroyed = false

        this._registrator = {}

        descendant.increment()
        destructible.promise.then(() => descendant.decrement(), noop)

        descendant.on('olio:registered', this._register.bind(this))
        descendant.on('olio:ready', this._ready.bind(this))

        this._constituents = {}

        this._process = process
        this._process.env.OLIO_SUPERVISOR_PROCESS_ID = process.pid
    }

    socket (header, socket) {
        const message = {
            module: 'olio',
            method: 'connect',
            program: header.program,
            to: header.to,
            from: header.from
        }
        require('assert')(message.program.name)
        const path = this._constituents[message.to.name].paths[message.to.index]
        descendant.down(path, 'olio:operate', message, socket)
    }

    _created (count, name, properties, pids) {
        this._constituents[name] = {
            count: count,
            registered: 0,
            ready: 0,
            properties: properties,
            pids: pids,
            paths: []
        }
    }

    _register (message) {
        assert(message.from != null, 'is null ' + JSON.stringify(message.from))
        const process = message.cookie.process, program = message.cookie.program
        this._constituents[process.name].paths[process.index] = message.from
        this._registrator[program.name][program.index].register(process.name, process.index, message.from)
    }

    send (address, message, socket) {
        descendant.down(address, 'olio:operate', message, coalesce(socket))
    }

    get ready () {
        return (async () => {
            for (const program in this._registrator) {
                for (const registrator of this._registrator[program]) {
                    for (const name in registrator.constituents) {
                        await registrator.created.get(name)
                    }
                }
            }
            return true
        })()
    }

    _ready (message) {
        const process = message.cookie.process, program = message.cookie.program
        this._registrator[program.name][program.index].ready(process.name)
    }

    _spawn (destructible, name, config) {
        // TODO Set Node.js arguments.
        const executable = path.join(__dirname, 'constituent.js')
        cluster.setupMaster({ exec: executable, args: [] })
        const workers = coalesce(config.workers, 1)
        const pids = []
        for (let index = 0; index < workers; index++) {
            const worker = cluster.fork({ OLIO_WORKER_INDEX: index })
            descendant.addChild(worker.process, {
                program: { name: 'program', index: 0 },
                process: { name, index }
            })
            const pid = worker.process.pid
            destructible.destruct(descendant.down.bind(descendant, [ pid ], 'olio:shutdown', true))
            pids.push(pid)
            destructible.durable(`process.${index}`, Monitor(this, worker.process, { name, index }))
        }
        this._created(workers, name, config.properties, pids)
    }

    spawn (configuration) {
        this._registrator.program = [ new Registrator(this, { name: 'program', index: 0 }, configuration) ]

        for (const name in configuration.constituents) {
            this._spawn(this._destructible.durable(`constituent.${name}`), name, configuration.constituents[name])
        }
    }
}

module.exports = Listener


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn.history;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.project.DumbAwareToggleAction;
import com.intellij.openapi.vcs.changes.committed.ChangeListFilteringStrategy;
import com.intellij.openapi.vcs.changes.committed.DecoratorManager;
import icons.SvnIcons;
import org.jetbrains.idea.svn.SvnBundle;

/**
* @author Konstantin Kolosovsky.
*/
public class ShowHideMergePanelAction extends DumbAwareToggleAction {

  private final DecoratorManager myManager;
  private final ChangeListFilteringStrategy myStrategy;
  private boolean myIsSelected;

  public ShowHideMergePanelAction(final DecoratorManager manager, final ChangeListFilteringStrategy strategy) {
    myManager = manager;
    myStrategy = strategy;
  }

  @Override
  public void update(final AnActionEvent e) {
    super.update(e);
    final Presentation presentation = e.getPresentation();
    presentation.setIcon(SvnIcons.ShowIntegratedFrom);
    presentation.setText(SvnBundle.message("committed.changes.action.enable.merge.highlighting"));
    presentation.setDescription(SvnBundle.message("committed.changes.action.enable.merge.highlighting.description.text"));
  }

  public boolean isSelected(final AnActionEvent e) {
    return myIsSelected;
  }

  public void setSelected(final AnActionEvent e, final boolean state) {
    myIsSelected = state;
    if (state) {
      myManager.setFilteringStrategy(myStrategy);
    } else {
      myManager.removeFilteringStrategy(myStrategy.getKey());
    }
  }
}


text:
RimWorld mod for Spartyon7

Before: Wood floors give 0 beauty. Smooth stone floors give 3 beauty. Smoothing requires 1200 work.

After: Smoothing takes 400 work. Wood and stone floors now have 3 levels: rough, smooth and polished. Smoothing a floow improves beauty by 1. Wood ranges from 0 to 2 beauty and stone ranges from -1 to 1 beauty.

##Changelog:

###1.2:
* Changed the way things are done behind the scenes
* Created textures for smooth and polished wood

###1.1:
* Changed everything!
* Added polished stone
* Added smooth and polished wood
* Created textures for smooth and polished stone

###1.0:
* threw it together in 2 hours
* things seem to work
* changed beauty values of rough stone, smooth stone and wood planks