text:
"""Tests for `tf.data.Dataset`."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import warnings

from absl.testing import parameterized
import numpy as np

from tensorflow.core.framework import graph_pb2
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.ops import optional_ops
from tensorflow.python.data.ops import readers
from tensorflow.python.data.util import nest
from tensorflow.python.data.util import structure
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.framework import combinations
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 tensor_shape
from tensorflow.python.framework import tensor_spec
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging

class DatasetTest(test_base.DatasetTestBase, parameterized.TestCase):

  @combinations.generate(test_base.default_test_combinations())
  def testAsSerializedGraph(self):
    dataset = dataset_ops.Dataset.range(10)
    graph = graph_pb2.GraphDef().FromString(
        self.evaluate(dataset._as_serialized_graph()))
    self.assertTrue(any([node.op == "RangeDataset" for node in graph.node]))

  def testAsSerializedGraphStateful(self):
    dataset = dataset_ops.Dataset.range(10).map(
        lambda _: random_ops.random_uniform(()))
    with self.assertRaises(errors.FailedPreconditionError):
      self.evaluate(dataset._as_serialized_graph(
          external_state_policy=dataset_ops.ExternalStatePolicy.FAIL))

  @combinations.generate(test_base.default_test_combinations())
  def testAsFunctionWithMap(self):
    if not context.executing_eagerly():
      self.skipTest("Only works executing eagerly")
    with ops.device("CPU"):
      original_dataset = dataset_ops.Dataset.range(5).map(lambda x: x * 2)
      fn = original_dataset._trace_variant_creation()
      variant = fn()

      revived_dataset = dataset_ops._VariantDataset(
          variant, original_dataset.element_spec)
      self.assertDatasetProduces(revived_dataset, range(0, 10, 2))

  @combinations.generate(test_base.default_test_combinations())
  def testAsFunctionWithMapInFlatMap(self):
    if not context.executing_eagerly():
      self.skipTest("Only works executing eagerly")
    with ops.device("CPU"):
      original_dataset = dataset_ops.Dataset.range(5).flat_map(
          lambda x: dataset_ops.Dataset.range(5).map(lambda x: x * 2))
      fn = original_dataset._trace_variant_creation()
      variant = fn()

      revived_dataset = dataset_ops._VariantDataset(
          variant, original_dataset.element_spec)
      self.assertDatasetProduces(revived_dataset, list(original_dataset))

  def checkNumInputs(self, dataset, num_inputs):
    self.assertLen(dataset._inputs(), num_inputs)

  @combinations.generate(test_base.default_test_combinations())
  def testFixedLengthRecordInputs(self):
    dataset = readers.FixedLengthRecordDataset("", 42)
    self.checkNumInputs(dataset, 0)

  @combinations.generate(test_base.default_test_combinations())
  def testFromGeneratorInputs(self):
    def gen():
      yield 42

    dataset = dataset_ops.Dataset.from_generator(gen, dtypes.int32)
    self.checkNumInputs(dataset, 1)

  @combinations.generate(test_base.default_test_combinations())
  def testFromTensorsInputs(self):
    dataset = dataset_ops.Dataset.from_tensors([42])
    self.checkNumInputs(dataset, 0)

  @combinations.generate(test_base.default_test_combinations())
  def testRangeInputs(self):
    dataset = dataset_ops.Dataset.range(10)
    self.checkNumInputs(dataset, 0)

  @combinations.generate(test_base.default_test_combinations())
  def testTextLineInputs(self):
    dataset = readers.TextLineDataset("")
    self.checkNumInputs(dataset, 0)

  @combinations.generate(test_base.default_test_combinations())
  def testTFRecordInputs(self):
    dataset = readers.TFRecordDataset("")
    self.checkNumInputs(dataset, 1)

  @combinations.generate(
      combinations.combine(tf_api_version=1, mode=["eager", "graph"]))
  def testDatasetComplexSourceInputs(self):
    dataset_fn = dataset_ops.Dataset.from_sparse_tensor_slices(
        sparse_tensor.SparseTensor(
            indices=np.array([[0, 0], [1, 0], [2, 0]]),
            values=np.array([0, 0, 0]),
            dense_shape=np.array([3, 1])))
    self.assertEmpty(dataset_fn._inputs())

  def checkUnaryInputs(self, dataset_fn):
    input_dataset = dataset_ops.Dataset.range(0)
    self.assertEqual([input_dataset], dataset_fn(input_dataset)._inputs())

  @combinations.generate(test_base.default_test_combinations())
  def testBatchInputs(self):
    self.checkUnaryInputs(lambda x: x.batch(10))

  @combinations.generate(test_base.default_test_combinations())
  def testCacheInputs(self):
    self.checkUnaryInputs(lambda x: x.cache())

  @combinations.generate(test_base.default_test_combinations())
  def testFilterInputs(self):
    self.checkUnaryInputs(lambda x: x.filter(lambda x: True))

  @combinations.generate(test_base.default_test_combinations())
  def testFlatMapInputs(self):
    self.checkUnaryInputs(
        lambda x: x.flat_map(lambda x: dataset_ops.Dataset.range(0)))

  @combinations.generate(test_base.default_test_combinations())
  def testMapInputs(self):
    self.checkUnaryInputs(lambda x: x.map(lambda x: x))

  @combinations.generate(test_base.default_test_combinations())
  def testPaddedBatchInputs(self):
    self.checkUnaryInputs(lambda x: x.padded_batch(10, []))

  @combinations.generate(test_base.default_test_combinations())
  def testParallelMapInputs(self):
    self.checkUnaryInputs(lambda x: x.map(lambda x: x, num_parallel_calls=2))

  @combinations.generate(test_base.default_test_combinations())
  def testRepeatInputs(self):
    self.checkUnaryInputs(lambda x: x.repeat())

  @combinations.generate(test_base.default_test_combinations())
  def testShuffleInputs(self):
    self.checkUnaryInputs(lambda x: x.shuffle(10))

  @combinations.generate(test_base.default_test_combinations())
  def testSkipInputs(self):
    self.checkUnaryInputs(lambda x: x.skip(1))

  @combinations.generate(test_base.default_test_combinations())
  def testTakeInputs(self):
    self.checkUnaryInputs(lambda x: x.take(1))

  @combinations.generate(test_base.default_test_combinations())
  def testWindowInputs(self):
    self.checkUnaryInputs(lambda x: x.window(10))

  @combinations.generate(test_base.default_test_combinations())
  def testUnaryTransformationInputsApply(self):
    input_dataset = dataset_ops.Dataset.range(0)
    dataset = input_dataset.apply(lambda dataset: dataset.cache())

    self.assertEqual([input_dataset], dataset._inputs())

  def checkInputsWithInterleaveFn(self, dataset_fn, interleave_parallelism):
    input_dataset = dataset_ops.Dataset.range(0)
    dataset = input_dataset.interleave(
        lambda x: dataset_ops.Dataset.range(0),
        cycle_length=2,
        num_parallel_calls=interleave_parallelism)
    self.assertEqual([input_dataset], dataset._inputs())

  @combinations.generate(test_base.default_test_combinations())
  def testParallelInterleaveInputs(self):
    self.checkInputsWithInterleaveFn(lambda: dataset_ops.range(0), 2)

  @combinations.generate(test_base.default_test_combinations())
  def testInterleaveInputs(self):
    self.checkInputsWithInterleaveFn(lambda: dataset_ops.range(0), None)

  @combinations.generate(test_base.default_test_combinations())
  def testNoWarnings(self):
    with test.mock.patch.object(warnings, "warn") as mock_log:
      dataset_ops.Dataset.range(0).interleave(
          lambda x: dataset_ops.Dataset.range(0), cycle_length=2)
      self.assertEmpty(mock_log.call_args_list)

  def checkBinaryInputs(self, dataset_fn):
    input1 = dataset_ops.Dataset.range(0)
    input2 = dataset_ops.Dataset.range(1)
    self.assertEqual([input1, input2], dataset_fn(input1, input2)._inputs())

  @combinations.generate(test_base.default_test_combinations())
  def testConcatenateInputs(self):
    self.checkBinaryInputs(lambda x, y: x.concatenate(y))

  def checkVariadicInputs(self, dataset_fn, input_datasets):
    self.assertEqual(
        nest.flatten(input_datasets),
        dataset_fn(input_datasets)._inputs())

  @combinations.generate(test_base.default_test_combinations())
  def testZipOneInputs(self):
    input_datasets = dataset_ops.Dataset.range(0)
    self.checkVariadicInputs(dataset_ops.Dataset.zip, input_datasets)

  @combinations.generate(test_base.default_test_combinations())
  def testZipNestInputs(self):
    input_datasets = (dataset_ops.Dataset.range(0),
                      (dataset_ops.Dataset.range(1),
                       dataset_ops.Dataset.range(2)))
    self.checkVariadicInputs(dataset_ops.Dataset.zip, input_datasets)

  @combinations.generate(test_base.default_test_combinations())
  def testZipTupleInputs(self):
    input_datasets = (dataset_ops.Dataset.range(0),
                      dataset_ops.Dataset.range(1))
    self.checkVariadicInputs(dataset_ops.Dataset.zip, input_datasets)

  @combinations.generate(test_base.default_test_combinations())
  def testFunctions(self):
    dataset = dataset_ops.Dataset.range(5).map(lambda x: x * 2)
    self.assertLen(dataset._functions(), 1)

  @combinations.generate(test_base.default_test_combinations())
  def testCollectInputs(self):
    ds1 = dataset_ops.Dataset.range(0)
    ds2 = ds1.concatenate(ds1)
    ds3 = dataset_ops.Dataset.zip((ds2, ds1, ds2))

    inputs = []
    queue = [ds3]
    while queue:
      ds = queue[0]
      queue = queue[1:]
      queue.extend(ds._inputs())
      inputs.append(ds)

    self.assertEqual(5, inputs.count(ds1))
    self.assertEqual(2, inputs.count(ds2))
    self.assertEqual(1, inputs.count(ds3))

  def checkDatasetSpec(self, tf_value, expected_element_structure):
    dataset = dataset_ops.Dataset.from_tensors(0).map(lambda _: tf_value)
    dataset_structure = structure.type_spec_from_value(dataset)
    self.assertIsInstance(dataset_structure, dataset_ops.DatasetSpec)

    self.assertTrue(
        structure.are_compatible(
            dataset_ops.get_structure(dataset), expected_element_structure))
    self.assertEqual([dtypes.variant],
                     structure.get_flat_tensor_types(dataset_structure))
    self.assertEqual([tensor_shape.TensorShape([])],
                     structure.get_flat_tensor_shapes(dataset_structure))

    # Assert that the `Dataset` survives a round-trip via _from_tensor_list()
    # and _to_tensor_list().
    round_trip_dataset = dataset_structure._from_tensor_list(
        dataset_structure._to_tensor_list(dataset))

    value = tf_value

    if isinstance(value, dataset_ops.Dataset):
      self.assertDatasetsEqual(value, dataset.flat_map(lambda x: x))
    elif isinstance(value, optional_ops.Optional):
      self.assertDatasetProduces(
          round_trip_dataset.map(lambda opt: opt.get_value()),
          [self.evaluate(value.get_value())],
          requires_initialization=True)
    else:
      self.assertDatasetProduces(
          round_trip_dataset, [self.evaluate(tf_value)],
          requires_initialization=True)

  @combinations.generate(test_base.default_test_combinations())
  def testTensorDatasetSpec(self):
    self.checkDatasetSpec(
        constant_op.constant(37.0), tensor_spec.TensorSpec([], dtypes.float32))

  @combinations.generate(test_base.default_test_combinations())
  def testSparseTensorDatasetSpec(self):
    self.checkDatasetSpec(
        sparse_tensor.SparseTensor(
            indices=[[0]],
            values=constant_op.constant([0], dtype=dtypes.int32),
            dense_shape=[1]), sparse_tensor.SparseTensorSpec([1], dtypes.int32))

  @combinations.generate(test_base.default_test_combinations())
  def testNestDatasetSpec(self):
    self.checkDatasetSpec(
        {
            "a": constant_op.constant(37.0),
            "b": (constant_op.constant(["Foo"]), constant_op.constant("Bar"))
        }, {
            "a":
                tensor_spec.TensorSpec([], dtypes.float32),
            "b": (
                tensor_spec.TensorSpec([1], dtypes.string),
                tensor_spec.TensorSpec([], dtypes.string),
            )
        })

  @combinations.generate(test_base.default_test_combinations())
  def testDatasetDatasetSpec(self):
    self.checkDatasetSpec(
        dataset_ops.Dataset.from_tensor_slices(
            constant_op.constant([1, 2, 3])),
        dataset_ops.DatasetSpec(tensor_spec.TensorSpec([], dtypes.int32)))

  @combinations.generate(test_base.default_test_combinations())
  def testOptionalDatasetSpec(self):
    self.checkDatasetSpec(
        optional_ops.Optional.from_value(37.0),
        optional_ops.OptionalSpec(tensor_spec.TensorSpec([], dtypes.float32)))

  @combinations.generate(
      combinations.combine(tf_api_version=[1], mode=["graph"]))
  def testSkipEagerSameGraphErrorOneShot(self):
    dataset = dataset_ops.Dataset.range(10)
    with ops.Graph().as_default():
      with self.assertRaisesRegexp(ValueError, "must be from the same graph"):
        dataset = dataset.batch(2)

  @combinations.generate(
      combinations.combine(tf_api_version=[1], mode=["graph"]))
  def testSkipEagerSameGraphErrorOneShotSimple(self):
    dataset = dataset_ops.Dataset.range(10)
    with ops.Graph().as_default():
      with test.mock.patch.object(tf_logging, "warning") as mock_log:
        _ = dataset_ops.make_one_shot_iterator(dataset)
        self.assertRegexpMatches(
            str(mock_log.call_args), "Please ensure that all datasets in the "
            "pipeline are created in the same graph as the iterator.")

  @combinations.generate(
      combinations.combine(tf_api_version=[1], mode=["graph"]))
  def testSkipEagerSameGraphErrorInitializable(self):
    dataset = dataset_ops.Dataset.range(10)
    with ops.Graph().as_default():
      with self.assertRaisesRegexp(ValueError, "must be from the same graph"):
        dataset = dataset.batch(2)

  @combinations.generate(
      combinations.times(
          combinations.combine(tf_api_version=[1, 2], mode="eager"),
          combinations.combine(execution_mode=[context.ASYNC, context.SYNC])))
  def testEagerIteration(self, execution_mode):
    with context.execution_mode(execution_mode):
      val = 0
      dataset = dataset_ops.Dataset.range(10)
      for foo in dataset:
        self.assertEqual(val, foo.numpy())
        val += 1

  @combinations.generate(test_base.default_test_combinations())
  def testDatasetAsFunctionArgument(self):

    @def_function.function
    def _uses_dataset(d):
      accumulator = array_ops.zeros([], dtype=dtypes.int64)
      for value in d:
        accumulator += value
      return accumulator

    with ops.device("CPU"):
      first_dataset = dataset_ops.Dataset.range(10)
      self.assertEqual(45, self.evaluate(_uses_dataset(first_dataset)))
      second_dataset = dataset_ops.Dataset.range(11)
      self.assertEqual(55, self.evaluate(_uses_dataset(second_dataset)))
      first_concrete = _uses_dataset.get_concrete_function(first_dataset)
      # The dataset should not be a captured input
      self.assertEmpty(first_concrete.graph.captures)
      # The two datasets have the same structure and so should re-use a trace.
      self.assertIs(first_concrete,
                    _uses_dataset.get_concrete_function(second_dataset))
      # With a different structure we should use a different trace.
      self.assertIsNot(
          first_concrete,
          _uses_dataset.get_concrete_function(
              dataset_ops.Dataset.zip((first_dataset, second_dataset))))

  @combinations.generate(test_base.default_test_combinations())
  def testLimitedRetracing(self):
    trace_count = [0]

    @def_function.function
    def f(ds):
      trace_count[0] += 1
      counter = np.int64(0)
      for elem in ds:
        counter += elem
      return counter

    dataset = dataset_ops.Dataset.range(5)
    dataset2 = dataset_ops.Dataset.range(10)

    for _ in range(10):
      self.assertEqual(self.evaluate(f(dataset)), 10)
      self.assertEqual(self.evaluate(f(dataset2)), 45)
      self.assertEqual(trace_count[0], 1)

  # pylint: disable=g-long-lambda,unnecessary-lambda
  @combinations.generate(test_base.default_test_combinations())
  def testLegacyStructureAPI(self):
    components = (np.array([1, 2, 3], dtype=np.int64), (np.array([4., 5.]),
                                                        np.array([6., 7.])),
                  np.array([8, 9, 10], dtype=np.int64))

    dataset = dataset_ops.Dataset.from_tensors(components)
    self.assertEqual(
        (dtypes.int64, (dtypes.float64, dtypes.float64), dtypes.int64),
        dataset_ops.get_legacy_output_types(dataset))
    self.assertEqual(([3], ([2], [2]), [3]),
                     dataset_ops.get_legacy_output_shapes(dataset))

    dataset = dataset.shuffle(10, 10)
    self.assertEqual(
        (dtypes.int64, (dtypes.float64, dtypes.float64), dtypes.int64),
        dataset_ops.get_legacy_output_types(dataset))
    self.assertEqual(([3], ([2], [2]), [3]),
                     dataset_ops.get_legacy_output_shapes(dataset))

    dataset = dataset.repeat(-1)
    self.assertEqual(
        (dtypes.int64, (dtypes.float64, dtypes.float64), dtypes.int64),
        dataset_ops.get_legacy_output_types(dataset))
    self.assertEqual(([3], ([2], [2]), [3]),
                     dataset_ops.get_legacy_output_shapes(dataset))

    dataset = dataset.filter(lambda x, y, z: True)
    self.assertEqual(
        (dtypes.int64, (dtypes.float64, dtypes.float64), dtypes.int64),
        dataset_ops.get_legacy_output_types(dataset))
    self.assertEqual(([3], ([2], [2]), [3]),
                     dataset_ops.get_legacy_output_shapes(dataset))

    dataset = dataset.take(5)
    self.assertEqual(
        (dtypes.int64, (dtypes.float64, dtypes.float64), dtypes.int64),
        dataset_ops.get_legacy_output_types(dataset))
    self.assertEqual(([3], ([2], [2]), [3]),
                     dataset_ops.get_legacy_output_shapes(dataset))

    dataset = dataset.map(lambda x, y, z: ((x, z), (y[0], y[1])))
    self.assertEqual(
        ((dtypes.int64, dtypes.int64), (dtypes.float64, dtypes.float64)),
        dataset_ops.get_legacy_output_types(dataset))
    self.assertEqual((([3], [3]), ([2], [2])),
                     dataset_ops.get_legacy_output_shapes(dataset))

    dataset = dataset.flat_map(lambda x, y: dataset_ops.Dataset.from_tensors(
        ((x[0], x[1]), (y[0], y[1]))))
    self.assertEqual(
        ((dtypes.int64, dtypes.int64), (dtypes.float64, dtypes.float64)),
        dataset_ops.get_legacy_output_types(dataset))
    self.assertEqual((([3], [3]), ([2], [2])),
                     dataset_ops.get_legacy_output_shapes(dataset))

    dataset = dataset.batch(32)
    self.assertEqual(
        ((dtypes.int64, dtypes.int64), (dtypes.float64, dtypes.float64)),
        dataset_ops.get_legacy_output_types(dataset))
    dataset_output_shapes = dataset_ops.get_legacy_output_shapes(dataset)
    self.assertEqual(
        (([None, 3], [None, 3]), ([None, 2], [None, 2])),
        nest.pack_sequence_as(
            dataset_output_shapes,
            [s.as_list() for s in nest.flatten(dataset_output_shapes)]))

    # Define a separate set of components with matching leading
    # dimension for the from-slices constructor.
    components_for_slices = (np.array([1, 2, 3],
                                      dtype=np.int64), (np.array([4., 5., 6.]),
                                                        np.array([7., 8., 9.])),
                             np.array([10, 11, 12], dtype=np.int64))

    dataset = dataset_ops.Dataset.from_tensor_slices(components_for_slices)
    self.assertEqual(
        (dtypes.int64, (dtypes.float64, dtypes.float64), dtypes.int64),
        dataset_ops.get_legacy_output_types(dataset))
    self.assertEqual(([], ([], []), []),
                     dataset_ops.get_legacy_output_shapes(dataset))

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


text:
package com.nominanuda.zen.stereotype;

import static org.junit.Assert.*;

import org.junit.Test;

public class ScopedSingletonTest {

	@Test
	public void test() {
		ScopedSingletonFactory ssf = ScopedSingletonFactory.getInstance();
		Object appScope1 = new Object();
		Object appScope2 = new Object();
		ScopedSingletonTest sing0 = ssf.buildJvmSingleton(ScopedSingletonTest.class);
		ScopedSingletonTest sing1 = ssf.buildScopedSingleton(appScope1, ScopedSingletonTest.class);
		ScopedSingletonTest sing2 = ssf.buildScopedSingleton(appScope2, ScopedSingletonTest.class);
		assertNotEquals(sing0, sing1);
		assertNotEquals(sing1, sing2);
	}

	@Test
	public void test2() {
		ScopedSingletonFactory ssf = ScopedSingletonFactory.getInstance();
		Object appScope1 = "1samename".substring(1);
		Object appScope2 = "2samename".substring(1);
		ScopedSingletonTest sing01 = ssf.buildJvmSingleton(ScopedSingletonTest.class);
		ScopedSingletonTest sing02 = ssf.buildJvmSingleton(ScopedSingletonTest.class);
		ScopedSingletonTest sing1 = ssf.buildScopedSingleton(appScope1, ScopedSingletonTest.class);
		ScopedSingletonTest sing2 = ssf.buildScopedSingleton(appScope1, ScopedSingletonTest.class);
		assertNotSame(appScope1, appScope2);
		assertEquals(sing01, sing02);
		assertEquals(sing1, sing2);
	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.github.aureliano.evtbridge.input.jdbc;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.aureliano.evtbridge.core.agent.AbstractDataReader;
import com.github.aureliano.evtbridge.core.data.ObjectMapperSingleton;
import com.github.aureliano.evtbridge.core.jdbc.ConnectionPool;
import com.github.aureliano.evtbridge.core.jdbc.JdbcConnectionModel;

public class JdbcDataReader extends AbstractDataReader {

	private JdbcConnectionModel schemaConnection;
	private ResultSet resultSet;
	private int columns;
	private String[] columnNames;

	private static final Logger logger = Logger.getLogger(JdbcDataReader.class);

	public JdbcDataReader() {
		super();
	}

	@Override
	public void initializeResources() {
		this.initialize();
	}

	@Override
	public String readLine() {
		try {
			if (!this.resultSet.next()) {
				return null;
			}

			Map<String, Object> row = new HashMap<String, Object>();

			for (short i = 0; i < this.columns; i++) {
				row.put(this.columnNames[i], this.resultSet.getObject(i + 1));
			}

			return this.parseToJson(row);
		} catch (SQLException ex) {
			throw new JdbcInputException(ex);
		}
	}

	@Override
	public void loadLastExecutionLog(Properties properties) { }

	@Override
	public Map<String, Object> executionLog() {
		return new HashMap<String, Object>();
	}

	@Override
	public void finalizeResources() {
		try {
			logger.info(">>> Closing result set.");
			this.resultSet.close();
		} catch (SQLException ex) {
			throw new JdbcInputException(ex);
		}
	}

	private void initialize() {
		this.schemaConnection = ((JdbcInputConfig) super.inputConfiguration).getConnection();
		this.prepareDataReading();
	}

	private void prepareDataReading() {
		try {
			logger.info("Executing query: " + this.schemaConnection.getSql());
			this.resultSet = ConnectionPool.instance().getConnection(this.schemaConnection)
					.createStatement().executeQuery(this.schemaConnection.getSql());

			ResultSetMetaData metaData = this.resultSet.getMetaData();
			this.columns = metaData.getColumnCount();

			this.columnNames = new String[this.columns];
			for (short i = 0; i < this.columns; i++) {
				this.columnNames[i] = metaData.getColumnLabel(i + 1);
			}
		} catch (SQLException ex) {
			throw new JdbcInputException(ex);
		}
	}

	private String parseToJson(Map<String, Object> map) {
		try {
			return ObjectMapperSingleton.instance().getObjectMapper().writeValueAsString(map);
		} catch (JsonProcessingException ex) {
			throw new JdbcInputException(ex);
		}
	}
}


text:
package com.github.srec.rec.component;

import com.github.srec.command.method.MethodCallEventCommand;
import com.github.srec.rec.EventRecorder;

import javax.swing.*;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import java.awt.*;

import static com.github.srec.util.Utils.createParameterMap;

/**
 * Understands recording internal frame events.
 *
 * @author Vivek Prahlad
 */
public class InternalFrameRecorder extends AbstractComponentRecorder implements InternalFrameListener {

    public InternalFrameRecorder(EventRecorder recorder) {
        super(recorder, JInternalFrame.class);
    }

    void componentShown(Component component) {
        frame(component).addInternalFrameListener(this);
    }

    private JInternalFrame frame(Component component) {
        return (JInternalFrame) component;
    }

    void componentHidden(Component component) {
        frame(component).removeInternalFrameListener(this);
    }

    public void internalFrameOpened(InternalFrameEvent e) {
    }

    public void internalFrameClosing(InternalFrameEvent e) {
        JInternalFrame iframe = e.getInternalFrame();
        recorder.record(new MethodCallEventCommand("iframe_close", iframe, null, createParameterMap("title", iframe.getTitle())));
    }

    public void internalFrameClosed(InternalFrameEvent e) {
    }

    public void internalFrameIconified(InternalFrameEvent e) {
    }

    public void internalFrameDeiconified(InternalFrameEvent e) {
    }

    public void internalFrameActivated(InternalFrameEvent e) {
        JInternalFrame iframe = e.getInternalFrame();
        recorder.record(new MethodCallEventCommand("iframe_activate", iframe, null, createParameterMap("title", iframe.getTitle())));
    }

    public void internalFrameDeactivated(InternalFrameEvent e) {
    }
}


text:
package com.inversoft.passport.domain.api;

import java.util.Locale;

import com.inversoft.json.JacksonConstructor;
import com.inversoft.passport.domain.email.EmailTemplate;

/**
 * @author Brian Pontarelli
 */
public class PreviewRequest {
  public EmailTemplate emailTemplate;

  public Locale locale;

  @JacksonConstructor
  public PreviewRequest() {
  }

  public PreviewRequest(EmailTemplate emailTemplate, Locale locale) {
    this.emailTemplate = emailTemplate;
    this.locale = locale;
  }
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.contextualsearch;

import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.browser.compositor.bottombar.OverlayContentDelegate;
import org.chromium.chrome.browser.compositor.bottombar.OverlayContentProgressObserver;
import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelContent;
import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelContentFactory;
import org.chromium.content.browser.ContentViewCore;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import javax.annotation.Nullable;

/**
 * Implements a fake Contextual Search server, for testing purposes.
 * TODO(donnd): add more functionality to this class once the overall approach has been validated.
 * TODO(donnd): rename this class when we refactor and rename the interface it implements.  Should
 *              be something like ContextualSearchFakeEnvironment.
 */
@VisibleForTesting
class ContextualSearchFakeServer
        implements ContextualSearchNetworkCommunicator, OverlayPanelContentFactory {

    private final ContextualSearchPolicy mPolicy;

    private final ContextualSearchManagerTest mManagerTest;
    private final ContextualSearchNetworkCommunicator mBaseManager;

    private final OverlayContentDelegate mContentDelegate;
    private final OverlayContentProgressObserver mProgressObserver;
    private final ChromeActivity mActivity;

    private final ArrayList<String> mRemovedUrls = new ArrayList<String>();

    private final Map<String, FakeTapSearch> mFakeTapSearches = new HashMap<>();
    private final Map<String, FakeLongPressSearch> mFakeLongPressSearches = new HashMap<>();

    private FakeTapSearch mActiveFakeTapSearch;

    private String mLoadedUrl;
    private int mLoadedUrlCount;

    private String mSearchTermRequested;
    private boolean mShouldUseHttps;

    private boolean mDidEverCallContentViewCoreOnShow;

    //============================================================================================
    // FakeSearch
    //============================================================================================

    /**
     * Abstract class that represents a fake contextual search.
     */
    public abstract class FakeSearch {
        private final String mNodeId;

        /**
         * @param nodeId The id of the node where the touch event will be simulated.
         */
        FakeSearch(String nodeId) {
            mNodeId = nodeId;
        }

        /**
         * Simulates a fake search.
         *
         * @throws InterruptedException
         * @throws TimeoutException
         */
        public abstract void simulate() throws InterruptedException, TimeoutException;

        /**
         * @return The search term that will be used in the contextual search.
         */
        public abstract String getSearchTerm();

        /**
         * @return The id of the node where the touch event will be simulated.
         */
        public String getNodeId() {
            return mNodeId;
        }
    }

    //============================================================================================
    // FakeLongPressSearch
    //============================================================================================

    /**
     * Class that represents a fake long-press triggered contextual search.
     */
    public class FakeLongPressSearch extends FakeSearch {
        private final String mSearchTerm;

        /**
         * @param nodeId The id of the node where the touch event will be simulated.
         * @param searchTerm The expected text that the node should contain.
         */
        FakeLongPressSearch(String nodeId, String searchTerm) {
            super(nodeId);

            mSearchTerm = searchTerm;
        }

        @Override
        public void simulate() throws InterruptedException, TimeoutException {
            mManagerTest.longPressNode(getNodeId());
            mManagerTest.waitForSelectionToBe(mSearchTerm);
        }

        @Override
        public String getSearchTerm() {
            return mSearchTerm;
        }
    }

    //============================================================================================
    // FakeTapSearch
    //============================================================================================

    /**
     * Class that represents a fake tap triggered contextual search.
     */
    public class FakeTapSearch extends FakeSearch {
        private final boolean mIsNetworkUnavailable;
        private final int mResponseCode;
        private final String mSearchTerm;
        private final String mDisplayText;
        private final String mAlternateTerm;
        private final boolean mDoPreventPreload;
        private final int mStartAdjust;
        private final int mEndAdjust;
        private final String mContextLanguage;

        boolean mDidStartResolution;
        boolean mDidFinishResolution;

        /**
         * @param nodeId                The id of the node where the touch event will be simulated.
         * @param isNetworkUnavailable  Whether the network is unavailable.
         * @param responseCode          The HTTP response code of the resolution.
         * @param searchTerm            The resolved search term.
         * @param displayText           The display text.
         * @param alternateTerm         The alternate text.
         * @param doPreventPreload      Whether search preload should be prevented.
         * @param startAdjust           The start adjustment of the selection.
         * @param endAdjust             The end adjustment of the selection.
         * @param contextLanguage       The language of the context determined by the server.
         */
        FakeTapSearch(String nodeId, boolean isNetworkUnavailable, int responseCode,
                      String searchTerm, String displayText, String alternateTerm,
                      boolean doPreventPreload, int startAdjust, int endAdjust,
                      String contextLanguage) {
            super(nodeId);

            mIsNetworkUnavailable = isNetworkUnavailable;
            mResponseCode = responseCode;
            mSearchTerm = searchTerm;
            mDisplayText = displayText;
            mAlternateTerm = alternateTerm;
            mDoPreventPreload = doPreventPreload;
            mStartAdjust = startAdjust;
            mEndAdjust = endAdjust;
            mContextLanguage = contextLanguage;
        }

        @Override
        public void simulate() throws InterruptedException, TimeoutException {
            mActiveFakeTapSearch = this;

            // When a resolution is needed, the simulation does not start until the system
            // requests one, and it does not finish until the simulated resolution happens.
            mDidStartResolution = false;
            mDidFinishResolution = false;

            mManagerTest.clickNode(getNodeId());
            mManagerTest.waitForSelectionToBe(mSearchTerm);

            if (mPolicy.shouldPreviousTapResolve(getBasePageUrl())) {
                // Now wait for the Search Term Resolution to start.
                mManagerTest.waitForSearchTermResolutionToStart(this);

                // Simulate a Search Term Resolution.
                simulateSearchTermResolution();

                // Now wait for the simulated Search Term Resolution to finish.
                mManagerTest.waitForSearchTermResolutionToFinish(this);
            } else {
                mDidFinishResolution = true;
            }
        }

        @Override
        public String getSearchTerm() {
            return mSearchTerm;
        }

        /**
         * Notifies that a Search Term Resolution has started.
         */
        public void notifySearchTermResolutionStarted() {
            mDidStartResolution = true;
        }

        /**
         * @return Whether the Search Term Resolution has started.
         */
        public boolean didStartSearchTermResolution() {
            return mDidStartResolution;
        }

        /**
         * @return Whether the Search Term Resolution has finished.
         */
        public boolean didFinishSearchTermResolution() {
            return mDidFinishResolution;
        }

        /**
         * Simulates a Search Term Resolution.
         */
        private void simulateSearchTermResolution() {
            mManagerTest.runOnMainSync(getRunnable());
        }

        /**
         * @return A Runnable to handle the fake Search Term Resolution.
         */
        private Runnable getRunnable() {
            return new Runnable() {
                @Override
                public void run() {
                    if (!mDidFinishResolution) {
                        handleSearchTermResolutionResponse(
                                mIsNetworkUnavailable, mResponseCode, mSearchTerm, mDisplayText,
                                mAlternateTerm, mDoPreventPreload, mStartAdjust, mEndAdjust,
                                mContextLanguage);

                        mActiveFakeTapSearch = null;
                        mDidFinishResolution = true;
                    }
                }
            };
        }
    }

    //============================================================================================
    // OverlayPanelContentWrapper
    //============================================================================================

    /**
     * A wrapper around OverlayPanelContent to be used during tests.
     */
    public class OverlayPanelContentWrapper extends OverlayPanelContent {
        OverlayPanelContentWrapper(OverlayContentDelegate contentDelegate,
                OverlayContentProgressObserver progressObserver, ChromeActivity activity) {
            super(contentDelegate, progressObserver, activity);
        }

        @Override
        public void loadUrl(String url, boolean shouldLoadImmediately) {
            mLoadedUrl = url;
            mLoadedUrlCount++;
            super.loadUrl(url, shouldLoadImmediately);
        }

        @Override
        public void removeLastHistoryEntry(String url, long timeInMs) {
            // Override to prevent call to native code.
            mRemovedUrls.add(url);
        }

        @Override
        protected ContentViewCore createContentViewCore(ChromeActivity activity) {
            return new ContentViewCoreWrapper(activity);
        }
    }

    //============================================================================================
    // ContentViewCoreWrapper
    //============================================================================================

    /**
     * A wrapper around ContentViewCore to be used during tests.
     */
    public class ContentViewCoreWrapper extends ContentViewCore {
        private boolean mIsVisible;

        ContentViewCoreWrapper(ChromeActivity activity) {
            super(activity);
        }

        @Override
        public void destroy() {
            super.destroy();
            mIsVisible = false;
        }

        @Override
        public void onShow() {
            super.onShow();
            mIsVisible = true;
            mDidEverCallContentViewCoreOnShow = true;
        }

        @Override
        public void onHide() {
            super.onHide();
            mIsVisible = false;
        }

        /**
         * @return Whether the ContentViewCore is visible.
         */
        public boolean isVisible() {
            return mIsVisible;
        }
    }

    //============================================================================================
    // ContextualSearchFakeServer
    //============================================================================================

    /**
     * Constructs a fake Contextual Search server that will callback to the given baseManager.
     * @param baseManager The manager to call back to for server responses.
     */
    @VisibleForTesting
    ContextualSearchFakeServer(ContextualSearchPolicy policy,
            ContextualSearchManagerTest managerTest,
            ContextualSearchNetworkCommunicator baseManager,
            OverlayContentDelegate contentDelegate,
            OverlayContentProgressObserver progressObserver,
            ChromeActivity activity) {
        mPolicy = policy;

        mManagerTest = managerTest;
        mBaseManager = baseManager;

        mContentDelegate = contentDelegate;
        mProgressObserver = progressObserver;
        mActivity = activity;
    }

    @Override
    public OverlayPanelContent createNewOverlayPanelContent() {
        return new OverlayPanelContentWrapper(mContentDelegate, mProgressObserver, mActivity);
    }

    /**
     * @return The search term requested, or {@code null} if no search term was requested.
     */
    @VisibleForTesting
    String getSearchTermRequested() {
        return mSearchTermRequested;
    }

    /**
     * @return the loaded search result page URL if any was requested.
     */
    @VisibleForTesting
    String getLoadedUrl() {
        return mLoadedUrl;
    }

    /**
     * @return The number of times we loaded a URL in the Content View.
     */
    @VisibleForTesting
    int getLoadedUrlCount() {
        return mLoadedUrlCount;
    }

    /**
     * Sets whether to return an HTTPS URL instead of HTTP, from {@link #getBasePageUrl}.
     */
    @VisibleForTesting
    void setShouldUseHttps(boolean setting) {
        mShouldUseHttps = setting;
    }

    /**
     * @return Whether onShow() was ever called for the current {@code ContentViewCore}.
     */
    @VisibleForTesting
    boolean didEverCallContentViewCoreOnShow() {
        return mDidEverCallContentViewCoreOnShow;
    }

    /**
     * Resets the fake server's member data.
     */
    @VisibleForTesting
    void reset() {
        mLoadedUrl = null;
        mSearchTermRequested = null;
        mShouldUseHttps = false;
        mLoadedUrlCount = 0;
    }

    //============================================================================================
    // History Removal Helpers
    //============================================================================================

    /**
     * @param url The URL to be checked.
     * @return Whether the given URL was removed from history.
     */
    public boolean hasRemovedUrl(String url) {
        return mRemovedUrls.contains(url);
    }

    //============================================================================================
    // ContextualSearchNetworkCommunicator
    //============================================================================================

    @Override
    public void startSearchTermResolutionRequest(String selection) {
        mLoadedUrl = null;
        mSearchTermRequested = selection;

        if (mActiveFakeTapSearch != null) {
            mActiveFakeTapSearch.notifySearchTermResolutionStarted();
        }
    }

    @Override
    public void handleSearchTermResolutionResponse(boolean isNetworkUnavailable, int responseCode,
            String searchTerm, String displayText, String alternateTerm, boolean doPreventPreload,
            int selectionStartAdjust, int selectionEndAdjust, String contextLanguage) {
        mBaseManager.handleSearchTermResolutionResponse(isNetworkUnavailable, responseCode,
                searchTerm, displayText, alternateTerm, doPreventPreload, selectionStartAdjust,
                selectionEndAdjust, contextLanguage);
    }

    @Override
    @Nullable public URL getBasePageUrl() {
        URL baseUrl = mBaseManager.getBasePageUrl();
        if (mShouldUseHttps && baseUrl != null) {
            try {
                return new URL(baseUrl.toString().replace("http://", "https://"));
            } catch (MalformedURLException e) {
                // TODO(donnd): Auto-generated catch block
                e.printStackTrace();
            }
        }
        return baseUrl;
    }

    //============================================================================================
    // Fake Searches Helpers
    //============================================================================================

    /**
     * Register fake searches that can be used in tests. Each fake search takes a node ID, which
     * represents the DOM node that will be touched. The node ID is also used as an ID for the
     * fake search of a given type (LongPress or Tap). This means that if you need different
     * behaviors you need to add new DOM nodes with different IDs in the test's HTML file.
     */
    public void registerFakeSearches() {
        registerFakeLongPressSearch(new FakeLongPressSearch("search", "Search"));
        registerFakeLongPressSearch(new FakeLongPressSearch("term", "Term"));
        registerFakeLongPressSearch(new FakeLongPressSearch("resolution", "Resolution"));

        registerFakeTapSearch(new FakeTapSearch("search", false, 200,
                "Search", "Search", "alternate-term", false, 0, 0, ""));
        registerFakeTapSearch(new FakeTapSearch("term", false, 200,
                "Term", "Term", "alternate-term", false, 0, 0, ""));
        registerFakeTapSearch(new FakeTapSearch("resolution", false, 200,
                "Resolution", "Resolution", "alternate-term", false, 0, 0, ""));
        registerFakeTapSearch(new FakeTapSearch("german", false, 200,
                "Deutsche", "Deutsche", "alternate-term", false, 0, 0, "de"));
    }

    /**
     * @param id The ID of the FakeLongPressSearch.
     * @return The FakeLongPressSearch with the given ID.
     */
    public FakeLongPressSearch getFakeLongPressSearch(String id) {
        return mFakeLongPressSearches.get(id);
    }

    /**
     * @param id The ID of the FakeTapSearch.
     * @return The FakeTapSearch with the given ID.
     */
    public FakeTapSearch getFakeTapSearch(String id) {
        return mFakeTapSearches.get(id);
    }

    /**
     * Register the FakeLongPressSearch.
     * @param fakeSearch The FakeLongPressSearch to be registered.
     */
    private void registerFakeLongPressSearch(FakeLongPressSearch fakeSearch) {
        mFakeLongPressSearches.put(fakeSearch.getNodeId(), fakeSearch);
    }

    /**
     * Register the FakeTapSearch.
     * @param fakeSearch The FakeTapSearch to be registered.
     */
    private void registerFakeTapSearch(FakeTapSearch fakeSearch) {
        mFakeTapSearches.put(fakeSearch.getNodeId(), fakeSearch);
    }
}


text: module.exports = exports = (process.env.NODE_ENV || "DEVELOPMENT").toUpperCase();


text:
Dotterbot
=========

2014 Dotterbot Java Code


text:
 <!-- * Copyright (C) 2022 Google Inc.
 *
 * 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. -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example.gcpsupport</groupId>
  <artifactId>cloud-client</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>cloud-client</name>
  <url>https://cloud.google.com/support/docs/reference/rest</url>

  <!--
    The parent pom defines common style checks and testing strategies for our samples.
    Removing or replacing it should not affect the execution of the samples in anyway.
  -->
  <parent>
    <groupId>com.google.cloud.samples</groupId>
    <artifactId>shared-configuration</artifactId>
    <version>1.2.0</version>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>1.33.2</version>
    </dependency>

    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-cloudsupport</artifactId>
      <version>v2beta-rev20211103-1.32.1</version>
    </dependency>

    <dependency>
      <groupId>com.google.auth</groupId>
      <artifactId>google-auth-library-oauth2-http</artifactId>
      <version>1.4.0</version>
    </dependency>

  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


text:
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"

"""
Verify that we execute TeX in a subdirectory (if that's where the document
resides) by checking that all the auxiliary files get created there and
not in the top-level directory. Test this when variantDir is used
Add use of \include and \includegraphics from within the included file

Also check that we find files

Test case courtesy Joel B. Mohler.
"""

import TestSCons

test = TestSCons.TestSCons()

#test.verbose_set(2)

latex = test.where_is('latex')
if not latex:
    test.skip_test("Could not find 'latex'; skipping test.\n")

pdflatex = test.where_is('pdflatex')
if not pdflatex:
    test.skip_test("Could not find 'pdflatex'; skipping test.\n")

test.subdir('docs')
test.subdir(['docs','content'])
test.subdir(['docs','fig'])

test.write('SConstruct', """\
import os
env = Environment(TOOLS = ['tex', 'pdftex'])

env.VariantDir('build', 'docs', duplicate=0)
pdf = env.PDF('build/main.tex')
""")

test.write(['docs','main.tex'],
r"""\documentclass{article}
\usepackage{makeidx}
\makeindex
\begin{document}
Hi there.
\index{info}
\include{content/chapter}
\printindex{}
\end{document}
""")

test.write(['docs','content','chapter.tex'], """\
Sub-document 1
\input{content/subchap}

""")

test.write(['docs','content','subchap.tex'], """\
Sub-chapter 2

""")

#test.run(arguments = '.')
#test.run(arguments = '.', stderr=None, stdout=None)

# next line tests that side effect nodes get disambiguated
# and their directories created in a variantDir before
# the builder tries to populate them and fails
test.run(arguments = 'build/main.pdf', stderr=None, stdout=None)

test.must_exist(['build', 'main.aux'])
test.must_exist(['build', 'main.fls'])
test.must_exist(['build', 'main.idx'])
test.must_exist(['build', 'main.ilg'])
test.must_exist(['build', 'main.ind'])
test.must_exist(['build', 'main.log'])
test.must_exist(['build', 'main.pdf'])

test.must_exist(['build', 'content', 'chapter.aux'])

test.must_not_exist('main.aux')
test.must_not_exist('main.dvi')
test.must_not_exist('main.idx')
test.must_not_exist('main.ilg')
test.must_not_exist('main.ind')
test.must_not_exist('main.log')
test.must_not_exist('main.pdf')

test.must_not_exist(['docs', 'main.aux'])
test.must_not_exist(['docs', 'main.dvi'])
test.must_not_exist(['docs', 'main.idx'])
test.must_not_exist(['docs', 'main.ilg'])
test.must_not_exist(['docs', 'main.ind'])
test.must_not_exist(['docs', 'main.log'])
test.must_not_exist(['docs', 'main.pdf'])

test.must_not_exist(['docs', 'content', 'main.aux'])
test.must_not_exist(['docs', 'content', 'main.dvi'])
test.must_not_exist(['docs', 'content', 'main.idx'])
test.must_not_exist(['docs', 'content', 'main.ilg'])
test.must_not_exist(['docs', 'content', 'main.ind'])
test.must_not_exist(['docs', 'content', 'main.log'])
test.must_not_exist(['docs', 'content', 'main.pdf'])

test.must_not_exist(['docs', 'content', 'chapter.aux'])

test.up_to_date(arguments = '.', stderr=None, stdout=None)

test.write(['docs','content', 'subchap.tex'], """\
Sub-document 2a
""")

test.not_up_to_date(arguments = '.')
#test.up_to_date(arguments = '.', stderr=None, stdout=None)

test.pass_test()

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


text:
Enter a city to see the current weather.

Command: show <city> weather

Output: "<city> is currently <temp>°F <slack emoji>"

**Configuration**
- Obtain an API key at http://openweathermap.org/faq
- Once obtained, set the environment variable OPEN_WEATHER_APP_ID to your API key
- `export OPEN_WEATHER_APP_ID='MYAPIKEY'`


text:
var mpd = require('mpd'),
    cmd = mpd.cmd
var mpdclient = mpd.connect({
  port: 6600,
  host: '192.168.0.10',
});
var redis = require("redis");
redisclient = redis.createClient();

GLOBAL.app = {};
app.uploadFilePath = "/home/tobi/dev/sandbox/nodempd/webapp/img/photo/";
app.mpd = mpdclient;
app.redis = redisclient;
app.playlist = require("./model/playlist.js");
app.player = require("./model/player.js");
app.search = require("./model/search.js");
app.wishlist = require("./model/wishlist.js");
app.fileUploadCtrl = require("./controller/fileuploadctrl.js");
app.photowishlist = require("./model/photowishlist.js");
app.photolist = require("./model/photolist.js");

app.http = require("./http.js");
app.socket = app.http.socketio;

var Song = require("./model/song.js");

mpdclient.on('ready', function() {

	app.playlist.loadPlaylist();
	app.player.loadPlayerInfo();
	app.wishlist.generateGlobalWishlist();

});
mpdclient.on('system', function(name) {
  //console.log("update", name);
	if (name === "playlist") {
		app.playlist.loadPlaylist();
	}
	else if (name === "player") {
		//app.player.loadPlayerInfo();
	}
});
mpdclient.on('system-player', function() {
  console.log("SYSTEM-PLAYER-UPDATE");
  app.player.loadPlayerInfo();
});

process.on('uncaughtException', function(err) {
  console.log(err);
});


text:
package org.apache.bcel.classfile;

import  org.apache.bcel.Constants;
import  java.io.*;

/**
 * This class is derived from the abstract
 * Constant class
 * and represents a reference to a String object.
 *
 * @version $Id: ConstantString.java,v 1.2 2006/08/22 15:33:21 andos Exp $
 * @author  M. Dahm
 * @see     Constant
 */
public final class ConstantString extends Constant implements ConstantObject {
  /**
	 *
	 */
	private static final long serialVersionUID = 5472320814406906117L;
private int string_index; // Identical to ConstantClass except for this name

  /**
   * Initialize from another object.
   */
  public ConstantString(ConstantString c) {
    this(c.getStringIndex());
  }
  /**
   * Initialize instance from file data.
   *
   * @param file Input stream
   * @throws IOException
   */
  ConstantString(DataInputStream file) throws IOException
  {
    this((int)file.readUnsignedShort());
  }
  /**
   * @param string_index Index of Constant_Utf8 in constant pool
   */
  public ConstantString(int string_index)
  {
    super(Constants.CONSTANT_String);
    this.string_index = string_index;
  }
  /**
   * Called by objects that are traversing the nodes of the tree implicitely
   * defined by the contents of a Java class. I.e., the hierarchy of methods,
   * fields, attributes, etc. spawns a tree of objects.
   *
   * @param v Visitor object
   */
  public void accept(Visitor v) {
    v.visitConstantString(this);
  }
  /**
   * Dump constant field reference to file stream in binary format.
   *
   * @param file Output file stream
   * @throws IOException
   */
  public final void dump(DataOutputStream file) throws IOException
  {
    file.writeByte(tag);
    file.writeShort(string_index);
  }
  /**
   * @return Index in constant pool of the string (ConstantUtf8).
   */
  public final int getStringIndex() { return string_index; }
  /**
   * @param string_index.
   */
  public final void setStringIndex(int string_index) {
    this.string_index = string_index;
  }
  /**
   * @return String representation.
   */
  public final String toString()
  {
    return super.toString() + "(string_index = " + string_index + ")";
  }

  /** @return String object
   */
  public Object getConstantValue(ConstantPool cp) {
    Constant c = cp.getConstant(string_index, Constants.CONSTANT_Utf8);
    return ((ConstantUtf8)c).getBytes();
  }

  /** @return dereferenced string
   */
  public String getBytes(ConstantPool cp) {
    return (String)getConstantValue(cp);
  }
}


text:
def cmd_line_count(ensoapi):
    """ Count lines in selected text """
    seldict = ensoapi.get_selection()
    ensoapi.display_message( "Selection is %s lines." %
                             len(seldict.get("text","").splitlines()) )

def cmd_character_count(ensoapi):
    """ Count characters in selected text """
    text = ensoapi.get_selection().get("text", "").strip()
    if not text:
        ensoapi.display_message( "No selection." )
    ensoapi.display_message( "%d characters." % len(text) )

def cmd_uppercase(ensoapi):
    """ Uppercase selected text """
    seldict = ensoapi.get_selection()
    text = seldict.get("text", "")
    if not text:
        ensoapi.display_message("No selection!")
    else:
        ensoapi.set_selection({"text":text.upper()})

def cmd_lowercase(ensoapi):
    """ Lowercase selected text """
    seldict = ensoapi.get_selection()
    text = seldict.get("text", "")
    if not text:
        ensoapi.display_message("No selection!")
    else:
        ensoapi.set_selection({"text":text.lower()})

def cmd_titlecase(ensoapi):
    """ Titlecase selected text """
    seldict = ensoapi.get_selection()
    text = seldict.get("text", "")
    if not text:
        ensoapi.display_message("No selection!")
    else:
        ensoapi.set_selection({"text":text.title()})

def cmd_unaccent(ensoapi):
    """ Unaccent (normalize) selected text """
    import unicodedata

    seldict = ensoapi.get_selection()
    text = seldict.get("text", "")
    if not text:
        ensoapi.display_message("No selection!")
    else:
        text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
        ensoapi.set_selection({"text": text})

def cmd_datetime(ensoapi):
    """ Insert short datetime string in the form yymmdd-HHMMss """
    from time import localtime, strftime
    dt = strftime("%y%m%d-%H%M%S", localtime())
    ensoapi.set_selection(dt)

def cmd_unquote_url(ensoapi):
    """ Unquote URL """
    import urllib
    seldict = ensoapi.get_selection()
    text = seldict.get("text", "")
    if not text:
        ensoapi.display_message("No selection!")
    else:
        text = urllib.unquote(text)
        ensoapi.set_selection({"text": text})


text:
set -e

# Include definitions of dataset and tuning related variables.
source "$(dirname $0)/../lib/setup.sh"
source_lib "config/common.sh"
source_lib "config/tuning.sh"
source_lib "config/ptb_word_rmsprop.sh"

# Model hyperparameters

num_params=$(million 10)
share_input_and_output_embeddings=true

# Evaluation hyperparameters

eval_softmax_temperature=-0.8

# Tuning parameters

num_workers=60

# Start a number of tuning studies, setting model specific parameters.

model="lstm"
tie_forget_and_input_gates=false
forget_bias=1.0
num_layers=1

tuneables="learning_rate,l2_penalty,
  input_dropout,inter_layer_dropout,state_dropout,
  output_dropout,input_embedding_ratio"
name="$(default_name)_${model}_d${num_layers}"
source_lib "run.sh" "$@"


text:
describe("String editor dialog", function() {
  describe("Its editable", function() {
    var dialog;
    beforeEach(function() {
      dialog = new cdb.admin.EditStringDialog({
        el: $('<div>'),
        initial_value: "jamón",
        readOnly: false
      });
      dialog.ok = function() {};
      dialog.cancel = function() {};
      dialog.hide = function() {};
      spyOn(dialog, 'ok');
      spyOn(dialog, 'cancel');
      spyOn(dialog, 'hide');
    });

    it("string dialog should work when change the text", function() {
      dialog.open();
      dialog.$el.find("textarea").val("jam");
      dialog.$el.find("a.ok").click();
      expect(dialog.hide).toHaveBeenCalled();
      expect(dialog.ok).toHaveBeenCalled();
    });

  })
  describe("Its not editable", function() {
    var dialog;
    beforeEach(function() {
      dialog = new cdb.admin.EditStringDialog({
        el: $('<div>'),
        initial_value: "jamón",
        readOnly: true
      });
      dialog.cancel = function() {};
      dialog.hide = function() {};
      spyOn(dialog, 'cancel');
      spyOn(dialog, 'hide');
    });

    it("should not contain any ok button", function() {
      expect(dialog.$el.find("a.ok").length).toBeFalsy();
    })

    it("textarea should not be editable", function() {
      expect(dialog.$el.find("textarea").attr('disabled')).toBeTruthy();
    });

    it("textarea should close when button clicked", function() {
      dialog.open();
      dialog.$el.find(".cancel").click();
      expect(dialog.cancel).toHaveBeenCalled();
    });

  })

});


text:
class A:
    pass

a = A()
print(a.f<caret>oo)

def func(c):
    x = A() if c else None
    return x.foo

# Sentinel reference to make sure that other warnings are still present
<error descr="Unresolved reference 'UNRESOLVED'">UNRESOLVED</error>


text:
package cd.go.authentication.ldap;

import cd.go.apacheds.ApacheDsLdapClient;
import cd.go.authentication.ldap.model.LdapConfiguration;
import cd.go.framework.ldap.JNDILdapClient;

import static cd.go.authentication.ldap.LdapPlugin.LOG;
import static cd.go.authentication.ldap.PluginSystemProperty.useJNDIClient;

public class LdapFactory {

    public LdapClient ldapForConfiguration(LdapConfiguration configuration) {
        boolean useJndiClient = useJNDIClient();

        if (useJndiClient) {
            LOG.debug("Using JDNI based ldap client as user has specified system property 'use.jndi.ldap.client=true'");
            return new JNDILdapClient(configuration);
        }

        LOG.debug("Using apache ds ldap client.");
        return new ApacheDsLdapClient(configuration);
    }
}


text:
package monocle.macros.internal

trait MacrosCompatibility {
  type Context = scala.reflect.macros.blackbox.Context

  def getDeclarations(c: Context)(tpe: c.universe.Type): c.universe.MemberScope =
    tpe.decls

  def getParameterLists(c: Context)(method: c.universe.MethodSymbol): List[List[c.universe.Symbol]] =
    method.paramLists

  def getDeclaration(c: Context)(tpe: c.universe.Type, name: c.universe.Name): c.universe.Symbol =
    tpe.decl(name)

  def createTermName(c: Context)(name: String): c.universe.TermName =
    c.universe.TermName(name)

  def createTypeName(c: Context)(name: String): c.universe.TypeName =
    c.universe.TypeName(name)

  def resetLocalAttrs(c: Context)(tree: c.Tree): c.Tree =
    c.untypecheck(tree)

  def getTermNames(c: Context): c.universe.TermNamesApi =
    c.universe.termNames

  def companionTpe(c: Context)(tpe: c.universe.Type): c.universe.Symbol =
    tpe.typeSymbol.companion
}


text:
import initSourcegraph from './index';

/**
 * Load sourcegraph in it's own listener so that it's isolated from failures.
 */
document.addEventListener('DOMContentLoaded', initSourcegraph);


text:
package com.lightcrafts.ui.editor;

import com.lightcrafts.model.CropBounds;
import com.lightcrafts.model.Engine;
import com.lightcrafts.ui.crop.CropListener;
import com.lightcrafts.ui.crop.CropMode;
import com.lightcrafts.ui.rotate.RotorListener;
import com.lightcrafts.ui.rotate.RotorMode;
import com.lightcrafts.ui.rotate.RotorControl;
import com.lightcrafts.utils.xml.XMLException;
import com.lightcrafts.utils.xml.XmlNode;

import static com.lightcrafts.ui.editor.Locale.LOCALE;

import javax.swing.*;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.UndoableEdit;
import javax.swing.undo.UndoableEditSupport;
import java.awt.event.ActionEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.*;

// Logic for crop and rotate: undo/redo, save/restore, and Engine interaction.

class CropRotateManager implements RotorListener {

    private CropMode rotorMode;     // A CropMode with its rotate-only flag set
    private CropMode cropMode;

    private RotorMode hiddenRotorMode;  // Legacy class, for 90-degree actions

    private CropBounds bounds;
    private boolean hasInvertedAspect;  // At rotate-reset, maybe invert bounds

    private Engine engine;
    private XFormModel xform;

    private UndoableEditSupport undo;

    private Editor editor;

    public void setEditor( Editor editor ) {
        this.editor = editor;
        hiddenRotorMode.setEditor( editor );
    }

    private class LocalCropListener implements CropListener {

        LocalCropListener( String s ) {
            m_opName = s;
        }

        public void cropCommitted(CropBounds crop) {
            CropBounds newBounds = (crop != null) ? crop : new CropBounds();
            // Don't allow rotations past 45 degrees through the crop mode.
            newBounds = limitRotation(newBounds);
            engine.setCropBounds(newBounds);
            double angle = newBounds.getAngle();
            // Note this sign change:
            hiddenRotorMode.setAngle(- angle);
            // The rotate package applies the convention that positive angles
            // are positive in screen coordinates, meaning clockwise on the
            // screen, which is the opposite of the convention in CropBounds.
            xform.update();
            postEdit(newBounds, LOCALE.get( m_opName + "EditName"), true );
        }

        public void unCrop() {
            CropBounds newBounds = getUncroppedBounds();
            engine.setCropBounds(newBounds);
            xform.update();
            // This method gets called when crop and rotate modes are entered,
            // to reveal the whole image.  We used to post an insignificant
            // undoable edit at this time, but it's not necessary for undo
            // and redo to work, and it has the bad side effect of leaving the
            // image uncropped when a crop is undone.
//            postEdit(newBounds, LOCALE.get("Un" + m_opName + "EditName"), false );
        }

        private final String m_opName;
    }

    CropRotateManager(Engine engine, XFormModel xform) {
        this.engine = engine;
        this.xform = xform;
        rotorMode = new CropMode(true);
        cropMode = new CropMode(false);
        hiddenRotorMode = new RotorMode();
        bounds = new CropBounds();
        undo = new UndoableEditSupport();
        cropMode.addCropListener( new LocalCropListener( "Crop" ) );
        rotorMode.addCropListener( new LocalCropListener( "Rotate" ) );
        hiddenRotorMode.addRotorListener(this);
    }

    CropMode getRotorMode() {
        return rotorMode;
    }

    CropMode getCropMode() {
        return cropMode;
    }

    Action getLeftAction() {
        // RotorControl control = hiddenRotorMode.getControl();
        // return control.getLeftAction();
        return new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                final double increment =
                        (bounds.isFlippedHorizontally() != bounds.isFlippedVertically())
                        ? -Math.PI / 2 : Math.PI / 2;
                final double newAngle = bounds.getAngle() + increment;
                final CropBounds newBounds = getNewBounds(newAngle, true);
                updateCropBounds(newBounds);
            }
        };
    }

    Action getRightAction() {
        // RotorControl control = hiddenRotorMode.getControl();
        // return  control.getRightAction();
        return new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                final double increment =
                        (bounds.isFlippedHorizontally() != bounds.isFlippedVertically())
                                ? Math.PI / 2 : -Math.PI / 2;
                final double newAngle = bounds.getAngle() + increment;
                final CropBounds newBounds = getNewBounds(newAngle, true);
                updateCropBounds(newBounds);
            }
        };
    }

    Action getHorizontalAction() {
        return new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                final CropBounds newBounds = bounds.flip(true, false);
                updateCropBounds(newBounds);
            }
        };
    }

    Action getVerticalAction() {
        return new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                final CropBounds newBounds = bounds.flip(false, true);
                updateCropBounds(newBounds);
            }
        };
    }

    void addUndoableEditListener(UndoableEditListener listener) {
        undo.addUndoableEditListener(listener);
    }

    void removeUndoableEditListener(UndoableEditListener listener) {
        undo.removeUndoableEditListener(listener);
    }

    public void angleChanged(
        double angle, boolean isChanging, boolean isNinetyDegrees
    ) {
        // Note this sign change:
        angle = - angle;
        // The rotate package applies the convention that positive angles
        // are positive in screen coordinates, meaning clockwise on the
        // screen, which is the opposite of the convention in CropBounds.

        if (! isChanging) {
            final CropBounds newBounds = getNewBounds(angle, isNinetyDegrees);
            updateCropBounds(newBounds);
        }
    }

    private void updateCropBounds(CropBounds newBounds) {
        if (editor != null) {
            editor.setMode(EditorMode.ARROW);
        }
        engine.setCropBounds(newBounds);
        if (! newBounds.isAngleOnly()) {
            cropMode.setCrop(newBounds);
        }
        xform.update();
        postEdit(newBounds, LOCALE.get("RotateEditName"), true );
    }

    public void angleReset() {
        angleChanged(0, false, hasInvertedAspect);
    }

    private CropBounds getNewBounds(double angle, boolean invertAspect) {
        final CropBounds newBounds;
        if (invertAspect) {
            hasInvertedAspect = ! hasInvertedAspect;
            newBounds = bounds.createInvertedAspect();
        } else {
            newBounds = bounds.clone();
        }
        return newBounds.setAngle(angle);
    }

    private void postEdit( final CropBounds newBounds, final String name,
                           final boolean significant ) {
        final CropBounds oldBounds = bounds;
        bounds = newBounds;
        UndoableEdit edit = new AbstractUndoableEdit() {
            public String getPresentationName() {
                return name;
            }
            public void undo() {
                super.undo();
                bounds = oldBounds;
                engine.setCropBounds(bounds);
                xform.update();
                // Note this sign change:
                hiddenRotorMode.setAngle(- bounds.getAngle());
                // The rotate package applies the convention that positive angles
                // are positive in screen coordinates, meaning clockwise on the
                // screen, which is the opposite of the convention in CropBounds.
                cropMode.setCrop(bounds);
            }
            public void redo() {
                super.redo();
                bounds = newBounds;
                engine.setCropBounds(bounds);
                xform.update();
                // Note this sign change:
                hiddenRotorMode.setAngle(- bounds.getAngle());
                // The rotate package applies the convention that positive angles
                // are positive in screen coordinates, meaning clockwise on the
                // screen, which is the opposite of the convention in CropBounds.
                cropMode.setCrop(bounds);
            }
            public boolean isSignificant() {
                return significant;
            }
        };
        undo.postEdit(edit);
    }

    // Compare the angle in the given CropBounds with the current angle in
    // our member bounds, and if the angle has changed by more than
    // 45 degrees, then reinterpret the crop as a different crop with a
    // closer angle and maybe transposed.
    private CropBounds limitRotation(CropBounds crop) {
        double oldAngle = (bounds != null) ? bounds.getAngle() : 0;
        double newAngle = (crop != null) ? crop.getAngle() : 0;
        while (newAngle - oldAngle > Math.PI / 4) {
            Point2D center = crop.getCenter();
            double width = crop.getWidth();
            double height = crop.getHeight();
            double angle = crop.getAngle();
            crop = new CropBounds(center, height, width, angle - Math.PI / 2);
            newAngle = crop.getAngle();
        }
        while (newAngle - oldAngle < - Math.PI / 4) {
            Point2D center = crop.getCenter();
            double width = crop.getWidth();
            double height = crop.getHeight();
            double angle = crop.getAngle();
            crop = new CropBounds(center, height, width, angle + Math.PI / 2);
            newAngle = crop.getAngle();
        }
        return crop;
    }

    // When crop mode starts, or when the user asks to reset the current crop,
    // use these CropBounds.  They are angle-only bounds, set to the nearest
    // multiple of 90 degrees.
    private CropBounds getUncroppedBounds() {
        if (bounds == null) {
            return new CropBounds();
        }
        double angle = bounds.getAngle();
        angle = (Math.PI / 2) * Math.round(angle / (Math.PI / 2));
        return new CropBounds(angle);
    }

    private final static String AngleTag = "Angle";

    private final static String CropTag = "Crop";

    private final static String ULtag = "UpperLeft";
    private final static String URtag = "UpperRight";
    private final static String LLtag = "LowerLeft";
    private final static String LRtag = "LowerRight";

    private final static String Xtag = "X";
    private final static String Ytag = "Y";

    private final static String FlipTag = "Flip";
    private final static String Htag = "Horizontal";
    private final static String Vtag = "Vertical";

    public void save(XmlNode node) {
        node = node.addChild(CropTag);

        if (bounds.isAngleOnly()) {
            double angle = bounds.getAngle();
            node.setAttribute(AngleTag, Double.toString(angle));
        }
        else {
            XmlNode ulNode = node.addChild(ULtag);
            Point2D ul = bounds.getUpperLeft();
            ulNode.setAttribute(Xtag, Double.toString(ul.getX()));
            ulNode.setAttribute(Ytag, Double.toString(ul.getY()));

            XmlNode urNode = node.addChild(URtag);
            Point2D ur = bounds.getUpperRight();
            urNode.setAttribute(Xtag, Double.toString(ur.getX()));
            urNode.setAttribute(Ytag, Double.toString(ur.getY()));

            XmlNode llNode = node.addChild(LLtag);
            Point2D ll = bounds.getLowerLeft();
            llNode.setAttribute(Xtag, Double.toString(ll.getX()));
            llNode.setAttribute(Ytag, Double.toString(ll.getY()));

            XmlNode lrNode = node.addChild(LRtag);
            Point2D lr = bounds.getLowerRight();
            lrNode.setAttribute(Xtag, Double.toString(lr.getX()));
            lrNode.setAttribute(Ytag, Double.toString(lr.getY()));
        }

        final boolean hFlip = bounds.isFlippedHorizontally();
        final boolean vFlip = bounds.isFlippedVertically();
        if (hFlip || vFlip) {
            XmlNode flipNode = node.addChild(FlipTag);
            flipNode.setAttribute(Htag, Boolean.toString(hFlip));
            flipNode.setAttribute(Vtag, Boolean.toString(vFlip));
        }
    }

    public void restore(XmlNode node) throws XMLException {
        try {
            node = node.getChild(CropTag);

            double x, y;
            Point2D.Double ul, ur, ll, lr;

            try {
                XmlNode ulNode = node.getChild(ULtag);
                x = Double.parseDouble(ulNode.getAttribute(Xtag));
                y = Double.parseDouble(ulNode.getAttribute(Ytag));
                ul = new Point2D.Double(x, y);

                XmlNode urNode = node.getChild(URtag);
                x = Double.parseDouble(urNode.getAttribute(Xtag));
                y = Double.parseDouble(urNode.getAttribute(Ytag));
                ur = new Point2D.Double(x, y);

                XmlNode llNode = node.getChild(LLtag);
                x = Double.parseDouble(llNode.getAttribute(Xtag));
                y = Double.parseDouble(llNode.getAttribute(Ytag));
                ll = new Point2D.Double(x, y);

                XmlNode lrNode = node.getChild(LRtag);
                x = Double.parseDouble(lrNode.getAttribute(Xtag));
                y = Double.parseDouble(lrNode.getAttribute(Ytag));
                lr = new Point2D.Double(x, y);
            }
            catch (NumberFormatException e) {
                throw new XMLException("Invalid crop coordinates", e);
            }
            bounds = new CropBounds(ul, ur, ll, lr);
        }
        catch (XMLException e1) {
            try {
                double angle = Double.parseDouble(node.getAttribute(AngleTag));

                Dimension size = engine.getNaturalSize();
                Rectangle2D imageBounds = new Rectangle2D.Double(0, 0, size.width, size.height);

                bounds = new CropBounds(imageBounds, angle);
                // bounds = new CropBounds(angle);
            }
            catch (XMLException e2) {
                throw new XMLException(
                    "No valid crop or rotate data: " +
                    e1.getMessage() + ", " + e2.getMessage()
                );
            }
        }

        try {
            XmlNode flipNode = node.getChild(FlipTag);
            boolean h = Boolean.parseBoolean(flipNode.getAttribute(Htag));
            boolean v = Boolean.parseBoolean(flipNode.getAttribute(Vtag));
            bounds.flip(h, v);
        }
        catch (XMLException ignored) {
        }

        engine.setCropBounds(bounds);
        cropMode.setCrop(bounds);
        // Note this sign change:
        hiddenRotorMode.setAngle(- bounds.getAngle());
        // The rotate package applies the convention that positive angles
        // are positive in screen coordinates, meaning clockwise on the
        // screen, which is the opposite of the convention in CropBounds.
        xform.update();
    }

    void dispose() {
        if (rotorMode != null)
            rotorMode.dispose();
        if (cropMode!= null)
            cropMode.dispose();
        if (hiddenRotorMode != null)
            hiddenRotorMode.dispose();
    }
}


text:
from django.conf.urls import url, patterns

from . import views

urlpatterns = patterns(
    '',
    url(r'^recover/(?P<signature>.+)/$', views.recover_done,
        name='password_reset_sent'),
    url(r'^recover/$', views.recover, name='password_reset_recover'),
    url(r'^reset/done/$', views.reset_done, name='password_reset_done'),
    url(r'^reset/(?P<token>[\w:-]+)/$', views.reset,
        name='password_reset_reset'),
)