text:
from markdown import markdown
from keras_autodoc import autogen
from keras_autodoc import get_methods
import pytest
import sys
import pathlib
from typing import Union, Optional, Tuple
from .dummy_package import dummy_module
from . import dummy_package

test_doc1 = {
    "doc": """Base class for recurrent layers.

# Arguments
    cell: A RNN cell instance. A RNN cell is a class that has:
        - a `call(input_at_t, states_at_t)` method, returning
            `(output_at_t, states_at_t_plus_1)`. The call method of the
            cell can also take the optional argument `constants`, see
            section "Note on passing external constants" below.
        - a `state_size` attribute. This can be a single integer
            (single state) in which case it is
            the size of the recurrent state
            (which should be the same as the size of the cell output).
            This can also be a list/tuple of integers
            (one size per state). In this case, the first entry
            (`state_size[0]`) should be the same as
            the size of the cell output.
        It is also possible for `cell` to be a list of RNN cell instances,
        in which cases the cells get stacked on after the other in the RNN,
        implementing an efficient stacked RNN.
    return_sequences: Boolean. Whether to return the last output
        in the output sequence, or the full sequence.
    return_state: Boolean. Whether to return the last state
        in addition to the output.
    go_backwards: Boolean (default False).
        If True, process the input sequence backwards and return the
        reversed sequence.
    stateful: Boolean (default False). If True, the last state
        for each sample at index i in a batch will be used as initial
        state for the sample of index i in the following batch.
    unroll: Boolean (default False).
        If True, the network will be unrolled,
        else a symbolic loop will be used.
        Unrolling can speed-up a RNN,
        although it tends to be more memory-intensive.
        Unrolling is only suitable for short sequences.
    input_dim: dimensionality of the input (integer).
        This argument (or alternatively,
        the keyword argument `input_shape`)
        is required when using this layer as the first layer in a model.
    input_length: Length of input sequences, to be specified
        when it is constant.
        This argument is required if you are going to connect
        `Flatten` then `Dense` layers upstream
        (without it, the shape of the dense outputs cannot be computed).
        Note that if the recurrent layer is not the first layer
        in your model, you would need to specify the input length
        at the level of the first layer
        (e.g. via the `input_shape` argument)

# Input shape
    3D tensor with shape `(batch_size, timesteps, input_dim)`.

# Output shape
    - if `return_state`: a list of tensors. The first tensor is
        the output. The remaining tensors are the last states,
        each with shape `(batch_size, units)`.
    - if `return_sequences`: 3D tensor with shape
        `(batch_size, timesteps, units)`.
    - else, 2D tensor with shape `(batch_size, units)`.

# Masking
    This layer supports masking for input data with a variable number
    of timesteps. To introduce masks to your data,
    use an [Embedding](embeddings.md) layer with the `mask_zero` parameter
    set to `True`.

# Note on using statefulness in RNNs
    You can set RNN layers to be 'stateful', which means that the states
    computed for the samples in one batch will be reused as initial states
    for the samples in the next batch. This assumes a one-to-one mapping
    between samples in different successive batches.

    To enable statefulness:
    - specify `stateful=True` in the layer constructor.
    - specify a fixed batch size for your model, by passing
        if sequential model:
          `batch_input_shape=(...)` to the first layer in your model.
        else for functional model with 1 or more Input layers:
          `batch_shape=(...)` to all the first layers in your model.
        This is the expected shape of your inputs
        *including the batch size*.
        It should be a tuple of integers, e.g. `(32, 10, 100)`.
    - specify `shuffle=False` when calling fit().

    To reset the states of your model, call `.reset_states()` on either
    a specific layer, or on your entire model.

# Note on specifying the initial state of RNNs

Note that
One: You can specify the initial state of RNN layers symbolically by
    calling them with the keyword argument `initial_state`.
Two: The value of `initial_state` should be a tensor or list of
    tensors representing
    the initial state of the RNN layer.
You can specify the initial state of RNN layers numerically by:
One: calling `reset_states`
    - With the keyword argument `states`.
        - The value of
    `states` should be a numpy array or
    list of numpy arrays representing
the initial state of the RNN layer.

# Note on passing external constants to RNNs
    You can pass "external" constants to the cell using the `constants`
    keyword: argument of `RNN.__call__` (as well as `RNN.call`) method.
    This: requires that the `cell.call` method accepts the same keyword argument
    `constants`. Such constants can be used to condition the cell
    transformation on additional static inputs (not changing over time),
    a.k.a. an attention mechanism.

# Examples

```python
# First, let's define a RNN Cell, as a layer subclass.

class MinimalRNNCell(keras.layers.Layer):

    def __init__(self, units, **kwargs):
        self.units = units
        self.state_size = units
        super(MinimalRNNCell, self).__init__(**kwargs)

    def build(self, input_shape):
        self.kernel = self.add_weight(shape=(input_shape[-1], self.units),
                                      initializer='uniform',
                                      name='kernel')
        self.recurrent_kernel = self.add_weight(
            shape=(self.units, self.units),
            initializer='uniform',
            name='recurrent_kernel')
        self.built = True

    def call(self, inputs, states):
        prev_output = states[0]
        h = K.dot(inputs, self.kernel)
        output = h + K.dot(prev_output, self.recurrent_kernel)
        return output, [output]

# Let's use this cell in a RNN layer:

cell = MinimalRNNCell(32)
x = keras.Input((None, 5))
layer = RNN(cell)
y = layer(x)

# Here's how to use the cell to build a stacked RNN:

cells = [MinimalRNNCell(32), MinimalRNNCell(64)]
x = keras.Input((None, 5))
layer = RNN(cells)
y = layer(x)
```
""",
    "result": """Base class for recurrent layers.

__Arguments__

- __cell__: A RNN cell instance. A RNN cell is a class that has:
    - a `call(input_at_t, states_at_t)` method, returning
        `(output_at_t, states_at_t_plus_1)`. The call method of the
        cell can also take the optional argument `constants`, see
        section "Note on passing external constants" below.
    - a `state_size` attribute. This can be a single integer
        (single state) in which case it is
        the size of the recurrent state
        (which should be the same as the size of the cell output).
        This can also be a list/tuple of integers
        (one size per state). In this case, the first entry
        (`state_size[0]`) should be the same as
        the size of the cell output.
    It is also possible for `cell` to be a list of RNN cell instances,
    in which cases the cells get stacked on after the other in the RNN,
    implementing an efficient stacked RNN.
- __return_sequences__: Boolean. Whether to return the last output
    in the output sequence, or the full sequence.
- __return_state__: Boolean. Whether to return the last state
    in addition to the output.
- __go_backwards__: Boolean (default False).
    If True, process the input sequence backwards and return the
    reversed sequence.
- __stateful__: Boolean (default False). If True, the last state
    for each sample at index i in a batch will be used as initial
    state for the sample of index i in the following batch.
- __unroll__: Boolean (default False).
    If True, the network will be unrolled,
    else a symbolic loop will be used.
    Unrolling can speed-up a RNN,
    although it tends to be more memory-intensive.
    Unrolling is only suitable for short sequences.
- __input_dim__: dimensionality of the input (integer).
    This argument (or alternatively,
    the keyword argument `input_shape`)
    is required when using this layer as the first layer in a model.
- __input_length__: Length of input sequences, to be specified
    when it is constant.
    This argument is required if you are going to connect
    `Flatten` then `Dense` layers upstream
    (without it, the shape of the dense outputs cannot be computed).
    Note that if the recurrent layer is not the first layer
    in your model, you would need to specify the input length
    at the level of the first layer
    (e.g. via the `input_shape` argument)

__Input shape__

3D tensor with shape `(batch_size, timesteps, input_dim)`.

__Output shape__

- if `return_state`: a list of tensors. The first tensor is
    the output. The remaining tensors are the last states,
    each with shape `(batch_size, units)`.
- if `return_sequences`: 3D tensor with shape
    `(batch_size, timesteps, units)`.
- else, 2D tensor with shape `(batch_size, units)`.

__Masking__

This layer supports masking for input data with a variable number
of timesteps. To introduce masks to your data,
use an [Embedding](embeddings.md) layer with the `mask_zero` parameter
set to `True`.

__Note on using statefulness in RNNs__

You can set RNN layers to be 'stateful', which means that the states
computed for the samples in one batch will be reused as initial states
for the samples in the next batch. This assumes a one-to-one mapping
between samples in different successive batches.

To enable statefulness:
- specify `stateful=True` in the layer constructor.
- specify a fixed batch size for your model, by passing
    if sequential model:
      `batch_input_shape=(...)` to the first layer in your model.
    else for functional model with 1 or more Input layers:
      `batch_shape=(...)` to all the first layers in your model.
    This is the expected shape of your inputs
    *including the batch size*.
    It should be a tuple of integers, e.g. `(32, 10, 100)`.
- specify `shuffle=False` when calling fit().

To reset the states of your model, call `.reset_states()` on either
a specific layer, or on your entire model.

__Note on specifying the initial state of RNNs__

Note that
One: You can specify the initial state of RNN layers symbolically by
    calling them with the keyword argument `initial_state`.
Two: The value of `initial_state` should be a tensor or list of
    tensors representing
    the initial state of the RNN layer.
You can specify the initial state of RNN layers numerically by:
One: calling `reset_states`
    - With the keyword argument `states`.
        - The value of
    `states` should be a numpy array or
    list of numpy arrays representing
the initial state of the RNN layer.

__Note on passing external constants to RNNs__

You can pass "external" constants to the cell using the `constants`
keyword: argument of `RNN.__call__` (as well as `RNN.call`) method.
This: requires that the `cell.call` method accepts the same keyword argument
`constants`. Such constants can be used to condition the cell
transformation on additional static inputs (not changing over time),
a.k.a. an attention mechanism.

__Examples__

```python
# First, let's define a RNN Cell, as a layer subclass.

class MinimalRNNCell(keras.layers.Layer):

    def __init__(self, units, **kwargs):
        self.units = units
        self.state_size = units
        super(MinimalRNNCell, self).__init__(**kwargs)

    def build(self, input_shape):
        self.kernel = self.add_weight(shape=(input_shape[-1], self.units),
                                      initializer='uniform',
                                      name='kernel')
        self.recurrent_kernel = self.add_weight(
            shape=(self.units, self.units),
            initializer='uniform',
            name='recurrent_kernel')
        self.built = True

    def call(self, inputs, states):
        prev_output = states[0]
        h = K.dot(inputs, self.kernel)
        output = h + K.dot(prev_output, self.recurrent_kernel)
        return output, [output]

# Let's use this cell in a RNN layer:

cell = MinimalRNNCell(32)
x = keras.Input((None, 5))
layer = RNN(cell)
y = layer(x)

# Here's how to use the cell to build a stacked RNN:

cells = [MinimalRNNCell(32), MinimalRNNCell(64)]
x = keras.Input((None, 5))
layer = RNN(cells)
y = layer(x)
```
""",
}

test_doc_with_arguments_as_last_block = {
    "doc": """Base class for recurrent layers.

# Arguments
    return_sequences: Boolean. Whether to return the last output
        in the output sequence, or the full sequence.
    return_state: Boolean. Whether to return the last state
        in addition to the output.
""",
    "result": """Base class for recurrent layers.

__Arguments__

- __return_sequences__: Boolean. Whether to return the last output
    in the output sequence, or the full sequence.
- __return_state__: Boolean. Whether to return the last state
    in addition to the output.
""",
}

@pytest.mark.parametrize(
    "docs_descriptor", [test_doc_with_arguments_as_last_block, test_doc1]
)
def test_doc_lists(docs_descriptor):
    docstring = autogen.process_docstring(docs_descriptor["doc"])
    assert markdown(docstring) == markdown(docs_descriptor["result"])

dummy_docstring = """Multiplies 2 tensors (and/or variables) and returns a *tensor*.

When attempting to multiply a nD tensor
with a nD tensor, it reproduces the Theano behavior.
(e.g. `(2, 3) * (4, 3, 5) -> (2, 4, 5)`)

# Examples
```python
# Theano-like behavior example
>>> x = K.random_uniform_variable(shape=(2, 3), low=0, high=1)
>>> y = K.ones((4, 3, 5))
>>> xy = K.dot(x, y)
>>> K.int_shape(xy)
(2, 4, 5)
```

# Numpy implementation
```python
def dot(x, y):
    return dot(x, y)
```
    """

def test_doc_multiple_sections_code():
    """ Checks that we can have code blocks in multiple sections."""
    generated = autogen.process_docstring(dummy_docstring)
    assert "# Theano-like behavior example" in generated
    assert "def dot(x, y):" in generated

def check_against_expected(elements):
    doc_generator = autogen.DocumentationGenerator(
        project_url='www.dummy.com/my_project'
    )
    markdown_text = ''
    for element in elements:
        markdown_text += doc_generator._render(element)

    current_file_path = pathlib.Path(__file__).resolve()
    expected_file = current_file_path.parent / 'dummy_package' / 'expected.md'
    expected_text = expected_file.read_text()
    # we check that the generated html is the same
    # to ignore blank lines or other differences not relevant.
    assert markdown(markdown_text) == markdown(expected_text)

def test_generate_markdown():
    elements = [dummy_module.Dense, dummy_module.ImageDataGenerator]
    elements += get_methods(dummy_module.ImageDataGenerator)
    elements.append(dummy_module.to_categorical)
    check_against_expected(elements)

def test_generate_markdown_from_string():
    elements = [
        'tests.dummy_package.dummy_module.Dense',
        'tests.dummy_package.dummy_module.ImageDataGenerator',
        'tests.dummy_package.dummy_module.ImageDataGenerator.flow',
        'tests.dummy_package.dummy_module.ImageDataGenerator.flow_from_directory',
        'tests.dummy_package.dummy_module.to_categorical'
    ]
    check_against_expected(elements)

@pytest.mark.parametrize('element', [
    'tests.dummy_package.DataGenerator',
    'tests.dummy_package.to_categorical'
])
def test_aliases_class_function(element):
    doc_generator = autogen.DocumentationGenerator()
    computed = doc_generator._render(element)
    expected = element + '('
    assert expected in computed

@pytest.mark.parametrize(['element', 'expected'], [
    ('tests.dummy_package.DataGenerator.flow', '\nDataGenerator.flow('),
    ('tests.dummy_package.DataGenerator.flow_from_directory',
     '\nDataGenerator.flow_from_directory('),
])
def test_aliases_methods(element, expected):
    doc_generator = autogen.DocumentationGenerator()
    computed = doc_generator._render(element)
    assert expected in computed

expected_dodo = """ dodo

```python
tests.dummy_package.dummy_module2.dodo(x)
```

Some dodo

----

"""

@pytest.mark.parametrize("titles_size", ["###", "##"])
def test_aliases_in_hints(titles_size):
    pages = {'dod.md': ['tests.dummy_package.DataGenerator',
                        'tests.dummy_package.dummy_module2.dodo']}
    doc_generator = autogen.DocumentationGenerator(pages=pages, titles_size=titles_size)
    result = doc_generator._render('tests.dummy_package.dummy_module2.dodo')
    assert result == titles_size + expected_dodo

class A:
    def dodo(self):
        """Some docstring."""
        pass

class B(A):
    def dodo(self):
        pass

def test_get_docstring_of_super_class():
    computed = autogen.DocumentationGenerator()._render(B.dodo)
    assert 'Some docstring' in computed

def water_plant(
    self, amount: Union[int, float], fertilizer_type: Optional[str] = None
):
    """Give your plant some water.

    # Arguments
        amount: How much water to give.
        fertilizer_type: What kind of fertilizer to add.
    """

    pass

def test_types_in_docstring():
    result = autogen.DocumentationGenerator()._render(water_plant)

    assert "water_plant(self, amount, fertilizer_type=None)" in result
    assert "- __amount__ `Union[int, float]`: How much" in result
    assert "- __fertilizer_type__ `Optional[str]`: What" in result

def hard_method(self, arg: Union[int, Tuple[int, int]], arg2: int = 0) -> int:
    """Can we parse this?

    # Arguments
        arg: One or two integers.
        arg2: One integer.
    """
    pass

def test_hard_method():
    generated = autogen.DocumentationGenerator()._render(hard_method)

    assert "- __arg__ `Union[int, Tuple[int, int]]`: One or" in generated
    assert "- __arg2__ `int`: One integer." in generated

def doing_things(an_argument: dummy_package.DataGenerator):
    """A function

    # Arguments
        an_argument: Some generator

    """

def test_rendinging_with_extra_alias():
    extra_aliases = ["tests.dummy_package.DataGenerator"]
    generated = autogen.DocumentationGenerator(extra_aliases=extra_aliases)._render(
        doing_things)
    assert "- __an_argument__ `tests.dummy_package.DataGenerator`: Some" in generated

def test_rendinging_with_extra_alias_custom_alias():
    extra_aliases = {"tests.dummy_package.dummy_module.ImageDataGenerator":
                     "some.new.Thing"}
    generated = autogen.DocumentationGenerator(extra_aliases=extra_aliases)._render(
        doing_things)
    assert "- __an_argument__ `some.new.Thing`: Some" in generated

@pytest.mark.skipif(
    sys.version_info < (3, 7),
    reason="the __future__ annotations only works with py37+."
)
def test_future_annotations():
    from . import autogen_future
    autogen_future.test_rendinging_with_extra_alias()

if __name__ == "__main__":
    pytest.main([__file__])


text:
package io.chymyst.benchmark

import java.time.LocalDateTime
import io.chymyst.benchmark.Common._
import io.chymyst.jc._

import code.jiansen.scalajoin._ // Use precompiled classes from Jiansen's Join.scala, which are in that package.

object Benchmarks7 {

  /// Concurrent decrement of `n` counters, each going from `count` to 0 concurrently.

  /// create `n` asynchronous counters, initialize each to `count`, then decrement `count*n` times, until all counters are zero.
  /// collect the zero-counter events, make sure there are `n` of them, then fire an `all_done` event that yields the benchmark time.
  val numberOfCounters = 5

  def benchmark7(count: Int, tp: Pool): Long = {

    val done = m[Unit]
    val all_done = m[Int]
    val f = b[LocalDateTime,Long]

    site(tp)(
      go { case all_done(0) + f(tInit, r) => r(elapsed(tInit)) },
      go { case all_done(x) + done(_) if x > 0 => all_done(x-1) }
    )
    val initialTime = LocalDateTime.now
    all_done(numberOfCounters)

    val d = make_counters(done, numberOfCounters, count, tp)
    (1 to (count*numberOfCounters)).foreach{ _ => d() }

    f(initialTime)
  }

  // this deadlocks whenever `count` * `counters` becomes large.
  def benchmark8(count: Int, tp: Pool): Long = {

    println(s"Creating $numberOfCounters concurrent counters, each going from $count to 0")

    object j8 extends Join {
      object done extends AsyName[Unit]
      object all_done extends AsyName[Int]
      object f extends SynName[LocalDateTime, Long]

      join {
        case all_done(0) and f(tInit) =>
          f.reply(elapsed(tInit))
        case all_done(x) and done(_) if x > 0 => all_done(x-1)
      }

    }

    val initialTime = LocalDateTime.now
    j8.all_done(count)
    val d = make_counters8a(j8.done, numberOfCounters, count)
    (1 to (count*numberOfCounters)).foreach{ _ => d(()) }
    j8.f(initialTime)
  }

  private def make_counters(done: M[Unit], counters: Int, init: Int, tp: Pool) = {
    val c = m[Int]
    val d = m[Unit]

    site(tp)(
      go { case c(0) => done() },
      go { case c(n) + d(_) if n > 0 => c(n - 1) }
    )
    (1 to counters).foreach(_ => c(init))
    // We return just one molecule.
    d
  }

  private def make_counters8a(done: AsyName[Unit], counters: Int, init: Int): AsyName[Unit] = {
    object j8a extends Join {
      object c extends AsyName[Int]
      object d extends AsyName[Unit]

      join {
        case c(0) => done(())
        case c(n) and d(_) if n > 0 => c(n-1)
      }

    }
    (1 to counters).foreach(_ => j8a.c(init))
    // We return just one molecule.
    j8a.d
  }

}

redpajama_set_name: RedPajamaGithub


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

package com.google.security.zynamics.binnavi.Gui.GraphWindows.Implementations;

import com.google.security.zynamics.binnavi.Gui.GraphWindows.CGraphModel;
import com.google.security.zynamics.binnavi.ZyGraph.Builders.ZyInstructionBuilder;
import com.google.security.zynamics.binnavi.ZyGraph.Builders.Modifiers.CDefaultModifier;
import com.google.security.zynamics.binnavi.disassembly.CCodeNodeHelpers;
import com.google.security.zynamics.binnavi.disassembly.INaviCodeNode;
import com.google.security.zynamics.binnavi.disassembly.INaviInstruction;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.NaviNode;
import com.google.security.zynamics.zylib.disassembly.IInstruction;
import com.google.security.zynamics.zylib.general.Pair;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.CStyleRunData;

import java.awt.Color;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Class that manages the grayed instructions in a graph.
 */
public final class CLineGrayer {
  /**
   * List of instructions in the current graph which are grayed.
   */
  private final Set<IInstruction> m_grayedInstructions = new HashSet<IInstruction>();

  /**
   * Grays or ungrays a line in a code node.
   *
   * @param model The model of the graph the node belongs to.
   * @param node The node where the user clicked.
   * @param codeNode The node that provides the raw data for the node.
   * @param y The y location where the user clicked.
   */
  private void grayLine(
      final CGraphModel model, final NaviNode node, final INaviCodeNode codeNode, final double y) {
    final double yPos = y - node.getY();

    final int row = node.positionToRow(yPos);

    final INaviInstruction instruction = CCodeNodeHelpers.lineToInstruction(codeNode, row);

    if (instruction == null) {
      return;
    }

    // Lines can be toggled between "gray" and "not gray" depending
    // on the current status of the line.

    if (m_grayedInstructions.contains(instruction)) {
      final Pair<String, List<CStyleRunData>> content = ZyInstructionBuilder.buildInstructionLine(
          instruction, model.getGraph().getSettings(),
          new CDefaultModifier(model.getGraph().getSettings(), model.getDebuggerProvider()));

      for (final CStyleRunData style : content.second()) {
        node.setColor(row, style.getStart(), style.getLength(), style.getColor());
      }

      m_grayedInstructions.remove(instruction);
    } else {
      node.setColor(row, Color.LIGHT_GRAY);

      m_grayedInstructions.add(instruction);
    }
  }

  /**
   * Invoked when the user wants to gray/ungray a line.
   *
   * @param model The model of the graph the node belongs to.
   * @param node The node where the user clicked.
   * @param y The y location where the user clicked.
   */
  public void handleGrayLine(final CGraphModel model, final NaviNode node, final double y) {
    if (node.getRawNode() instanceof INaviCodeNode) {
      grayLine(model, node, (INaviCodeNode) node.getRawNode(), y);
    }
  }
}


text:
<?php

namespace MessageApp\User\Finder;

use MessageApp\User\ApplicationUser;

interface ApplicationUserFinder
{
    /**
     * Finds an user by its primary key / identifier.
     *
     * @param  string $id The identifier.
     *
     * @return ApplicationUser The user.
     */
    public function find($id);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<annotationscheme>
  <attribute id="anaphref_id" name="anaphref"
	     type="markable_pointer" color="blue" width="1" style="lcurve"
	     max_size="1"
	     target_domain="source"
	     point_to_markable_text="Mark as anaphoric antecedent of source"
	     remove_pointer_to_markable_text="Unmark as anaphoric antecedent of source">
    <value id="source_anaphref_set" name="set"/>
    <value id="source_anaphref_not_set" name="not_set" />
  </attribute>

  <attribute id="sentiment_ref_id" name="sentiment_ref"
	     type="markable_pointer" text="sentiment to which this source belongs to"
	     color="blue" width="1" style="lcurve" max_size="1"
	     target_domain="sentiment"
	     point_to_markable_text="Mark sentiment which this source belongs to"
	     remove_pointer_to_markable_text="Unmark sentiment which this source belongs to">
    <value id="sentiment_ref_set" name="set"/>
    <value id="sentiment_ref_not_set" name="not_set"/>
  </attribute>
</annotationscheme>


text:
<?php

namespace OWeb\manage;

use OWeb\types\Header;
use \OWeb\manage\Events;

/**
 * Manages the header files included to your web page.
 * This will not check for double includes it will just store the data
 * until you are ready to start the drawing of your page.
 *
 * If THe header you add is a js or css and aren't external links it will automatically correct
 * the path to were ares stored the .js and css files.
 *
 * ! The existance of the files won't be checked
 *
 * @author De Cramer Oliver
 */
class Headers extends \OWeb\utils\Singleton{

	/**
	 * The file you want to include is a a javasripty file, a .js.
	 */
	const javascript = 0;
	const js = 0;

	/**
	 * YOu want to include javascript code
	 */
	const jsCode = 3;

	/**
	 * A Css
	 */
    const css = 1;

	/**
	 * You just want to add a bit of Code inside the header. This code want't be modified.
	 */
    const code = 2;

	//List of all CSS headers
	private $css_headers = array();

	//List of all Javascript headers
	private $js_headers = array();

	//List of other headers
	private $other_headers = array();

	private $eventM;

	function __construct() {
		$this->eventM = Events::getInstance();
		self::forceInstance($this);
	}

	public function reset(){
		unset($this->css_headers);
		unset($this->js_headers);
		unset($this->other_headers);
		$this->css_headers = array();
		$this->js_headers = array();
		$this->other_headers = array();
	}

	/**
	 * Allows you to add a header to the we bpage
	 *
	 * @param  $code The url to the css, js or the name of the css or js file.
	 *						The path will be added automatically.
	 * @param int $type The type of the Header you want to add.
	 */
	public function addHeader($header, $type = -1){
		if($header instanceof Header)
			$this->other_headers[] = $header;
		else
			$this->addAndCreateHeader($header, $type);
	}

	public function addAndCreateHeader($code, $type){
		switch ($type){
			case self::javascript :
				$code =$this->getPath(OWEB_HTML_DIR_JS, $code);
				break;
			case self::css :
				$code =$this->getPath(OWEB_HTML_DIR_CSS, $code);

		}
        $header = new Header($code, $type);
        $code = md5($header->getCode());

		switch ($type) {
			case self::jsCode :
			case self::javascript :
				$this->js_headers[$code] = $header;
				break;
			case self::css :
				$this->css_headers[$code] = $header;
				break;
			default:
				$this->other_headers[] = $header;
				break;
		}
	}

	public function addJs($file){
		$this->addHeader($file, self::js);
	}

	public function addCss($file){
		$this->addHeader($file, self::css);
	}

	public function addJsCode($code){
		$this->addHeader($code, self::jsCode);
	}

	public function addCode($code){
		$this->addHeader($code, self::code);
	}

	private function getPath($path1, $path2){
		if($path2[0]=='h'&&$path2[1]=='t'&&$path2[2]=='t'&&$path2[3]=='p')
			return $path2;
		else
			return $path1.'/'.$path2;
	}

	/**
	 * Display the Headers that has been added.
	 */
	public function display(){

		$this->eventM->sendEvent('Didplay_Prepare@OWeb\manage\Headers');

		echo "\n<!--OWEB displays all CSS includes-->\n";
		//DIsplaying all Css Headers
		foreach ($this->css_headers as $id => $h){
			echo $h->getCode($id);
		}

		echo "\n<!--OWEB displays all JS includes and codes-->\n";

		//Displaying Javascript Headers
		foreach ($this->js_headers as $id => $h){
			echo $h->getCode($id);
		}

		echo "\n<!--OWEB displays personalized header codes-->\n";
		//Displaying all other headers
		foreach ($this->other_headers as $id => $h){
			echo $h->getCode($id);
		}

		$this->eventM->sendEvent('Didplay_Done@OWeb\manage\Headers');
	}

	/**
	 * Returns the string that the display function would display.
	 *
	 * @return String The headers that has been added as a String.
	 */
	public function toString(){

		$s = "\n<!--OWEB displays all CSS includes-->\n";
		//DIsplaying all Css Headers
		foreach ($this->css_headers as $id => $h){
			$s .= $h->getCode($id);
		}

		$s .=  "\n<!--OWEB displays all JS includes and codes-->\n";

		//Displaying Javascript Headers
		foreach ($this->js_headers as $id => $h){
			$s .= $h->getCode($id);
		}

		$s .=  "\n<!--OWEB displays personalized header codes-->\n";
		//Displaying all other headers
		foreach ($this->other_headers as $id => $h){
			$s .= $h->getCode($id);
		}

		return $s;
	}

	public function getAllHeaders(){
		$all = array();
		foreach ($this->css_headers as $id => $h){
			$all[$id] = $h->getCode($id);
		}
		foreach ($this->js_headers as $id => $h){
			$all[$id] = $h->getCode($id);
		}
		foreach ($this->other_headers as $id => $h){
			$all[$id] = $h->getCode($id);
		}
		return $all;
	}

}

?>


text:
package com.coolweather.app.activity;

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

import com.coolweather.app.model.City;
import com.coolweather.app.model.County;
import com.coolweather.app.model.Province;
import com.coolweather.app.util.CoolWeatherDB;
import com.coolweather.app.util.HttpCallbackListener;
import com.coolweather.app.util.HttpUtil;
import com.coolweather.app.util.Utility;
import com.coolweather.app.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ChooseAreaActivity extends Activity {

	public static final int LEVEL_PROVINCE = 0;
	public static final int LEVEL_CITY = 1;
	public static final int LEVEL_COUNTY = 2;

	private ProgressDialog progressDialog;
	private TextView textView;
	private ListView listView;
	private ArrayAdapter<String> adapter;
	private CoolWeatherDB coolWeatherDB;
	private List<String> dataList = new ArrayList<String>();
	private List<Province> provincelist;
	private List<City> citylist;
	private List<County> countylist;
	private Province selectedProvince;
	private City selectedCity;
	private int currentLevel;
	private boolean isFromWeatherActivity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		if(prefs.getBoolean("city_selected", false) && !isFromWeatherActivity){
			Intent intent = new Intent(this,WeatherActivity.class);
			startActivity(intent);
			finish();
			return;
		}
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.choose_area);
		listView = (ListView) findViewById(R.id.list_view);
		textView = (TextView) findViewById(R.id.title_text);
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,dataList);
		listView.setAdapter(adapter);
		coolWeatherDB = CoolWeatherDB.getInstance(this);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,
					long arg3) {
				// TODO Auto-generated method stub
				if(currentLevel == LEVEL_PROVINCE){
					selectedProvince = provincelist.get(index);
					queryCities();
				}else if(currentLevel == LEVEL_CITY){
					selectedCity = citylist.get(index);
					queryCounties();
				}else if (currentLevel == LEVEL_COUNTY) {
					String countyCode = countylist.get(index).getCountyCode();
					Intent intent = new Intent(ChooseAreaActivity.this,WeatherActivity.class);
					intent.putExtra("county_code", countyCode);
					startActivity(intent);
					finish();
				}
			}
		});
		queryProvinces();
	}

	private void queryProvinces() {
		// TODO Auto-generated method stub
		provincelist = coolWeatherDB.loadProvices();
		if(provincelist.size() > 0){
			dataList.clear();
			for(Province province : provincelist){
				dataList.add(province.getProvinceName());
			}
			adapter.notifyDataSetChanged();listView.setSelection(0);
			textView.setText("Öйú");
			currentLevel = LEVEL_PROVINCE;
		}else {
			queryFromService(null,"province");
		}
	}

	protected void queryCounties() {
		// TODO Auto-generated method stub
		countylist = coolWeatherDB.loadCounties(selectedCity.getId());
		if(countylist.size() > 0){
			dataList.clear();
			for(County county : countylist){
				dataList.add(county.getCountyName());
			}
			adapter.notifyDataSetChanged();
			listView.setSelection(0);
			textView.setText(selectedCity.getCityName());
			currentLevel = LEVEL_COUNTY;
		}else {
			queryFromService(selectedCity.getCityCode(),"county");
		}
	}

	protected void queryCities() {
		// TODO Auto-generated method stub
		citylist = coolWeatherDB.loadCities(selectedProvince.getId());
		if(citylist.size() > 0){
			dataList.clear();
			for(City city : citylist){
				dataList.add(city.getCityName());
			}
			adapter.notifyDataSetChanged();listView.setSelection(0);
			textView.setText(selectedProvince.getProvinceName());
			currentLevel = LEVEL_CITY;
		}else {
			queryFromService(selectedProvince.getProvinceCode(),"city");
		}
	}

	private void queryFromService(final String code,final String type) {
		// TODO Auto-generated method stub
		String address;
		if(!TextUtils.isEmpty(code)){
			address = "http://www.weather.com.cn./data/list3/city" + code +".xml";
		}else{
			address = "http://www.weather.com.cn./data/list3/city.xml";
		}
		showProgressDialog();
		HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {

			@Override
			public void onFinish(String response) {
				// TODO Auto-generated method stub
				boolean result = false;
				if("province".equals(type)){
					result = Utility.handleProvincesResponse(coolWeatherDB, response);
				}else if ("city".equals(type)) {
					result = Utility.handleCitiesResponse(coolWeatherDB, response , selectedProvince.getId());
				}else if ("county".equals(type)) {
					result = Utility.handleCountiesResponse(coolWeatherDB, response , selectedCity.getId());
				}
				if(result){
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							closeProgressDialog();
							if("province".equals(type)){
								queryProvinces();
							}else if("city".equals(type)){
								queryCities();
							}else if("county".equals(type)){
								queryCounties();
							}
						}

					});
				}
			}

			@Override
			public void onError(Exception e) {
				// TODO Auto-generated method stub
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						closeProgressDialog();Toast.makeText(ChooseAreaActivity.this, "¼ÓÔØʧ°Ü", 1).show();
					}
				});
			}
		});
	}

	private void showProgressDialog() {
		// TODO Auto-generated method stub
		if(progressDialog == null){
			progressDialog = new ProgressDialog(this);
			progressDialog.setMessage("ÕýÔÚ¼ÓÔØ");
			progressDialog.setCanceledOnTouchOutside(false);
		}
		progressDialog.show();
	}

	private void closeProgressDialog() {
		// TODO Auto-generated method stub
		if(progressDialog != null){
			progressDialog.dismiss();
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if(currentLevel == LEVEL_COUNTY){
			queryCities();
		}else if(currentLevel == LEVEL_CITY){
			queryProvinces();
		}else {
			if(isFromWeatherActivity){
				Intent intent = new Intent(this,WeatherActivity.class);
				startActivity(intent);
			}
			finish();
		}
	}

}


text:
import os
import sys

from modularodm import Q
from modularodm.exceptions import ModularOdmException

from framework.auth.core import User

from website import settings
from website.app import init_app
from website.conferences.model import Conference

def main():
    init_app(set_backends=True, routes=False)
    populate_conferences()

MEETING_DATA = {
    'spsp2014': {
        'name': 'SPSP 2014',
        'info_url': None,
        'logo_url': None,
        'active': False,
        'admins': [],
        'public_projects': True,
    },
    'asb2014': {
        'name': 'ASB 2014',
        'info_url': 'http://www.sebiologists.org/meetings/talks_posters.html',
        'logo_url': None,
        'active': False,
        'admins': [],
        'public_projects': True,
    },
    'aps2014': {
        'name': 'APS 2014',
        'info_url': 'http://centerforopenscience.org/aps/',
        'logo_url': '/static/img/2014_Convention_banner-with-APS_700px.jpg',
        'active': False,
        'admins': [],
        'public_projects': True,
    },
    'annopeer2014': {
        'name': '#annopeer',
        'info_url': None,
        'logo_url': None,
        'active': False,
        'admins': [],
        'public_projects': True,
    },
    'cpa2014': {
        'name': 'CPA 2014',
        'info_url': None,
        'logo_url': None,
        'active': False,
        'admins': [],
        'public_projects': True,
    },
    'filaments2014': {
        'name': 'Filaments 2014',
        'info_url': None,
        'logo_url': 'https://science.nrao.edu/science/meetings/2014/'
                    'filamentary-structure/images/filaments2014_660x178.png',
        'active': False,
        'admins': [
            'lvonschi@nrao.edu',
            'sara.d.bowman@gmail.com',
            # 'Dkim@nrao.edu',
        ],
        'public_projects': True,
    },
    'bitss2014': {
        'name': 'BITSS Research Transparency Forum 2014',
        'info_url': None,
        'logo_url': os.path.join(
            settings.STATIC_URL_PATH,
            'img',
            'conferences',
            'bitss.jpg',
        ),
        'active': False,
        'admins': [
            'gkroll@berkeley.edu',
            'andrew@cos.io',
            'awais@berkeley.edu',
        ],
        'public_projects': True,
    },
    'spsp2015': {
        'name': 'SPSP 2015',
        'info_url': None,
        'logo_url': 'http://spspmeeting.org/CMSPages/SPSPimages/spsp2015banner.jpg',
        'active': True,
        'admins': [
            'meetings@spsp.org',
            'andrew@cos.io',
        ],
    },
    'aps2015': {
        'name': 'APS 2015',
        'info_url': None,
        'logo_url': 'http://www.psychologicalscience.org/images/APS_2015_Banner_990x157.jpg',
        'active': True,
        'admins': [
            'KatyCain526@gmail.com',
        ],
        'public_projects': True,
    },
    'icps2015': {
        'name': 'ICPS 2015',
        'info_url': None,
        'logo_url': 'http://icps.psychologicalscience.org/wp-content/themes/deepblue/images/ICPS_Website-header_990px.jpg',
        'active': True,
        'admins': [
            'KatyCain526@gmail.com',
        ],
        'public_projects': True,
    },
    'mpa2015': {
        'name': 'MPA 2015',
        'info_url': None,
        'logo_url': 'http://www.midwesternpsych.org/resources/Pictures/MPA%20logo.jpg',
        'active': True,
        'admins': [
            'mpa@kent.edu',
            'KatyCain526@gmail.com',
        ],
        'public_projects': True,
    },
    'NCCC2015': {
        'name': '2015 NC Cognition Conference',
        'info_url': None,
        'logo_url': None,
        'active': True,
        'admins': [
            'aoverman@elon.edu',
            'KatyCain526@gmail.com',
        ],
        'public_projects': True,
    },
    'VPRSF2015': {
        'name': 'Virginia Piedmont Regional Science Fair',
        'info_url': None,
        'logo_url': 'http://vprsf.org/wp-content/themes/VPRSF/images/logo.png',
        'active': True,
        'admins': [
            'director@vprsf.org',
            'KatyCain526@gmail.com',
        ],
        'public_projects': True,
    },
    'APRS2015': {
        'name': 'UVA Annual Postdoctoral Research Symposium 2015',
        'info_url': None,
        'logo_url': 'http://s1.postimg.org/50qj9u6i7/GPA_Logo.jpg',
        'active': True,
        'admins': [
            'mhurst@virginia.edu',
            'KatyCain526@gmail.com',
        ],
        'public_projects': True,
    },
    'ASB2015': {
        'name': 'Association of Southeastern Biologists  2015',
        'info_url': None,
        'logo_url': 'http://www.sebiologists.org/wp/wp-content/uploads/2014/09/banner_image_Large.png',
        'active': True,
        'admins': [
            'amorris.mtsu@gmail.com',
            'KatyCain526@gmail.com',
        ],
        'public_projects': True,
    },
    'TeaP2015': {
        'name': 'Tagung experimentell arbeitender Psychologen 2015',
        'info_url': None,
        'logo_url': None,
        'active': True,
        'admins': [
            'sara.d.bowman@gmail.com',
        ],
        'public_projects': True,
    },
    'VSSEF2015': {
        'name': 'Virginia State Science and Engineering Fair 2015',
        'info_url': 'http://www.vmi.edu/conferences/vssef/vssef_home/',
        'logo_url': 'http://www.vmi.edu/uploadedImages/Images/Headers/vssef4.jpg',
        'active': True,
        'admins': [],
        'public_projects': True,
    },
    'RMPA2015': {
        'name': 'Rocky Mountain Psychological Association 2015',
        'info_url': 'http://www.rockymountainpsych.org/uploads/7/4/2/6/7426961/85th_annual_rmpa_conference_program_hr.pdf',
        'logo_url': 'http://www.rockymountainpsych.org/uploads/7/4/2/6/7426961/header_images/1397234084.jpg',
        'active': True,
        'admins': [],
        'public_projects': True,
    },
    'ARP2015': {
        'name': 'Association for Research in Personality 2015',
        'info_url': 'http://www.personality-arp.org/conference/',
        'logo_url': 'http://www.personality-arp.org/wp-content/uploads/conference/st-louis-arp.jpg',
        'active': True,
        'admins': [],
        'public_projects': True,
    },
    'SEP2015': {
        'name': 'Society of Experimental Psychologists Meeting 2015',
        'info_url': 'http://faculty.virginia.edu/Society_of_Experimental_Psychologists/',
        'logo_url': 'http://www.sepsych.org/nav/images/SEP-header.gif',
        'active': True,
        'admins': [],
        'public_projects': True,
    },

}

def populate_conferences():
    for meeting, attrs in MEETING_DATA.iteritems():
        meeting = meeting.strip()
        admin_emails = attrs.pop('admins')
        admin_objs = []
        for email in admin_emails:
            try:
                user = User.find_one(Q('username', 'iexact', email))
                admin_objs.append(user)
            except ModularOdmException:
                raise RuntimeError('Username {0!r} is not registered.'.format(email))
        conf = Conference(
            endpoint=meeting, admins=admin_objs, **attrs
        )
        try:
            conf.save()
        except ModularOdmException:
            print('{0} Conference already exists. Updating existing record...'.format(meeting))
            conf = Conference.find_one(Q('endpoint', 'eq', meeting))
            for key, value in attrs.items():
                setattr(conf, key, value)
            conf.admins = admin_objs
            conf.save()

if __name__ == '__main__':
    main()


text:
var fs = require('fs')
	, trycatch = require('../lib/trycatch')
	, _ = require('underscore')._

trycatch.configure({
	'long-stack-traces': true
, colors: {
    "node": "none"
  , "node_modules": false
  , "default": 'yellow'
  }
})

trycatch(function() {
	  fs.readFile(__filename, function () {
	      _.map(['Error 1', 'Error 2']
	      , function foo(v) {
		        setTimeout(function() {
		          throw new Error(v)
		        }, 10)
		      })
	  })
	}
, function(err) {
	  console.log("Async error caught!\n", err.stack);
	});


text:
namespace mojo {
namespace test {
namespace {

void AllocRequestMessage(uint32_t name, const char* text, Message* message) {
  size_t payload_size = strlen(text) + 1;  // Plus null terminator.
  internal::RequestMessageBuilder builder(name, payload_size);
  memcpy(builder.buffer()->Allocate(payload_size), text, payload_size);
  builder.Finish(message);
}

void AllocResponseMessage(uint32_t name, const char* text,
                          uint64_t request_id, Message* message) {
  size_t payload_size = strlen(text) + 1;  // Plus null terminator.
  internal::ResponseMessageBuilder builder(name, payload_size, request_id);
  memcpy(builder.buffer()->Allocate(payload_size), text, payload_size);
  builder.Finish(message);
}

class MessageAccumulator : public MessageReceiver {
 public:
  explicit MessageAccumulator(internal::MessageQueue* queue) : queue_(queue) {
  }

  virtual bool Accept(Message* message) MOJO_OVERRIDE {
    queue_->Push(message);
    return true;
  }

  virtual bool AcceptWithResponder(Message* message, MessageReceiver* responder)
      MOJO_OVERRIDE {
    return false;
  }

 private:
  internal::MessageQueue* queue_;
};

class ResponseGenerator : public MessageReceiver {
 public:
  ResponseGenerator() {
  }

  virtual bool Accept(Message* message) MOJO_OVERRIDE {
    return false;
  }

  virtual bool AcceptWithResponder(Message* message, MessageReceiver* responder)
      MOJO_OVERRIDE {
    EXPECT_TRUE(message->has_flag(internal::kMessageExpectsResponse));

    return SendResponse(message->name(), message->request_id(), responder);
  }

  bool SendResponse(uint32_t name, uint64_t request_id,
                    MessageReceiver* responder) {
    Message response;
    AllocResponseMessage(name, "world", request_id, &response);

    bool result = responder->Accept(&response);
    delete responder;
    return result;
  }
};

class LazyResponseGenerator : public ResponseGenerator {
 public:
  LazyResponseGenerator() : responder_(NULL), name_(0), request_id_(0) {
  }

  virtual ~LazyResponseGenerator() {
    delete responder_;
  }

  virtual bool AcceptWithResponder(Message* message, MessageReceiver* responder)
      MOJO_OVERRIDE {
    name_ = message->name();
    request_id_ = message->request_id();
    responder_ = responder;
    return true;
  }

  bool has_responder() const { return !!responder_; }

  void Complete() {
    SendResponse(name_, request_id_, responder_);
    responder_ = NULL;
  }

 private:
  MessageReceiver* responder_;
  uint32_t name_;
  uint32_t request_id_;
};

class RouterTest : public testing::Test {
 public:
  RouterTest() {
  }

  virtual void SetUp() MOJO_OVERRIDE {
    CreateMessagePipe(&handle0_, &handle1_);
  }

  virtual void TearDown() MOJO_OVERRIDE {
  }

  void PumpMessages() {
    loop_.RunUntilIdle();
  }

 protected:
  ScopedMessagePipeHandle handle0_;
  ScopedMessagePipeHandle handle1_;

 private:
  Environment env_;
  RunLoop loop_;
};

TEST_F(RouterTest, BasicRequestResponse) {
  internal::Router router0(handle0_.Pass());
  internal::Router router1(handle1_.Pass());

  ResponseGenerator generator;
  router1.set_incoming_receiver(&generator);

  Message request;
  AllocRequestMessage(1, "hello", &request);

  internal::MessageQueue message_queue;
  router0.AcceptWithResponder(&request, new MessageAccumulator(&message_queue));

  PumpMessages();

  EXPECT_FALSE(message_queue.IsEmpty());

  Message response;
  message_queue.Pop(&response);

  EXPECT_EQ(std::string("world"),
            std::string(reinterpret_cast<const char*>(response.payload())));
}

TEST_F(RouterTest, RequestWithNoReceiver) {
  internal::Router router0(handle0_.Pass());
  internal::Router router1(handle1_.Pass());

  // Without an incoming receiver set on router1, we expect router0 to observe
  // an error as a result of sending a message.

  Message request;
  AllocRequestMessage(1, "hello", &request);

  internal::MessageQueue message_queue;
  router0.AcceptWithResponder(&request, new MessageAccumulator(&message_queue));

  PumpMessages();

  EXPECT_TRUE(router0.encountered_error());
  EXPECT_TRUE(router1.encountered_error());
  EXPECT_TRUE(message_queue.IsEmpty());
}

TEST_F(RouterTest, LateResponse) {
  // Test that things won't blow up if we try to send a message to a
  // MessageReceiver, which was given to us via AcceptWithResponder,
  // after the router has gone away.

  LazyResponseGenerator generator;
  {
    internal::Router router0(handle0_.Pass());
    internal::Router router1(handle1_.Pass());

    router1.set_incoming_receiver(&generator);

    Message request;
    AllocRequestMessage(1, "hello", &request);

    internal::MessageQueue message_queue;
    router0.AcceptWithResponder(&request,
                                new MessageAccumulator(&message_queue));

    PumpMessages();

    EXPECT_TRUE(generator.has_responder());

  }

  generator.Complete();  // This should end up doing nothing.
}

}  // namespace
}  // namespace test
}  // namespace mojo


text:
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>cn.zhuhongqing</groupId>
		<artifactId>zhq-parent</artifactId>
		<version>0.0.1</version>
	</parent>

	<artifactId>zhq-template-velocity</artifactId>
	<name>zhq-template-velocity</name>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>cn.zhuhongqing</groupId>
			<artifactId>zhq-template</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity</artifactId>
			<version>1.7</version>
		</dependency>
	</dependencies>
</project>


text:
package cf.nearby.nearby.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import java.util.ArrayList;

import cf.nearby.nearby.R;
import cf.nearby.nearby.activity.InquiryDateDetailActivity;
import cf.nearby.nearby.obj.HaveMeal;
import cf.nearby.nearby.obj.MainRecord;
import cf.nearby.nearby.obj.PatientRemark;
import cf.nearby.nearby.obj.TakeMedicine;
import cf.nearby.nearby.util.AdditionalFunc;
import cf.nearby.nearby.util.OnAdapterSupport;
import cf.nearby.nearby.util.OnLoadMoreListener;
import cf.nearby.nearby.util.RecordListSupporter;

/**
 * Created by tw on 2017-10-01.
 */
public class InquiryDateListCustomAdapter extends RecyclerView.Adapter<InquiryDateListCustomAdapter.ViewHolder> {

    // UI
    private Context context;
//    private RecordListSupporter recordSupporter;

    private OnAdapterSupport onAdapterSupport;

    public ArrayList<MainRecord> list;

    // 무한 스크롤
    private OnLoadMoreListener onLoadMoreListener;
    private int visibleThreshold = 10;
    private int lastVisibleItem, totalItemCount;
    private boolean loading = false;

    // 생성자
    public InquiryDateListCustomAdapter(Context context, ArrayList<MainRecord> list, RecyclerView recyclerView, OnAdapterSupport listener) {
        this.context = context;
        this.list = list;
        this.onAdapterSupport = listener;
//        this.recordSupporter = recordSupporter;

        if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
            recyclerView.addOnScrollListener(new ScrollListener() {
                @Override
                public void onHide() {
                    hideViews();
                }

                @Override
                public void onShow() {
                    showViews();
                }
            });
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //recycler view에 반복될 아이템 레이아웃 연결
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.inquiry_date_list_custom_item,null);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        final MainRecord mr = list.get(position);
        final int pos = position;

        holder.tv_dateTitle.setText(mr.getDate());

        holder.cv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, InquiryDateDetailActivity.class);
                intent.putExtra("date", mr.getRegisteredDate());
                onAdapterSupport.redirectActivity(intent);
            }
        });

    }

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

    private void hideViews() {
        if (onAdapterSupport != null) {
            onAdapterSupport.hideView();
        }
    }

    private void showViews() {
        if (onAdapterSupport != null) {
            onAdapterSupport.showView();
        }
    }

    // 무한 스크롤
    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }
    public void setLoaded() {
        loading = false;
    }

    public abstract class ScrollListener extends RecyclerView.OnScrollListener {
        private static final int HIDE_THRESHOLD = 30;
        private int scrolledDistance = 0;
        private boolean controlsVisible = true;

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();

            totalItemCount = linearLayoutManager.getItemCount();
            lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
            if (!loading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                // End has been reached
                // Do something
                loading = true;
                if (onLoadMoreListener != null) {
                    onLoadMoreListener.onLoadMore();
                }
            }
            // 여기까지 무한 스크롤

            if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) {
                onHide();
                controlsVisible = false;
                scrolledDistance = 0;
            } else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) {
                onShow();
                controlsVisible = true;
                scrolledDistance = 0;
            }

            if((controlsVisible && dy>0) || (!controlsVisible && dy<0)) {
                scrolledDistance += dy;
            }
            // 여기까지 툴바 숨기기
        }

        public abstract void onHide();
        public abstract void onShow();

    }

    public final static class ViewHolder extends RecyclerView.ViewHolder {

        Rect rect;

        CardView cv;
        TextView tv_dateTitle;

        public ViewHolder(View v) {
            super(v);
            cv = (CardView)v.findViewById(R.id.cv);
            setCardButtonOnTouchAnimation(cv);
            tv_dateTitle = (TextView)v.findViewById(R.id.tv_date_title);
        }

        public void setCardButtonOnTouchAnimation(final View v){

            View.OnTouchListener onTouchListener = new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
//                System.out.println(motionEvent.getAction());
                    switch (motionEvent.getAction()){
                        case MotionEvent.ACTION_DOWN: {
                            rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
//                        System.out.println("action down");
                            Animation anim = new ScaleAnimation(
                                    1f, 0.95f, // Start and end values for the X axis scaling
                                    1f, 0.95f, // Start and end values for the Y axis scaling
                                    Animation.RELATIVE_TO_SELF, 0.5f, // Pivot point of X scaling
                                    Animation.RELATIVE_TO_SELF, 0.5f); // Pivot point of Y scaling
                            anim.setFillAfter(true); // Needed to keep the result of the animation
                            anim.setDuration(300);
                            v.startAnimation(anim);
                            v.requestLayout();
                            return true;
                        }
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP: {
//                        System.out.println("action up");
                            Animation anim = new ScaleAnimation(
                                    0.95f, 1f, // Start and end values for the X axis scaling
                                    0.95f, 1f, // Start and end values for the Y axis scaling
                                    Animation.RELATIVE_TO_SELF, 0.5f, // Pivot point of X scaling
                                    Animation.RELATIVE_TO_SELF, 0.5f); // Pivot point of Y scaling
                            anim.setFillAfter(true); // Needed to keep the result of the animation
                            anim.setDuration(300);
                            v.startAnimation(anim);
                            v.requestLayout();
                            if(!rect.contains(v.getLeft() + (int) motionEvent.getX(), v.getTop() + (int) motionEvent.getY())){
                                // User moved outside bounds
                            }else{
                                v.callOnClick();
                            }
                            return true;
                        }
                    }
                    return false;
                }
            };
            v.setOnTouchListener(onTouchListener);
        }

    }

}


text:
package io.github.tehstoneman.betterstorage.common.item.cardboard;

import io.github.tehstoneman.betterstorage.BetterStorage;
import io.github.tehstoneman.betterstorage.ModInfo;
import io.github.tehstoneman.betterstorage.api.ICardboardItem;
import io.github.tehstoneman.betterstorage.utils.MiscUtils;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemSpade;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.common.registry.GameRegistry;

public class ItemCardboardShovel extends ItemSpade implements ICardboardItem
{

	private String name;

	public ItemCardboardShovel()
	{
		super( ItemCardboardSheet.toolMaterial );
	}

	@Override
	public boolean canDye( ItemStack stack )
	{
		return true;
	}

	@Override
	public int getColor( ItemStack stack )
	{
		final NBTTagCompound nbttagcompound = stack.getTagCompound();

		if( nbttagcompound != null )
		{
			final NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag( "display" );

			if( nbttagcompound1 != null && nbttagcompound1.hasKey( "color", 3 ) )
				return nbttagcompound1.getInteger( "color" );
		}
		return 0x705030;
	}

	// Makes sure cardboard tools don't get destroyed,
	// and are ineffective when durability is at 0.
	@Override
	public boolean canHarvestBlock( IBlockState block, ItemStack stack )
	{
		return ItemCardboardSheet.canHarvestBlock( stack, super.canHarvestBlock( block, stack ) );
	}

	@Override
	public boolean onLeftClickEntity( ItemStack stack, EntityPlayer player, Entity entity )
	{
		return !ItemCardboardSheet.isEffective( stack );
	}

	/*
	 * @Override
	 * public boolean onBlockDestroyed( ItemStack stack, World world, IBlockState block, BlockPos pos, EntityLivingBase player )
	 * {
	 * return ItemCardboardSheet.onBlockDestroyed( stack, world, block, pos, player );
	 * }
	 */

	@Override
	public boolean hitEntity( ItemStack stack, EntityLivingBase target, EntityLivingBase player )
	{
		return ItemCardboardSheet.damageItem( stack, 1, player );
	}
}


text:
Ember.Location.registerImplementation("hashbang", Ember.HashLocation.extend({
  getURL: function() {
    return Ember.get(this, "location").hash.substr(2);
  },
  setURL: function(path) {
    Ember.get(this, "location").hash = "!" + path;
    return Ember.set(this, "lastSetURL", path);
  },
  onUpdateURL: function(callback) {
    var guid, self;
    self = this;
    guid = Ember.guidFor(this);
    return Ember.$(window).bind("hashchange.ember-location-" + guid, function() {
      return Ember.run(function() {
        var path;
        path = location.hash.substr(2);
        if (Ember.get(self, "lastSetURL") === path) {
          return;
        }
        Ember.set(self, "lastSetURL", null);
        return callback(path);
      });
    });
  },
  formatURL: function(url) {
    return "#!" + url;
  }
}));


text:
"""Access Role Action Type Mapping Model Class."""
from __future__ import unicode_literals
from granted.models.base_model import BaseModel
from django.db import models

class AccessRoleActionTypeMapping(BaseModel):
    """Access Role Action Type Mapping Model definition."""

    access_role = models.ForeignKey('AccessRole')
    action_type = models.ForeignKey('ActionType')

    class Meta:
        db_table = 'access_role_action_type_mappings'
        verbose_name = 'Access Role Action Type Mapping'
        verbose_name_plural = 'Access Role Action Type Mappings'
        unique_together = (('access_role', 'action_type'))

    def __unicode__(self):
        """Return the name of the entity."""
        return ''


text:
package com.fhc25.percepcion.osiris.mapviewer.ui.overlays;

import java.util.Comparator;

/**
 * Describes an element that can be displayed through a map library
 */
public abstract class VisualElement {

	/**
	 * Gets the Zdepth of the visual element. The Zdepth determines the order of
	 * drawing when several visual elements are drawn over the same map. Lower
	 * numbers imply that the visual element is drawn earlier, and then appears
	 * occluded by visual elements with higher Zdepth
	 *
	 * @return
	 */
	abstract public int getZDepth();

    /**
     * Called for destroying the visual element. Not every implementation shall use this feature,
     * for instance if the destruction of the visual element does not need to be called explicitly
     */
    abstract public void destroy();

	/**
	 * Main comparator based on the Zdepth value of the visual elements
	 */
	static public final Comparator<VisualElement> ZDEPTH_COMPARATOR = new Comparator<VisualElement>() {

		@Override
		public int compare(VisualElement lhs, VisualElement rhs) {
			return lhs.getZDepth() - rhs.getZDepth();
		}

	};

}


text:
namespace fbp {

    void connector::connect(port_container& ports, connectable* pconnectable) {
        do_connect(ports, pconnectable);
    }

    connector::~connector() {}

}


text:
package backend.transform.scalars.instructionCombine;

import backend.ir.AllocationInst;
import backend.ir.MallocInst;
import backend.ir.SelectInst;
import backend.target.TargetData;
import backend.transform.scalars.InstructionCombine;
import backend.type.*;
import backend.utils.InstVisitor;
import backend.value.*;
import backend.value.Instruction.*;
import backend.value.Value.UndefValue;
import tools.APInt;
import tools.Util;

import java.util.ArrayList;

/**
 * @author Jianping Zeng.
 * @version 0.4
 */
public class Combiner implements InstVisitor<Instruction> {
  private InstructionCombine com;
  private TargetData td;

  public Combiner(InstructionCombine com) {
    this.com = com;
    td = com.getTargetData();
  }

  /**
   * Transform the case that bitcast from integral pointer to
   * aggregate pointer, get rid of redundant bitcast instruction.
   *
   * @param inst
   * @return
   */
  @Override
  public Instruction visitBitCast(User inst) {
    Util.assertion(inst != null);
    BitCastInst bc = (BitCastInst) inst;
    // optimize the case like this:
    // %t = alloca %struct.Test
    // %1 = bitcast %struct.Test* %t to i64*
    // store i64 %0, i64* %1, align 1
    Value srcOp = bc.operand(0);
    if (!(srcOp instanceof AllocationInst))
      return null;
    // if no td available, we can't go on.
    if (td == null)
      return null;

    AllocationInst ai = (AllocationInst) srcOp;

    Type srcTy = ai.getType();
    Type destTy = bc.getType();

    if (srcTy.isPointerType() && destTy.isPointerType()) {
      Type srcEleTy = ((PointerType) srcTy).getElementType();
      Type destEleTy = ((PointerType) destTy).getElementType();
      if (!srcEleTy.isSized() || !destEleTy.isSized())
        return null;
      int srcEleTyAlign = td.getABITypeAlignment(srcEleTy);
      int destEleTyAlign = td.getABITypeAlignment(destEleTy);
      if (destEleTyAlign < srcEleTyAlign)
        return null;

      // If the allocation has multiple uses, only promote it if we are strictly
      // increasing the alignment of the resultant allocation.  If we keep it the
      // same, we open the door to infinite loops of various kinds.
      if (!ai.hasOneUses() && destEleTyAlign == srcEleTyAlign)
        return null;

      long srcEleTySize = td.getTypeSize(srcEleTy);
      long destEleTySize = td.getTypeSize(destEleTy);
      if (srcEleTySize == 0 || destEleTySize == 0)
        return null;
      if ((destEleTySize % srcEleTySize) != 0)
        return null;

      if (srcEleTy.isAggregateType() && destEleTy.isIntegerTy()) {
        int scale = (int) (srcEleTySize / destEleTySize);
        Value numElements = ai.operand(0);
        Value amt;
        if (scale == 1)
          amt = numElements;
        else {
          // If the allocation size is constant, form a constant mul expression
          amt = ConstantInt.get(Type.getInt32Ty(inst.getContext()), scale);
          if (numElements instanceof ConstantInt) {
            amt = ConstantExpr.getMul((ConstantInt) amt, (ConstantInt) numElements);
          } else {
            Instruction tmp = BinaryOperator.createMul(amt, numElements, "tmp");
            tmp.insertBefore(ai);
            amt = tmp;
          }
        }
        AllocationInst newAI;
        if (ai instanceof MallocInst)
          newAI = new MallocInst(destEleTy, amt, "tmp", ai.getAlignment(), ai);
        else
          newAI = new AllocaInst(destEleTy, amt, ai.getAlignment(), "tmp", ai);
        newAI.setName(ai.getName());

        // If the allocation has multiple real uses, insert a cast and change all
        // things that used it to use the new cast.  This will also hack on CI, but it
        // will die soon.
        if (!bc.isUseEmpty()) {
          com.addUserToWorklist(ai);
          CastInst cast = new BitCastInst(newAI, ai.getType(), "tmpcast");
          cast.insertBefore(ai);
          ai.replaceAllUsesWith(cast);
          ai.eraseFromParent();
        }
        return com.replaceInstUsesWith(bc, newAI);
      }
    }
    return null;
  }

  @Override
  public Instruction visitRet(User inst) {
    return null;
  }

  @Override
  public Instruction visitBr(User inst) {
    return null;
  }

  @Override
  public Instruction visitSwitch(User inst) {
    return null;
  }

  @Override
  public Instruction visitICmp(User inst) {
    return null;
  }

  @Override
  public Instruction visitFCmp(User inst) {
    return null;
  }

  @Override
  public Instruction visitLoad(User inst) {
    return null;
  }

  @Override
  public Instruction visitStore(User inst) {
    return null;
  }

  @Override
  public Instruction visitCall(User inst) {
    return null;
  }

  @Override
  public Instruction visitGetElementPtr(User inst) {
    Util.assertion(inst instanceof GetElementPtrInst);
    GetElementPtrInst gep = (GetElementPtrInst) inst;
    Value ptrOp = gep.operand(0);
    if (gep.getNumOfOperands() == 1)
      return com.replaceInstUsesWith(gep, ptrOp);
    boolean firstIndexIsZero = false;
    if (gep.operand(1) instanceof ConstantInt) {
      firstIndexIsZero = ((ConstantInt) gep.operand(1)).isNullValue();
    }
    if (gep.getNumOfOperands() == 2 && firstIndexIsZero)
      return com.replaceInstUsesWith(gep, ptrOp);

    // Checks to see if we can simplify:
    // X = bitcast A to struct T*
    // Y = gep X, <... constant index...>
    if (ptrOp instanceof BitCastInst) {
      BitCastInst bci = (BitCastInst) ptrOp;
      if (td != null && !(bci.operand(0) instanceof BitCastInst) &&
          gep.hasAllConstantIndices()) {
        Value gepRes = emitGEPOffset(gep, gep);
        if (!(gepRes instanceof ConstantInt))
          return null;

        ConstantInt offsetVal = (ConstantInt) gepRes;
        long offset = offsetVal.getSExtValue();
        if (offset == 0) {
          // If this GEP instruction doesn't move the pointer, just replace the GEP
          // with a bitcast of the real input to the dest type.
          if (bci.operand(0) instanceof AllocationInst) {
            Instruction i = visitBitCast(bci);
            if (i != null) {
              if (!i.equals(bci)) {
                i.setName(bci.getName());
                bci.eraseFromParent();
                com.replaceInstUsesWith(bci, i);
              }
              return gep;
            }
          }
          Instruction res = new BitCastInst(bci.operand(0), gep.getType(), "bitcast", gep);
          return com.replaceInstUsesWith(gep, res);
        }

        // Otherwise, if the offset is non-zero, we need to find out if there is a
        // field at Offset in 'A's type.  If so, we can pull the cast through the
        // GEP.
        ArrayList<Value> newIndices = new ArrayList<>();
        Type intTy = ((PointerType) bci.operand(0).getType()).getElementType();
        if (findElementAtOffset(intTy, offset, newIndices, td) != null) {
          Instruction newGEP = new GetElementPtrInst(bci.operand(0), newIndices, "gep.new");
          if (newGEP.getType().equals(gep.getType()))
            return gep;
          if (gep.isInBounds())
            ((GetElementPtrInst) newGEP).setIsInBounds(true);

          newGEP.insertBefore(gep);
          Instruction res = new BitCastInst(newGEP, gep.getType(), "bitcast", gep);
          return com.replaceInstUsesWith(gep, res);
        }
      }
    }
    return null;
  }

  private Type findElementAtOffset(Type ty,
                                   long offset,
                                   ArrayList<Value> newIndices,
                                   TargetData td) {
    if (td == null || !ty.isSized()) return null;

    Type intPtrTy = td.getIntPtrType(ty.getContext());
    long firstIdx = 0;
    long tySize = td.getTypeAllocSize(ty);
    if (tySize != 0) {
      firstIdx = offset / tySize;
      offset -= firstIdx * tySize;
      if (offset < 0) {
        --firstIdx;
        offset += tySize;
        Util.assertion(offset == 0);
      }
      Util.assertion(offset < tySize, "out of range");
    }

    newIndices.add(ConstantInt.get(intPtrTy, firstIdx));
    while (offset != 0) {
      if (offset * 8 >= td.getTypeSizeInBits(ty))
        return null;
      if (ty instanceof StructType) {
        StructType sty = (StructType) ty;
        TargetData.StructLayout layout = td.getStructLayout(sty);
        Util.assertion(offset < layout.getSizeInBits(),
            "Offset must stay within the indexed type");
        int elt = layout.getElementContainingOffset(offset);
        newIndices.add(ConstantInt.get(Type.getInt32Ty(ty.getContext()), elt));
        offset -= layout.getElementOffset(elt);
        ty = sty.getElementType(elt);
      } else if (ty instanceof ArrayType) {
        ArrayType aty = (ArrayType) ty;
        long eleSize = td.getTypeAllocSize(aty.getElementType());
        Util.assertion(eleSize != 0, "can't index into zero-sized array");
        newIndices.add(ConstantInt.get(intPtrTy, offset / eleSize));
        offset %= eleSize;
        ty = aty.getElementType();
      } else
        // otherwise, we can't index into the middle of this typeo.
        return null;
    }
    return ty;
  }

  private Value emitGEPOffset(GetElementPtrInst gep,
                              Instruction inst) {
    Type intPtrTy = td.getIntPtrType(gep.getContext());
    GEPTypeIterator gepItr = new GEPTypeIterator(gep);

    Value result = ConstantInt.getNullValue(intPtrTy);
    int intPtrWidth = td.getPointerSizeInBits();
    long ptrSizeMask = ~0L >>> (64 - intPtrWidth);
    CompositeType ct = (CompositeType) gep.getPointerOperandType().getElementType();

    for (int i = 1, e = gep.getNumOfOperands(); i < e && gepItr.hasNext(); i++) {
      Value op = gep.operand(i);
      long size = td.getTypeAllocSize(gepItr.getIndexedType()) & ptrSizeMask;
      if (op instanceof ConstantInt) {
        ConstantInt ci = (ConstantInt) op;
        if (ci.isZero()) continue;

        if (gepItr.getCurType() instanceof StructType) {
          StructType sty = (StructType) gepItr.getCurType();
          size = td.getStructLayout(sty).getElementOffset(ci.getZExtValue());

          if (result instanceof ConstantInt) {
            ConstantInt rc = (ConstantInt) result;
            result = ConstantInt.get(gep.getContext(), rc.getValue().add(new APInt(intPtrWidth, size)));
          } else {
            result = BinaryOperator.createAdd(result, ConstantInt.get(intPtrTy, size),
                gep.getName() + ".offs", gep);
          }
          continue;
        }

        Constant scale = ConstantInt.get(intPtrTy, size);
        Constant oc = ConstantExpr.getIntegerCast(ci, intPtrTy, true);
        scale = ConstantExpr.getMul(oc, scale);
        if (result instanceof Constant)
          result = ConstantExpr.getAdd((Constant) result, scale);
        else {
          // emit an add instruction.
          result = BinaryOperator.createAdd(result, scale, gep.getName() + ".offs", gep);
        }
        continue;
      }
      if (!op.getType().equals(intPtrTy)) {
        if (op instanceof Constant) {
          Constant opC = (Constant) op;
          op = ConstantExpr.getIntegerCast(opC, intPtrTy, true);
        } else
          op = CastInst.createIntegerCast(op, intPtrTy, true,
              op.getName() + ".c", gep);
      }

      if (size != 1) {
        Constant scale = ConstantInt.get(intPtrTy, size);
        if (op instanceof Constant) {
          Constant opC = (Constant) op;
          op = ConstantExpr.getMul(scale, opC);
        } else
          op = BinaryOperator.createMul(scale, op, gep.getName() + ".idx", gep);
      }

      // emit an add instruction.
      if (op instanceof Constant && result instanceof Constant) {
        result = ConstantExpr.getAdd((Constant) result, (Constant) op);
      } else
        result = BinaryOperator.createAdd(result, op, op.getName() + ".add", gep);
    }
    return result;
  }

  @Override
  public Instruction visitPhiNode(User inst) {
    return null;
  }

  @Override
  public Instruction visitSelect(User inst) {
    return null;
  }

  /***
   * <pre>
   * Rank the specified value, order the value ascend from undef, const, unary, other inst.
   * 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
   * </pre>
   * @param val
   * @return
   */
  private int getComplexity(Value val) {
    if (val instanceof UndefValue) return 0;
    else if (val instanceof Constant) return 1;
    else if (val instanceof Instruction) {
      if (BinaryOperator.isNot(val) || BinaryOperator.isNeg(val) || BinaryOperator.isFNeg(val))
        return 3;
      return 4;
    } else if (val instanceof Argument)
      return 3;
    else
      return 2;

  }

  /**
   * Reorder the expression list as the order from most complexity to less complexity.
   * 1. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2)).
   * 2. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2)).
   *
   * @param inst
   * @return
   */
  private boolean simplifyCommutative(BinaryOperator inst) {
    boolean changed = false;
    if (getComplexity(inst.operand(0)) < getComplexity(inst.operand(1)))
      changed = !inst.swapOperands();

    if (!inst.isAssociative()) return changed;
    Value op0 = inst.operand(0), op1 = inst.operand(1);
    if (op0 instanceof BinaryOperator) {
      BinaryOperator binOp0 = (BinaryOperator) op0;
      if (binOp0.getOpcode() == inst.getOpcode()) {
        if (binOp0.operand(1) instanceof ConstantInt) {
          ConstantInt ci1 = (ConstantInt) binOp0.operand(1);
          if (op1 instanceof ConstantInt) {
            Constant foldedCE = ConstantExpr.get(inst.getOpcode(),
                ci1, (Constant) op1);
            inst.setOperand(0, binOp0.operand(0));
            inst.setOperand(1, foldedCE);
            changed = true;
          } else if (op1 instanceof BinaryOperator &&
              ((BinaryOperator) op1).getOpcode() == inst.getOpcode()) {
            BinaryOperator binaryOp1 = (BinaryOperator) op1;
            if (binaryOp1.operand(1) instanceof ConstantInt) {
              ConstantInt ci2 = (ConstantInt) binaryOp1.operand(1);
              inst.setOperand(0, BinaryOperator.create(inst.getOpcode(),
                  binOp0.operand(0), binaryOp1.operand(0), "tmp", inst));
              inst.setOperand(1, ConstantExpr.get(inst.getOpcode(),
                  ci1, ci2));
              changed = true;
            }
          }
        }
      }
    }
    return changed;
  }

  @Override
  public Instruction visitAdd(User inst) {
    BinaryOperator binOps = (BinaryOperator) inst;
    boolean changed = simplifyCommutative(binOps);
    Value lhs = binOps.operand(0), rhs = binOps.operand(1);
    // any + C
    if (rhs instanceof Constant) {
      Constant rhsC = (Constant) rhs;
      // any + undef --> undef.
      if (rhs instanceof UndefValue)
        return com.replaceInstUsesWith(binOps, lhs);
      // X + 0 --> X
      if (rhs.isNullConstant())
        return com.replaceInstUsesWith(binOps, rhs);
      // zext(bool) + C --> bool ? C+1 : C.
      if (rhs instanceof ConstantInt) {
        ConstantInt ci = (ConstantInt) rhs;
        if (lhs instanceof ZExtInst &&
            ((ZExtInst) lhs).operand(0).hasOneUses() &&
            ((ZExtInst) lhs).operand(0).getType().isIntegerTy(1)) {
          Value cond = ((ZExtInst) lhs).operand(0);
          return com.replaceInstUsesWith(binOps, new SelectInst(cond,
              ConstantExpr.getAdd(ci, ConstantInt.getTrue(lhs.getContext())), ci, "", binOps));
        }
      }
      if (lhs instanceof Constant) {
        Constant lhsC = (Constant) lhs;
        return com.replaceInstUsesWith(binOps, ConstantExpr.getAdd(lhsC, rhsC));
      }
      // simplify it with pattern matching technology.
    }
    return null;
  }

  @Override
  public Instruction visitFAdd(User inst) {
    return null;
  }

  @Override
  public Instruction visitSub(User inst) {
    return null;
  }

  @Override
  public Instruction visitFSub(User inst) {
    return null;
  }

  @Override
  public Instruction visitMul(User inst) {
    return null;
  }

  @Override
  public Instruction visitFMul(User inst) {
    return null;
  }

  @Override
  public Instruction visitFDiv(User inst) {
    return null;
  }
}


text:
package twitter4j.util;

import org.junit.jupiter.api.Test;

import java.util.Calendar;
import java.util.Locale;

import static org.junit.jupiter.api.Assertions.assertEquals;

class TimeSpanConverterTest {

    final int second = 1000;
    final int minute = second * 60;
    final int hour = minute * 60;

    TimeSpanConverter converter;

    private void assertTimeSpanString(String expected, long time) {
        assertEquals(expected, converter.toTimeSpanString(time));

    }

    // Beware the 'month' argument follows the Java Calendar standard and is 0-based.
    private long getSpecificLocalDateInMillis(int month, int day) {
        return this.getSpecificLocalDateInMillis((int) this.getCurrentYear(), month, day);
    }

    // Beware the 'month' argument follows the Java Calendar standard and is 0-based.
    private long getSpecificLocalDateInMillis(int year, int month, int day) {
        // Re-create the instance in case these tests are multi-threaded.
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, day);
        return cal.getTimeInMillis();
    }

    private long getCurrentYear() {
        // Re-create the instance in case these tests are multi-threaded.
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.YEAR);
    }

    @Test
    void testItalian() throws Exception {
        converter = new TimeSpanConverter(Locale.ITALIAN);
        assertTimeSpanString("Ora", System.currentTimeMillis() - second);
        assertTimeSpanString("4 secondi fa", System.currentTimeMillis() - second * 4);
        assertTimeSpanString("1 minuto fa", System.currentTimeMillis() - second * 61);
        assertTimeSpanString("3 minuti fa", System.currentTimeMillis() - minute * 3);
        assertTimeSpanString("1 ora fa", System.currentTimeMillis() - hour);
        assertTimeSpanString("3 ore fa", System.currentTimeMillis() - hour * 3);
        assertTimeSpanString("18 dic 09", getSpecificLocalDateInMillis(2009, 11, 18));
    }

    @Test
    void testSpanish() throws Exception {
        Locale[] locales = Locale.getAvailableLocales();
        Locale locale = null;
        for (Locale loc : locales) {
            if ("es".equals(loc.getLanguage())) {
                locale = loc;
            }
        }
        converter = new TimeSpanConverter(locale);
        assertTimeSpanString("Ahora", System.currentTimeMillis() - second);
        assertTimeSpanString("hace 4 segundos", System.currentTimeMillis() - second * 4);
        assertTimeSpanString("hace 1 minuto", System.currentTimeMillis() - second * 61);
        assertTimeSpanString("hace 3 minutos", System.currentTimeMillis() - minute * 3);
        assertTimeSpanString("hace 1 hora", System.currentTimeMillis() - hour);
        assertTimeSpanString("hace 3 horas", System.currentTimeMillis() - hour * 3);
        assertTimeSpanString("18 dic 09", getSpecificLocalDateInMillis(2009, 11, 18));
    }

    @Test
    void testEnglish() throws Exception {
        converter = new TimeSpanConverter(Locale.ENGLISH);
        assertTimeSpanString("now", System.currentTimeMillis() - second);
        assertTimeSpanString("4 seconds ago", System.currentTimeMillis() - second * 4);
        assertTimeSpanString("58 seconds ago", System.currentTimeMillis() - second * 58);
        assertTimeSpanString("1 minute ago", System.currentTimeMillis() - second * 61);
        assertTimeSpanString("3 minutes ago", System.currentTimeMillis() - minute * 3);
        assertTimeSpanString("1 hour ago", System.currentTimeMillis() - hour);
        assertTimeSpanString("3 hours ago", System.currentTimeMillis() - hour * 3);
        assertTimeSpanString("18 Dec 09", getSpecificLocalDateInMillis(2009, 11, 18));
    }

    @Test
    void testFrench() throws Exception {
        converter = new TimeSpanConverter(Locale.FRENCH);
        assertTimeSpanString("Maintenant", System.currentTimeMillis() - second);
        assertTimeSpanString("Il y a 4 secondes", System.currentTimeMillis() - second * 4);
        assertTimeSpanString("Il y a 1 minute", System.currentTimeMillis() - second * 61);
        assertTimeSpanString("Il y a 3 minutes", System.currentTimeMillis() - minute * 3);
        assertTimeSpanString("Il y a 1 heure", System.currentTimeMillis() - hour);
        assertTimeSpanString("Il y a 3 heures", System.currentTimeMillis() - hour * 3);
        assertTimeSpanString("18 déc. 09", getSpecificLocalDateInMillis(2009, 11, 18));
    }

    @Test
    void testGerman() throws Exception {
        converter = new TimeSpanConverter(Locale.GERMAN);
        assertTimeSpanString("Jetzt", System.currentTimeMillis() - second);
        assertTimeSpanString("vor 4 Sekunden", System.currentTimeMillis() - second * 4);
        assertTimeSpanString("vor 1 Minute", System.currentTimeMillis() - second * 61);
        assertTimeSpanString("vor 3 Minuten", System.currentTimeMillis() - minute * 3);
        assertTimeSpanString("vor 1 Stunde", System.currentTimeMillis() - hour);
        assertTimeSpanString("vor 3 Stunden", System.currentTimeMillis() - hour * 3);
        assertTimeSpanString("18 Dez 09", getSpecificLocalDateInMillis(2009, 11, 18));
    }

    @Test
    void testJapanese() throws Exception {
        converter = new TimeSpanConverter(Locale.JAPANESE);
        assertTimeSpanString("今", System.currentTimeMillis() - second);
        assertTimeSpanString("4秒前", System.currentTimeMillis() - second * 4);
        assertTimeSpanString("58秒前", System.currentTimeMillis() - second * 58);
        assertTimeSpanString("1分前", System.currentTimeMillis() - second * 61);
        assertTimeSpanString("3分前", System.currentTimeMillis() - minute * 3);
        assertTimeSpanString("1時間前", System.currentTimeMillis() - hour);
        assertTimeSpanString("3時間前", System.currentTimeMillis() - hour * 3);
        assertTimeSpanString("09年12月18日", getSpecificLocalDateInMillis(2009, 11, 18));
    }
}