text:
import datetime
import logging
import os
import random
import sys
import unittest

ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT_DIR)

import test_env

test_env.setup_test_env()

# From tools/third_party/
import webtest

from google.appengine.ext import deferred
from google.appengine.ext import ndb

from components import auth_testing
from components import utils
from server import task_pack
from server import task_request
from server import task_result
from server import task_to_run
from support import test_case

# pylint: disable=W0212

def _gen_request_data(properties=None, **kwargs):
  base_data = {
    'name': 'Request name',
    'user': 'Jesus',
    'properties': {
      'commands': [[u'command1']],
      'data': [],
      'dimensions': {},
      'env': {},
      'execution_timeout_secs': 24*60*60,
      'io_timeout_secs': None,
    },
    'priority': 50,
    'scheduling_expiration_secs': 60,
    'tags': [u'tag:1'],
  }
  base_data.update(kwargs)
  base_data['properties'].update(properties or {})
  return base_data

def _safe_cmp(a, b):
  # cmp(datetime.datetime.utcnow(), None) throws TypeError. Workaround.
  return cmp(utils.encode_to_json(a), utils.encode_to_json(b))

def get_entities(entity_model):
  return sorted(
      (i.to_dict() for i in entity_model.query().fetch()), cmp=_safe_cmp)

class TestCase(test_case.TestCase):
  def setUp(self):
    super(TestCase, self).setUp()
    auth_testing.mock_get_current_identity(self)

class TaskResultApiTest(TestCase):
  APP_DIR = ROOT_DIR

  def setUp(self):
    super(TaskResultApiTest, self).setUp()
    self.now = datetime.datetime(2014, 1, 2, 3, 4, 5, 6)
    self.mock_now(self.now)
    self.mock(random, 'getrandbits', lambda _: 0x88)
    self.app = webtest.TestApp(
        deferred.application,
        extra_environ={
          'REMOTE_ADDR': '1.0.1.2',
          'SERVER_SOFTWARE': os.environ['SERVER_SOFTWARE'],
        })

  def assertEntities(self, expected, entity_model):
    self.assertEqual(expected, get_entities(entity_model))

  def test_all_apis_are_tested(self):
    # Ensures there's a test for each public API.
    module = task_result
    expected = set(
        i for i in dir(module)
        if i[0] != '_' and hasattr(getattr(module, i), 'func_name'))
    missing = expected - set(i[5:] for i in dir(self) if i.startswith('test_'))
    self.assertFalse(missing)

  def test_State(self):
    for i in task_result.State.STATES:
      self.assertTrue(task_result.State.to_string(i))
    with self.assertRaises(ValueError):
      task_result.State.to_string(0)

    self.assertEqual(
        set(task_result.State._NAMES), set(task_result.State.STATES))
    items = (
      task_result.State.STATES_RUNNING + task_result.State.STATES_DONE +
      task_result.State.STATES_ABANDONED)
    self.assertEqual(set(items), set(task_result.State.STATES))
    self.assertEqual(len(items), len(set(items)))
    self.assertEqual(
        task_result.State.STATES_RUNNING + task_result.State.STATES_NOT_RUNNING,
        task_result.State.STATES)

  def test_state_to_string(self):
    # Same code as State.to_string() except that it works for
    # TaskResultSummary too.
    class Foo(ndb.Model):
      deduped_from = None
      state = task_result.StateProperty()
      failure = ndb.BooleanProperty(default=False)
      internal_failure = ndb.BooleanProperty(default=False)

    for i in task_result.State.STATES:
      self.assertTrue(task_result.State.to_string(i))
    for i in task_result.State.STATES:
      self.assertTrue(task_result.state_to_string(Foo(state=i)))
    f = Foo(state=task_result.State.COMPLETED)
    f.deduped_from = '123'
    self.assertEqual('Deduped', task_result.state_to_string(f))

  def test_new_result_summary(self):
    request = task_request.make_request(_gen_request_data())
    actual = task_result.new_result_summary(request)
    expected = {
      'abandoned_ts': None,
      'bot_id': None,
      'bot_version': None,
      'children_task_ids': [],
      'completed_ts': None,
      'costs_usd': [],
      'cost_saved_usd': None,
      'created_ts': self.now,
      'deduped_from': None,
      'durations': [],
      'exit_codes': [],
      'failure': False,
      'id': '1d69b9f088008810',
      'internal_failure': False,
      'modified_ts': None,
      'name': u'Request name',
      'properties_hash': None,
      'server_versions': [],
      'started_ts': None,
      'state': task_result.State.PENDING,
      'try_number': None,
      'user': u'Jesus',
    }
    self.assertEqual(expected, actual.to_dict())
    self.assertEqual(50, actual.priority)
    self.assertEqual(True, actual.can_be_canceled)
    actual.state = task_result.State.RUNNING
    self.assertEqual(False, actual.can_be_canceled)

    actual.children_task_ids = [
      '1d69ba3ea8008810', '3d69ba3ea8008810', '2d69ba3ea8008810',
    ]
    ndb.transaction(actual.put)
    expected = [u'1d69ba3ea8008810', u'2d69ba3ea8008810', u'3d69ba3ea8008810']
    self.assertEqual(expected, actual.key.get().children_task_ids)

  def test_new_run_result(self):
    request = task_request.make_request(_gen_request_data())
    actual = task_result.new_run_result(request, 1, 'localhost', 'abc')
    expected = {
      'abandoned_ts': None,
      'bot_id': 'localhost',
      'bot_version': 'abc',
      'children_task_ids': [],
      'completed_ts': None,
      'cost_usd': 0.,
      'durations': [],
      'exit_codes': [],
      'failure': False,
      'id': '1d69b9f088008811',
      'internal_failure': False,
      'modified_ts': None,
      'server_versions': ['default-version'],
      'started_ts': self.now,
      'state': task_result.State.RUNNING,
      'try_number': 1,
    }
    self.assertEqual(expected, actual.to_dict())
    self.assertEqual(50, actual.priority)
    self.assertEqual(False, actual.can_be_canceled)

  def test_integration(self):
    # Creates a TaskRequest, along its TaskResultSummary and TaskToRun. Have a
    # bot reap the task, and complete the task. Ensure the resulting
    # TaskResultSummary and TaskRunResult are properly updated.
    request = task_request.make_request(_gen_request_data())
    result_summary = task_result.new_result_summary(request)
    to_run = task_to_run.new_task_to_run(request)
    ndb.transaction(lambda: ndb.put_multi([result_summary, to_run]))
    expected = {
      'abandoned_ts': None,
      'bot_id': None,
      'bot_version': None,
      'children_task_ids': [],
      'completed_ts': None,
      'costs_usd': [],
      'cost_saved_usd': None,
      'created_ts': self.now,
      'deduped_from': None,
      'durations': [],
      'exit_codes': [],
      'failure': False,
      'id': '1d69b9f088008810',
      'internal_failure': False,
      'modified_ts': self.now,
      'name': u'Request name',
      'properties_hash': None,
      'server_versions': [],
      'started_ts': None,
      'state': task_result.State.PENDING,
      'try_number': None,
      'user': u'Jesus',
    }
    self.assertEqual(expected, result_summary.to_dict())

    # Nothing changed 2 secs later except latency.
    self.mock_now(self.now, 2)
    self.assertEqual(expected, result_summary.to_dict())

    # Task is reaped after 2 seconds (4 secs total).
    reap_ts = self.now + datetime.timedelta(seconds=4)
    self.mock_now(reap_ts)
    to_run.queue_number = None
    to_run.put()
    run_result = task_result.new_run_result(request, 1, 'localhost', 'abc')
    result_summary.set_from_run_result(run_result, request)
    ndb.transaction(lambda: ndb.put_multi((result_summary, run_result)))
    expected = {
      'abandoned_ts': None,
      'bot_id': u'localhost',
      'bot_version': u'abc',
      'children_task_ids': [],
      'completed_ts': None,
      'costs_usd': [0.],
      'cost_saved_usd': None,
      'created_ts': self.now,
      'deduped_from': None,
      'durations': [],
      'exit_codes': [],
      'failure': False,
      'id': '1d69b9f088008810',
      'internal_failure': False,
      'modified_ts': reap_ts,
      'name': u'Request name',
      'properties_hash': None,
      'server_versions': [u'default-version'],
      'started_ts': reap_ts,
      'state': task_result.State.RUNNING,
      'try_number': 1,
      'user': u'Jesus',
    }
    self.assertEqual(expected, result_summary.key.get().to_dict())

    # Task completed after 2 seconds (6 secs total), the task has been running
    # for 2 seconds.
    complete_ts = self.now + datetime.timedelta(seconds=6)
    self.mock_now(complete_ts)
    run_result.completed_ts = complete_ts
    run_result.exit_codes.append(0)
    run_result.state = task_result.State.COMPLETED
    ndb.transaction(
        lambda: ndb.put_multi(run_result.append_output(0, 'foo', 0)))
    result_summary.set_from_run_result(run_result, request)
    ndb.transaction(lambda: ndb.put_multi((result_summary, run_result)))
    expected = {
      'abandoned_ts': None,
      'bot_id': u'localhost',
      'bot_version': u'abc',
      'children_task_ids': [],
      'completed_ts': complete_ts,
      'costs_usd': [0.],
      'cost_saved_usd': None,
      'created_ts': self.now,
      'deduped_from': None,
      'durations': [],
      'exit_codes': [0],
      'failure': False,
      'id': '1d69b9f088008810',
      'internal_failure': False,
      'modified_ts': complete_ts,
      'name': u'Request name',
      'properties_hash': None,
      'server_versions': [u'default-version'],
      'started_ts': reap_ts,
      'state': task_result.State.COMPLETED,
      'try_number': 1,
      'user': u'Jesus',
    }
    self.assertEqual(expected, result_summary.key.get().to_dict())
    self.assertEqual(['foo'], list(result_summary.get_outputs()))
    self.assertEqual(datetime.timedelta(seconds=2), result_summary.duration)
    self.assertEqual(
        datetime.timedelta(seconds=2),
        result_summary.duration_now(utils.utcnow()))
    self.assertEqual(
        datetime.timedelta(seconds=4), result_summary.pending)
    self.assertEqual(
        datetime.timedelta(seconds=4),
        result_summary.pending_now(utils.utcnow()))

    self.assertEqual(
        task_pack.pack_result_summary_key(result_summary.key),
        result_summary.key_string)
    self.assertEqual(complete_ts, result_summary.ended_ts)
    self.assertEqual(
        task_pack.pack_run_result_key(run_result.key),
        run_result.key_string)
    self.assertEqual(complete_ts, run_result.ended_ts)

  def test_yield_run_result_keys_with_dead_bot(self):
    request = task_request.make_request(_gen_request_data())
    result_summary = task_result.new_result_summary(request)
    ndb.transaction(result_summary.put)
    run_result = task_result.new_run_result(request, 1, 'localhost', 'abc')
    run_result.completed_ts = self.now
    result_summary.set_from_run_result(run_result, request)
    ndb.transaction(lambda: ndb.put_multi((run_result, result_summary)))

    self.mock_now(self.now + task_result.BOT_PING_TOLERANCE)
    self.assertEqual(
        [], list(task_result.yield_run_result_keys_with_dead_bot()))

    self.mock_now(self.now + task_result.BOT_PING_TOLERANCE, 1)
    self.assertEqual(
        [run_result.key],
        list(task_result.yield_run_result_keys_with_dead_bot()))

  def test_set_from_run_result(self):
    request = task_request.make_request(_gen_request_data())
    result_summary = task_result.new_result_summary(request)
    run_result = task_result.new_run_result(request, 1, 'localhost', 'abc')
    self.assertTrue(result_summary.need_update_from_run_result(run_result))
    ndb.transaction(lambda: ndb.put_multi((result_summary, run_result)))

    self.assertTrue(result_summary.need_update_from_run_result(run_result))
    result_summary.set_from_run_result(run_result, request)
    ndb.transaction(lambda: ndb.put_multi([result_summary]))

    self.assertFalse(result_summary.need_update_from_run_result(run_result))

  def test_set_from_run_result_two_server_versions(self):
    request = task_request.make_request(_gen_request_data())
    result_summary = task_result.new_result_summary(request)
    run_result = task_result.new_run_result(request, 1, 'localhost', 'abc')
    self.assertTrue(result_summary.need_update_from_run_result(run_result))
    ndb.transaction(lambda: ndb.put_multi((result_summary, run_result)))

    self.assertTrue(result_summary.need_update_from_run_result(run_result))
    result_summary.set_from_run_result(run_result, request)
    ndb.transaction(lambda: ndb.put_multi([result_summary]))

    run_result.signal_server_version('new-version')
    result_summary.set_from_run_result(run_result, request)
    ndb.transaction(lambda: ndb.put_multi((result_summary, run_result)))
    self.assertEqual(
        ['default-version', 'new-version'],
        run_result.key.get().server_versions)
    self.assertEqual(
        ['default-version', 'new-version'],
        result_summary.key.get().server_versions)

  def test_set_from_run_result_two_tries(self):
    request = task_request.make_request(_gen_request_data())
    result_summary = task_result.new_result_summary(request)
    run_result_1 = task_result.new_run_result(request, 1, 'localhost', 'abc')
    run_result_2 = task_result.new_run_result(request, 2, 'localhost', 'abc')
    self.assertTrue(result_summary.need_update_from_run_result(run_result_1))
    ndb.transaction(lambda: ndb.put_multi((result_summary, run_result_2)))

    self.assertTrue(result_summary.need_update_from_run_result(run_result_1))
    result_summary.set_from_run_result(run_result_1, request)
    ndb.transaction(lambda: ndb.put_multi((result_summary, run_result_1)))

    result_summary = result_summary.key.get()
    self.assertFalse(result_summary.need_update_from_run_result(run_result_1))

    self.assertTrue(result_summary.need_update_from_run_result(run_result_2))
    result_summary.set_from_run_result(run_result_2, request)
    ndb.transaction(lambda: ndb.put_multi((result_summary, run_result_2)))
    result_summary = result_summary.key.get()

    self.assertEqual(2, result_summary.try_number)
    self.assertFalse(result_summary.need_update_from_run_result(run_result_1))

  def test_run_result_duration(self):
    run_result = task_result.TaskRunResult(
        started_ts=datetime.datetime(2010, 1, 1, 0, 0, 0),
        completed_ts=datetime.datetime(2010, 1, 1, 0, 2, 0))
    self.assertEqual(datetime.timedelta(seconds=120), run_result.duration)
    self.assertEqual(
        datetime.timedelta(seconds=120),
        run_result.duration_now(utils.utcnow()))

    run_result = task_result.TaskRunResult(
        started_ts=datetime.datetime(2010, 1, 1, 0, 0, 0),
        abandoned_ts=datetime.datetime(2010, 1, 1, 0, 1, 0))
    self.assertEqual(None, run_result.duration)
    self.assertEqual(None, run_result.duration_now(utils.utcnow()))

  def test_run_result_timeout(self):
    request = task_request.make_request(_gen_request_data())
    result_summary = task_result.new_result_summary(request)
    ndb.transaction(result_summary.put)
    run_result = task_result.new_run_result(request, 1, 'localhost', 'abc')
    run_result.state = task_result.State.TIMED_OUT
    run_result.completed_ts = self.now
    result_summary.set_from_run_result(run_result, request)
    ndb.transaction(lambda: ndb.put_multi((run_result, result_summary)))
    run_result = run_result.key.get()
    result_summary = result_summary.key.get()
    self.assertEqual(True, run_result.failure)
    self.assertEqual(True, result_summary.failure)

  def test_get_result_summary_query(self):
    # Indirectly tested by both frontend and API.
    pass

  def test_get_tasks(self):
    # Indirectly tested by both frontend and API.
    pass

  def test_search_by_name(self):
    # Tested in task_scheduler_test.
    pass

class TestOutput(TestCase):
  APP_DIR = ROOT_DIR

  def setUp(self):
    super(TestOutput, self).setUp()
    request = task_request.make_request(_gen_request_data())
    result_summary = task_result.new_result_summary(request)
    ndb.transaction(result_summary.put)
    self.run_result = task_result.new_run_result(request, 1, 'localhost', 'abc')
    result_summary.set_from_run_result(self.run_result, request)
    ndb.transaction(lambda: ndb.put_multi((result_summary, self.run_result)))
    self.run_result = self.run_result.key.get()

  def assertTaskOutputChunk(self, expected):
    q = task_result.TaskOutputChunk.query().order(
        task_result.TaskOutputChunk.key)
    self.assertEqual(expected, [t.to_dict() for t in q.fetch()])

  def test_append_output(self):
    # Test that one can stream output and it is returned fine.
    def run(*args):
      entities = self.run_result.append_output(*args)
      self.assertEqual(1, len(entities))
      ndb.put_multi(entities)
    run(0, 'Part1\n', 0)
    run(1, 'Part2\n', 0)
    run(1, 'Part3\n', len('Part2\n'))
    self.assertEqual(
        ['Part1\n', 'Part2\nPart3\n'], list(self.run_result.get_outputs()))
    self.assertEqual(
        'Part1\n',
        self.run_result.get_command_output_async(0).get_result())
    self.assertEqual(
        'Part2\nPart3\n',
        self.run_result.get_command_output_async(1).get_result())
    self.assertEqual(
        None, self.run_result.get_command_output_async(2).get_result())

  def test_append_output_large(self):
    self.mock(logging, 'error', lambda *_: None)
    one_mb = '<3Google' * (1024*1024/8)

    def run(*args):
      entities = self.run_result.append_output(*args)
      # Asserts at least one entity was created.
      self.assertTrue(entities)
      ndb.put_multi(entities)

    for i in xrange(16):
      run(0, one_mb, i*len(one_mb))

    self.assertEqual(
        task_result.TaskOutput.FETCH_MAX_CONTENT,
        len(self.run_result.get_command_output_async(0).get_result()))

  def test_append_output_max_chunk(self):
    # This test case is very slow (1m25s locally) if running with the default
    # values, so scale it down a bit which results in ~2.5s.
    self.mock(
        task_result.TaskOutput, 'PUT_MAX_CONTENT',
        task_result.TaskOutput.PUT_MAX_CONTENT / 8)
    self.mock(
        task_result.TaskOutput, 'PUT_MAX_CHUNKS',
        task_result.TaskOutput.PUT_MAX_CHUNKS / 8)
    self.assertFalse(
        task_result.TaskOutput.PUT_MAX_CONTENT %
            task_result.TaskOutput.CHUNK_SIZE)

    calls = []
    self.mock(logging, 'error', lambda *args: calls.append(args))
    max_chunk = 'x' * task_result.TaskOutput.PUT_MAX_CONTENT
    entities = self.run_result.append_output(0, max_chunk, 0)
    self.assertEqual(task_result.TaskOutput.PUT_MAX_CHUNKS, len(entities))
    ndb.put_multi(entities)
    self.assertEqual([], calls)

    # Try with PUT_MAX_CONTENT + 1 bytes, so the last byte is discarded.
    entities = self.run_result.append_output(1, max_chunk + 'x', 0)
    self.assertEqual(task_result.TaskOutput.PUT_MAX_CHUNKS, len(entities))
    ndb.put_multi(entities)
    self.assertEqual(1, len(calls))
    self.assertTrue(calls[0][0].startswith('Dropping '), calls[0][0])
    self.assertEqual(1, calls[0][1])

  def test_append_output_partial(self):
    ndb.put_multi(self.run_result.append_output(0, 'Foo', 10))
    expected_output = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Foo'
    self.assertEqual(
        expected_output,
        self.run_result.get_command_output_async(0).get_result())
    self.assertTaskOutputChunk([{'chunk': expected_output, 'gaps': [0, 10]}])

  def test_append_output_partial_hole(self):
    ndb.put_multi(self.run_result.append_output(0, 'Foo', 0))
    ndb.put_multi(self.run_result.append_output(0, 'Bar', 10))
    expected_output = 'Foo\x00\x00\x00\x00\x00\x00\x00Bar'
    self.assertEqual(
        expected_output,
        self.run_result.get_command_output_async(0).get_result())
    self.assertTaskOutputChunk([{'chunk': expected_output, 'gaps': [3, 10]}])

  def test_append_output_partial_far(self):
    ndb.put_multi(self.run_result.append_output(
        0, 'Foo', 10 + task_result.TaskOutput.CHUNK_SIZE))
    self.assertEqual(
        '\x00' * (task_result.TaskOutput.CHUNK_SIZE + 10) + 'Foo',
        self.run_result.get_command_output_async(0).get_result())
    expected = [
      {'chunk': '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Foo', 'gaps': [0, 10]},
    ]
    self.assertTaskOutputChunk(expected)

  def test_append_output_partial_far_split(self):
    # Missing, writing happens on two different TaskOutputChunk entities.
    ndb.put_multi(self.run_result.append_output(
        0, 'FooBar', 2 * task_result.TaskOutput.CHUNK_SIZE - 3))
    self.assertEqual(
        '\x00' * (task_result.TaskOutput.CHUNK_SIZE * 2 - 3) + 'FooBar',
        self.run_result.get_command_output_async(0).get_result())
    expected = [
      {
        'chunk': '\x00' * (task_result.TaskOutput.CHUNK_SIZE - 3) + 'Foo',
        'gaps': [0, 102397],
      },
      {'chunk': 'Bar', 'gaps': []},
    ]
    self.assertTaskOutputChunk(expected)

  def test_append_output_overwrite(self):
    # Overwrite previously written data.
    ndb.put_multi(self.run_result.append_output(0, 'FooBar', 0))
    ndb.put_multi(self.run_result.append_output(0, 'X', 3))
    self.assertEqual(
        'FooXar', self.run_result.get_command_output_async(0).get_result())
    self.assertTaskOutputChunk([{'chunk': 'FooXar', 'gaps': []}])

  def test_append_output_reverse_order(self):
    # Write the data in reverse order in multiple calls.
    ndb.put_multi(self.run_result.append_output(0, 'Wow', 11))
    ndb.put_multi(self.run_result.append_output(0, 'Foo', 8))
    ndb.put_multi(self.run_result.append_output(0, 'Baz', 0))
    ndb.put_multi(self.run_result.append_output(0, 'Bar', 4))
    expected_output = 'Baz\x00Bar\x00FooWow'
    self.assertEqual(
        expected_output,
        self.run_result.get_command_output_async(0).get_result())
    self.assertTaskOutputChunk(
        [{'chunk': expected_output, 'gaps': [3, 4, 7, 8]}])

  def test_append_output_reverse_order_second_chunk(self):
    # Write the data in reverse order in multiple calls.
    ndb.put_multi(self.run_result.append_output(
        0, 'Wow', task_result.TaskOutput.CHUNK_SIZE + 11))
    ndb.put_multi(self.run_result.append_output(
        0, 'Foo', task_result.TaskOutput.CHUNK_SIZE + 8))
    ndb.put_multi(self.run_result.append_output(
        0, 'Baz', task_result.TaskOutput.CHUNK_SIZE + 0))
    ndb.put_multi(self.run_result.append_output(
        0, 'Bar', task_result.TaskOutput.CHUNK_SIZE + 4))
    self.assertEqual(
        task_result.TaskOutput.CHUNK_SIZE * '\x00' + 'Baz\x00Bar\x00FooWow',
        self.run_result.get_command_output_async(0).get_result())
    self.assertTaskOutputChunk(
        [{'chunk': 'Baz\x00Bar\x00FooWow', 'gaps': [3, 4, 7, 8]}])

if __name__ == '__main__':
  if '-v' in sys.argv:
    unittest.TestCase.maxDiff = None
  unittest.main()


text:
#pragma once
#include "mccsemanticerrorchecker.h"

class MccFunctionDeclaration;
class MccWhileStatement;
class MccBlockStatement;
class MccContinueStatement;
class MccBreakStatement;

/**
 * @brief Check whether a while block exists out of
 *	a break or continue statement.
 */
class MccJumpInWhileChecker :
	public MccSemanticErrorChecker
{
public:
	MccJumpInWhileChecker(void);
	virtual ~MccJumpInWhileChecker(void);

	void detect(MccFunctionDeclaration *fun);
	void detect(MccWhileStatement *while_stmt);
	void detect(MccBlockStatement *block_stmt);
	void detect(MccBreakStatement *brk_stmt);
	void detect(MccContinueStatement *ctn_stmt);

private:
	/**
	 * @brief the current while block numbers.
	 */
	int m_while_level;
};

redpajama_set_name: RedPajamaGithub


text:
package model.entity;

import java.io.Serializable;

/**
 * Created by Vitaly on 02.11.15.
 */
public class Ping implements Serializable {

    private String utils = "ping";

    public Ping() {
    }

    public String getUtils() {
        return utils;
    }

    public void setUtils(String utils) {
        this.utils = utils;
    }

}


text:
package ozone.owf.gorm;

import org.codehaus.groovy.transform.ASTTransformation;
import org.codehaus.groovy.transform.GroovyASTTransformation;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.ast.stmt.*;
import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
import ozone.owf.grails.domain.Person;
import grails.util.GrailsNameUtils;
import groovy.util.*;

import java.lang.reflect.Modifier;
import java.util.*;
import java.io.*;

/**
 * Performs an ast transformation on a class - adds createdBy/createdDate editedBy/EditedDate id and table
 * properties to the subject class.
 */
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
public class AuditStampASTTransformation implements ASTTransformation {

	//private static final Log LOG = LogFactory.getLog(AuditStampASTTransformation.class);
	private static final ConfigObject CO = new ConfigSlurper().parse(getContents(new File("./grails-app/conf/Config.groovy")));
	private static final Properties CONF = (new ConfigSlurper().parse(getContents(new File("./grails-app/conf/Config.groovy")))).toProperties();

	static{
		//System.out.println("greenbill  is [" + getMap(CO,"stamp.mapping.pluralTable").getClass()+ "]");
		//ConfigurationHolder.setConfig(CO);
		//Map confmap = ConfigurationHolder.getFlatConfig();
	}

	public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {

		String createdByField = CONF.getProperty("stamp.audit.createdBy");
		String editedByField = CONF.getProperty("stamp.audit.editedBy");
		String editedDateField = CONF.getProperty("stamp.audit.editedDate");
		String createdDateField = CONF.getProperty("stamp.audit.createdDate");

		for (ASTNode astNode : astNodes) {
			if (astNode instanceof ClassNode) {
				ClassNode classNode = (ClassNode) astNode;
				//List<FieldNode>  fnlist = classNode.getFields();
				//LOG.info("[Audit stamp ASTTransformation] Adding propertie [edited..created] to class [" + classNode.getName() + "]");
				//System.out.println(classNode.getName() + " - [Audit stamp ASTTransformation] Adding propertie [edited..created]");
				if(editedByField!=null){
					classNode.addProperty(editedByField, Modifier.PUBLIC, new ClassNode(Person.class), ConstantExpression.NULL,null,null);
					addNullableConstraint(classNode,editedByField);
                }
				if(createdByField!=null){
					classNode.addProperty(createdByField, Modifier.PUBLIC, new ClassNode(Person.class), ConstantExpression.NULL,null,null);
					addNullableConstraint(classNode,createdByField);
                }
				Expression now = new ConstructorCallExpression(new ClassNode(java.util.Date.class),MethodCallExpression.NO_ARGUMENTS);
				if(createdDateField!=null){
					classNode.addProperty(createdDateField, Modifier.PUBLIC, new ClassNode(java.util.Date.class), now, null, null);
					addNullableConstraint(classNode,createdDateField);
				}
				if(editedDateField!=null){
					classNode.addProperty(editedDateField, Modifier.PUBLIC, new ClassNode(java.util.Date.class), now, null, null);
					addNullableConstraint(classNode,editedDateField);
				}

				classNode.addInterface(new ClassNode(DomainObject.class));
				/****comment this out if you don't want our the custom ID and table name stuff****/
			//	addTableAndIdMapping(classNode);

			}
		}
	}

	@SuppressWarnings("rawtypes")
	public void addTableAndIdMapping(ClassNode classNode){
		FieldNode closure = classNode.getDeclaredField("mapping");

		if(closure!=null){
			boolean hasTable=hasFieldInClosure(closure,"table");
			boolean hasId=hasFieldInClosure(closure,"id");

			ClosureExpression exp = (ClosureExpression)closure.getInitialExpression();
			BlockStatement block = (BlockStatement) exp.getCode();

			//this just adds an s to the class name for the table if its not specified
			Boolean pluralize = (Boolean)getMap(CO,"stamp.mapping.pluralTable");
			if(!hasTable && pluralize!=null && pluralize){
				String tablename = GrailsNameUtils.getShortName(classNode.getName())+"s";
				//LOG.info("Added new mapping to assign table: " + tablename);
				MethodCallExpression tableMeth = new MethodCallExpression(
					VariableExpression.THIS_EXPRESSION,
					new ConstantExpression("table"),
					new ArgumentListExpression(new ConstantExpression(tablename))
					);
				//block = (BlockStatement) exp.getCode();
				block.addStatement(new ExpressionStatement(tableMeth));
				//System.out.println(classNode.getName()+" - Added table mapping " + tablename );
			}
			//This adds the ID generator that we use for domian classes
			Map tableconf = (Map)getMap(CO,"stamp.mapping.id");
			if(!hasId && tableconf!=null){
				NamedArgumentListExpression namedarg = new NamedArgumentListExpression();
				if(tableconf.get("column") != null){
					namedarg.addMapEntryExpression(new ConstantExpression("column"), new ConstantExpression(tableconf.get("column").toString()));
				}
				if(tableconf.get("generator") != null){
					namedarg.addMapEntryExpression(new ConstantExpression("generator"), new ConstantExpression(tableconf.get("generator").toString()));
				}
				MethodCallExpression tableMeth = new MethodCallExpression(
					VariableExpression.THIS_EXPRESSION,
					new ConstantExpression("id"),
					namedarg
					);
				//block = (BlockStatement) exp.getCode();
				block.addStatement(new ExpressionStatement(tableMeth));
				//System.out.println(classNode.getName() + " - Added ID mapping with "+ tableconf);
			}
		}
		//System.out.println(block.toString());
	}

	public void addNullableConstraint(ClassNode classNode,String fieldName){
		FieldNode closure = classNode.getDeclaredField("constraints");

		if(closure!=null){

			ClosureExpression exp = (ClosureExpression)closure.getInitialExpression();
			BlockStatement block = (BlockStatement) exp.getCode();

			if(!hasFieldInClosure(closure,fieldName)){
				NamedArgumentListExpression namedarg = new NamedArgumentListExpression();
				namedarg.addMapEntryExpression(new ConstantExpression("nullable"), new ConstantExpression(true));
				MethodCallExpression constExpr = new MethodCallExpression(
					VariableExpression.THIS_EXPRESSION,
					new ConstantExpression(fieldName),
					namedarg
					);
				block.addStatement(new ExpressionStatement(constExpr));
				//System.out.println(classNode.getName() + " - Added nullabel constraint for "+ fieldName);
			}
		}
		//System.out.println(block.toString());
	}

	public boolean hasFieldInClosure(FieldNode closure, String fieldName){
		if(closure != null){
			ClosureExpression exp = (ClosureExpression) closure.getInitialExpression();
			BlockStatement block = (BlockStatement) exp.getCode();
			List<Statement> ments = block.getStatements();
			for(Statement expstat : ments){
				if(expstat instanceof ExpressionStatement && ((ExpressionStatement)expstat).getExpression() instanceof MethodCallExpression){
					MethodCallExpression methexp = (MethodCallExpression)((ExpressionStatement)expstat).getExpression();
					ConstantExpression conexp = (ConstantExpression)methexp.getMethod();
					if(conexp.getValue().equals(fieldName)){
						return true;
					}
				}
			}
		}
		return false;
	}

	static public String getContents(File aFile) {
		//...checks on aFile are elided
		StringBuilder contents = new StringBuilder();

		try {
			//use buffering, reading one line at a time
			//FileReader always assumes default encoding is OK!
			BufferedReader input =  new BufferedReader(new FileReader(aFile));
			try {
				String line = null;
				while (( line = input.readLine()) != null){
					contents.append(line);
					contents.append(System.getProperty("line.separator"));
				}
			}
			finally {
				input.close();
			}
		}
		catch (IOException ex){
			ex.printStackTrace();
		}

		return contents.toString();
	}

	@SuppressWarnings("rawtypes")
	static public Object getMap(Map configMap, String keypath) {
		String keys[] = keypath.split("\\.");
		Map map = configMap;
		for(String key : keys){
			Object val = map.get(key);
			if(val !=null){
				//System.out.println("got a key for are " +key);
				if(val instanceof Map){
					map = (Map)map.get(key);
				} else{
					return val;
				}
			}else{
				return null;
			}
		}
		return map;
	}

}

//FUTURE
/**
java.math.BigDecimal
java.lang.Integer
java.lang.Long
java.util.Date
java.lang.String
java.lang.Boolean
*/

/**
since grails has everything default to nullable:false, we change that to nullable:true here since omost of the time we condider it ok
explicity set nullable:false as the exception

public void addConstraintDefaults(ClassNode classNode){
	List<FieldNode>  fnlist = classNode.getFields();
	for(FieldNode fnode : fnlist){
		if(!fnode.isStatic()){
			//check if the type is in our list
			System.out.println("*" + fnode.getName() + " - " + fnode.getType().getName());
		}
	}

	boolean hasConstraint=false;

}
**/

/*
org.codehaus.groovy.ast.stmt.BlockStatement@f4b2da[
	org.codehaus.groovy.ast.stmt.ExpressionStatement@a0a4a[
		expression:org.codehaus.groovy.ast.expr.MethodCallExpression@29aa5a[
			object: org.codehaus.groovy.ast.expr.VariableExpression@6f0383[variable: this]
			method: ConstantExpression[discDate]
			arguments: org.codehaus.groovy.ast.expr.NamedArgumentListExpression@4fb195[
				org.codehaus.groovy.ast.expr.MapEntryExpression@13becc(key: ConstantExpression[nullable], value: ConstantExpression[true])
			]
		]
	],.....

/*
{ org.codehaus.groovy.ast.stmt.BlockStatement@f0bc0[
	org.codehaus.groovy.ast.stmt.ExpressionStatement@cc9e15[
		expression:org.codehaus.groovy.ast.expr.MethodCallExpression@9e94e8[
			object: org.codehaus.groovy.ast.expr.VariableExpression@3c2282[variable: this]
			method: ConstantExpression[table]
			arguments: org.codehaus.groovy.ast.expr.ArgumentListExpression@42428a[ConstantExpression[SyncSteps]]
		]
	],
	org.codehaus.groovy.ast.stmt.ExpressionStatement@1eafb4[
		expression:org.codehaus.groovy.ast.expr.MethodCallExpression@a17663[
			object: org.codehaus.groovy.ast.expr.VariableExpression@3c2282[variable: this]
			method: ConstantExpression[id]
			arguments: org.codehaus.groovy.ast.expr.NamedArgumentListExpression@636202[
				org.codehaus.groovy.ast.expr.MapEntryExpression@b781ea(
					key: ConstantExpression[column], value: ConstantExpression[OID]
				),
				org.codehaus.groovy.ast.expr.MapEntryExpression@b25934(
					key: ConstantExpression[generator], value: ConstantExpression[ozone.owf.nineci.hibernate.NewObjectIdGenerator]
				)
			]
		]
	], org.codehaus.groovy.ast.stmt.ExpressionStatement@fe6f06[
		expression:org.codehaus.groovy.ast.expr.MethodCallExpression@2b0459[
			object: org.codehaus.groovy.ast.expr.VariableExpression@3c2282[variable: this]
			method: ConstantExpression[syncBatch]
			arguments: org.codehaus.groovy.ast.expr.NamedArgumentListExpression@2a938f[
				org.codehaus.groovy.ast.expr.MapEntryExpression@3dbf04(key: ConstantExpression[column], value: ConstantExpression[SyncBatchId])]]]] }

*/


text:
%w[
  rubygems
  pivotal-tracker
  slack
  time_difference
  byebug
  typhoeus
  multi_xml
].each { |r| require r }

module WhoIsSlacking

  MultiXml.parser = :nokogiri

  class Start
    # whois-slacking
    # -- get project name
    # -- get slack channel
    # -- get all users for the project
    # -- save tasks
    #   -- retrieve all tasks from pivotal for the project
    #   -- loop through tasks
    #   -- if task/username combo does not exist in db
    #     -- save project/task/user
    #     -- save when task was started
    #     -- save who started task
    #     -- if task is not-completed in pivotal
    #       -- save status as status not-completed
    #       -- publish message task/user started today
    #         -- "Today Johnny started 'As a user I should be able to log in'"
    #     -- if task is completed in pivotal
    #       -- save status as status completed
    #       -- publish message task/user started today
    #         -- "Today Johnny completed 'As a user I should be able to log in'"
    #   -- if task/username combo exists and is not completed in db
    #     -- calculate how long (realtime) the task has been worked on in days (.5, 1.5 etc)
    #     -- update time on task
    #     -- save who started task
    #     -- publish message task/user/how long to slack
    #       -- "Johnny has spent 2 days working on 'As a user I should be able to log in'"
    # -- pruning
    #   -- retrieve all tasks from db for the project
    #   -- retrieve all tasks from pivotal for the project
    #   -- loop through all tasks from db
    #     -- if task/user name combo does not exist in pivotal
    #       -- mark task/user name combo in db as deleted
    #         -- "Today Johnny gave up working on 'As a user I should be able to log in'"
    #     -- if task/user name combo is completed in pivotal but not completed in db
    #       -- mark task/user name combo in db as completed
    #         -- "Today Johnny completed 'As a user I should be able to log in'"
    def self.now
      WhoIsSlacking::Pivotal.connect_to_pivotal
      project_object = WhoIsSlacking::Pivotal
        .pivotal_project( WhoIsSlacking::Pivotal.project_name)
      tasks = WhoIsSlacking::Pivotal.project_stories(project_object)
      tasks.each do |task|
        if task.current_state != 'unstarted' &&
            task.owned_by &&
            task.current_state != 'restart' &&
            task.current_state != 'unestimated' &&
            task.current_state != 'unscheduled' &&
            task.current_state != 'accepted'
          WhoIsSlacking::DataTools.save_task(project_object.name, task.id, task.name, task.owned_by, task.current_state, task.accepted_at, task.url )
        end
      end
    end

  end

  class Pivotal
    def self.connect_to_pivotal
      PivotalTracker::Client.token = ENV["PIVOTAL_TOKEN"]
      PivotalTracker::Client.timeout = ENV["PIVOTAL_TIMEOUT"].to_i
    end

    def self.project_name
      ENV["PIVOTAL_PROJECT_NAME"]
    end

    def self.pivotal_project(single_project_name=project_name)
      projects = PivotalTracker::Project.all
      projects.find {|x| x.name == single_project_name}
    end

    def self.project_members(project_object)
      project_object.memberships.all
    end

    def self.project_stories(project_object)
      project_object.stories.all
    end

    def self.pivotal_users_by_project
    end

  end

  class SlackWrapper
    def self.slack_channel
      ENV["SLACK_CHANNEL"]
    end

    def self.post_to_slack(message)
      Slack.configure { |config| config.token = ENV["SLACK_TOKEN"] }
      Slack.chat_postMessage channel: slack_channel, text: message
    end
  end

  class DataTools;
    attr_accessor :data_format
    attr_accessor :apikey

    def self.whois_store(store_type=nil)
      t = store_type.nil? ? ENV["WHOIS_DATA_STORE"] : store_type.to_s

      case t
      when "redis"
        url = ENV["REDISTOGO_URL"] || "redis://127.0.0.1:6379/"
        uri = URI.parse url
        store = Moneta.new(:Redis, host: uri.host, port: uri.port, password: uri.password)
      else # also for "file"
        store = Moneta.new(:File, :dir => 'moneta')
      end
    end

    def self.save_task(project, task_id, task, user, current_state, accepted_at, url, options={})

      # dont use accepted_at
      accepted_at = accepted_at
      url = url
      created_dt = DateTime.now.to_s
      start_dt = DateTime.now.to_s
      updated_dt = created_dt
      current_state = current_state
      active = true
      message = nil
      task_entity = {project: project, task_id: task_id, task: task, user: user, current_state: current_state, url: url, active: active, start_dt: start_dt, created_dt: created_dt, accepted_at: accepted_at, updated_dt: updated_dt}
      # initialize datastore type
      store = whois_store
      mutex = Moneta::Mutex.new(store, 'moneta')
      mutex.synchronize do
        mkey = self.whois_key(project, task_id, user)
        entity_exists = store[mkey]

        if entity_exists &&
            entity_exists[:current_state] != 'finished' &&
            entity_exists[:current_state] != 'delivered' &&
            entity_exists[:current_state] != 'accepted' #   -- if task/username combo exists and is not delivered/finished in db
          #     -- calculate how long (realtime) the task has been worked on in days (.5, 1.5 etc)
          #     -- update time on task
          #     -- save who started task
          #     -- publish message task/user/how long to slack
          #       -- "Johnny has spent 2 days working on 'As a user I should be able to log in'"
          # keep created at date

          start_dt = entity_exists[:start_dt].to_datetime
          puts "start_dt in db was #{start_dt}"

          days_worked = TimeDifference.between(DateTime.now,  start_dt).in_days
          if days_worked >= 1.0
            message = "*#{user}* has spent *#{days_worked.to_i} days* working on <#{url}|#{task}>"
          else # show hours instead
            # hours_worked = TimeDifference.between(DateTime.now,  start_dt).in_hours
            # message = "*#{user} has spent #{hours_worked.to_i} hours working on #{task}*"
            message = "*#{user}* has spent *less than a day* working on <#{url}|#{task}>"
          end
          # keep the created dt and start_dt
          created_dt = entity_exists[:created_dt]
          start_dt = entity_exists[:start_dt].to_datetime
          task_entity[:created_dt] = created_dt
          task_entity[:start_dt] = start_dt.to_s
          puts "start_dt in db will be #{start_dt}"
          store[mkey] = task_entity

        elsif entity_exists && entity_exists[:current_state] == 'delivered' && current_state == 'delivered'
          start_dt = entity_exists[:start_dt].to_datetime
          puts "start_dt in db for delivered state was #{start_dt}"

          days_worked = TimeDifference.between(DateTime.now,  start_dt).in_days
          if days_worked >= 1.0
            message = "Task <#{url}|#{task}> has been in a *delivered state for #{days_worked.to_i} days*"
          else
            message = "Task <#{url}|#{task}> has been in a *delivered state for less than a day*"
          end
        elsif entity_exists && entity_exists[:current_state] == 'finished'
          # don't do anything if entity already exists as delivered
        else #   -- if task/username combo does not exist in db
          #     -- save project/task/user
          #     -- save when task was started
          #     -- save who started task
          store[mkey] = task_entity

          if current_state != "finished" && current_state != "delivered" #     -- if task is not-completed in pivotal and is not in db
            #       -- save status as status not-completed
            #       -- publish message task/user started today
            #         -- "Today Johnny started 'As a user I should be able to log in'"
            message = "Now tracking *#{user}* as doing <#{url}|#{task}>"

          elsif current_state == "finished" #     -- if task is completed in pivotal and is not in db
            #       -- save status as status completed
            #       -- publish message task/user started today
            #         -- "Today Johnny completed 'As a user I should be able to log in'"
            message = "Today *#{user} finished* <#{url}|#{task}> and it is *waiting to be delivered*"
          elsif current_state == "delivered" #     -- if task is completed in pivotal
            #       -- save status as status completed
            #       -- publish message task/user started today
            #         -- "Today Johnny completed 'As a user I should be able to log in'"
            message = "Today *#{user} delivered* <#{url}|#{task}> and it is *waiting to be accepted*"
          end

        end
      end
      WhoIsSlacking::SlackWrapper.post_to_slack(message) if message
    end

    def self.whois_key(project, task, user)
      "#{project}-#{task}-#{user}"
    end

  end
end


text:
package com.all.client.view.components;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.PopupMenu;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.all.client.util.ReflectionUtilities;

public class TestDevicesPanel {
	private static final boolean DEBUG = false;
	private DevicesPanel collapsable = new DevicesPanel();

	private Log log = LogFactory.getLog(this.getClass());

	@Before
	public void initializeTree() {
		collapsable.setPreferredSize(new Dimension(150, 16));
		collapsable.setMinimumSize(new Dimension(150, 16));
		collapsable.setMaximumSize(new Dimension(999999, 9999999));
		collapsable.setSize(new Dimension(150, 16));
		JPanel firstPanel = new JPanel();
		firstPanel.setMinimumSize(new Dimension(0, 20));
		firstPanel.setMaximumSize(new Dimension(9999, 20));
		firstPanel.setPreferredSize(new Dimension(100, 20));
		firstPanel.setSize(new Dimension(100, 20));
		firstPanel.setBackground(Color.BLUE);
		collapsable.content().add(firstPanel);
		if (DEBUG) {
			JFrame frame = new JFrame();
			frame.setSize(150, 300);
			frame.setLayout(new BorderLayout());
			frame.add(collapsable, BorderLayout.NORTH);
			frame.setVisible(true);
		}
	}

	@Test
	public void shouldCreateACollapsablePanelAsAnInstanceOfPanel() throws Exception {
		JPanel collapsable = this.collapsable;
		assertNotNull(collapsable);
		assertEquals(16, collapsable.getHeight());
	}

	@Test
	public void shouldAddTitleToCollapsablePanel() throws Exception {
		String demoTitle = "Devices";
		JLabel titleLabel = (JLabel) ReflectionUtilities.getPrivateField(collapsable, "titleLabel");
		assertEquals("", titleLabel.getText());
		collapsable.setTitle(demoTitle);
		assertEquals(demoTitle, titleLabel.getText());
	}

	@Test
	public void shouldCollapsePanel() throws Exception {
		collapsable.collapse();
		assertEquals(16, collapsable.getHeight());
	}

	@Test
	public void shouldExpandPanel() throws Exception {
		collapsable.collapse();
		collapsable.expand();
		assertEquals(16, collapsable.getHeight());
	}

	@Test
	public void shouldSimulateClickingThaButton() throws Exception {
		assertEquals(16, collapsable.getHeight());
		JButton arrowButton = (JButton) ReflectionUtilities.getPrivateField(collapsable, "arrowButton");
		arrowButton.doClick();
		assertEquals(16, collapsable.getHeight());
		arrowButton.doClick();
		assertEquals(16, collapsable.getHeight());
	}

	@Test
	public void shouldNotAllowNormalPanelOperations() throws Exception {
		Component comp = mock(Component.class);
		try {
			collapsable.add(comp);
			fail();
		} catch (RuntimeException e) {
		}
		try {
			collapsable.add(comp, 0);
			fail();
		} catch (RuntimeException e) {
		}
		try {
			collapsable.add(comp, new Object());
			fail();
		} catch (RuntimeException e) {
		}
		try {
			collapsable.add(comp, new Object(), 0);
			fail();
		} catch (RuntimeException e) {
		}
		try {
			collapsable.add(mock(PopupMenu.class));
			fail();
		} catch (RuntimeException e) {
		}
		try {
			collapsable.add("", comp);
			fail();
		} catch (RuntimeException e) {
		}
		try {
			collapsable.remove(comp);
			fail();
		} catch (RuntimeException e) {
		}
		try {
			collapsable.remove(0);
			fail();
		} catch (RuntimeException e) {
		}
		try {
			collapsable.remove(mock(PopupMenu.class));
			fail();
		} catch (RuntimeException e) {
		}
		try {
			collapsable.removeAll();
			fail();
		} catch (RuntimeException e) {
		}
	}

	@After
	public void waitIfDebug() {
		if (DEBUG) {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				log.debug(e,e);
			}
		}
	}
}


text:
After installation on your site, you will start collecting data. Auth0 Analytics will immediately begin sending events to <%- name %>.

You will see the following events being logged:

* Auth0 Lock show
* Auth0 Lock hide
* Auth0 Lock unrecoverable_error
* Auth0 Lock authenticated
* Auth0 Lock authorization_error
* Auth0 Lock forgot_password ready
* Auth0 Lock forgot_password submit
* Auth0 Lock signin submit
* Auth0 Lock signup submit
* Auth0 Lock federated login

Note that some events that Lock emits like `hash_parsed` are not used for analytics purposes. Also, be aware that some events are only available in newer versions of Lock. If you are using an older version of Lock you will only see some of these events. We suggest upgrading to the latest version of Lock to get the most of the Auth0 Analytics integration.

For more information on the events that are sent see the [Lock API documentation](/libraries/lock/v11/api#on-).


text:
ActiveRecord::Schema.define(version: 20150218200223) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "markers", force: :cascade do |t|
    t.json     "info"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "stories", force: :cascade do |t|
    t.text     "title"
    t.text     "description"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "users", force: :cascade do |t|
    t.datetime "created_at",       null: false
    t.datetime "updated_at",       null: false
    t.string   "provider"
    t.string   "uid"
    t.string   "name"
    t.string   "oauth_token"
    t.datetime "oauth_expires_at"
  end

end


text:
Range Slider let the user select a range of values by moving the slider thumb. The smallest value is to the left, the largest to the right.

We have used noUISlider plugin as a reference which we have then customized based on our Propeller theme.

## Installation

### npm

```
npm install propellerkit-range-slider
```

## Propeller Range Slider Guidelines

Follow our [Guidelines](http://propeller.in/components/range-slider.php) for more options.

## Browser Support

- Firefox, Chrome, Safari Mac
- IE 9+
- Android 4.4+, Chrome for Android 44+
- iOS Safari 7+

## Bugs and feature requests

Found any bug or issue? Post them on [GITHUB](https://github.com/digicorp/propeller/issues).
Have feedback, suggestions or Questions? Join [GITTER CHAT ROOM](https://gitter.im/Propeller-Material-Design-Bootstrap-Framework/Support).

## Community

Get updates on Propeller's development. Chat with the Product team and community members using Propeller.

- Follow [@propellerkit on Twitter](https://twitter.com/PropellerKit).
- Chat with fellow members on [GITTER](https://gitter.im/Propeller-Material-Design-Bootstrap-Framework/Support).

## Versioning

For transparency into our release cycle and in striving to maintain backward compatibility, Propeller is maintained under [the Semantic Versioning guidelines](http://semver.org/). Sometimes we screw up, but we'll adhere to those rules whenever possible.

See [the Releases section of our GitHub project](https://github.com/digicorp/propeller/releases) for changelogs for each release version of Propeller.

## License

Propeller v1.1.0 (http://propeller.in)
© 2016-2017 [Digicorp Information Systems Pvt. Ltd.](https://www.digi-corp.com/)
Licensed under [MIT](https://github.com/digicorp/propeller/blob/master/LICENSE)

## Author

Developed and maintained at [Digicorp](https://www.digi-corp.com/).


text:
PARALLEL=4

###################################################
# DO NOT change variables bellow unless you known
# what you are doing.
###################################################

# thirdparty root dir. default is where this script is.
export TP_DIR=$PALO_HOME/thirdparty

# thirdparties will be downloaded and unpacked here
export TP_SOURCE_DIR=$TP_DIR/src

# thirdparties will be installed to here
export TP_INSTALL_DIR=$TP_DIR/installed

# patches for all thirdparties
export TP_PATCH_DIR=$TP_DIR/patches

# header files of all thirdparties will be intalled to here
export TP_INCLUDE_DIR=$TP_INSTALL_DIR/include

# libraries of all thirdparties will be intalled to here
export TP_LIB_DIR=$TP_INSTALL_DIR/lib

# all java libraries will be unpacked to here
export TP_JAR_DIR=$TP_INSTALL_DIR/lib/jar

#####################################################
# Download url, filename and unpaced filename
# of all thirdparties
#####################################################

# libevent
LIBEVENT_DOWNLOAD="https://github.com/libevent/libevent/releases/download/release-2.1.8-stable/libevent-2.1.8-stable.tar.gz"
LIBEVENT_NAME=libevent-2.1.8-stable.tar.gz
LIBEVENT_SOURCE=libevent-2.1.8-stable

# openssl
OPENSSL_DOWNLOAD="https://www.openssl.org/source/openssl-1.0.2k.tar.gz"
OPENSSL_NAME=openssl-1.0.2k.tar.gz
OPENSSL_SOURCE=openssl-1.0.2k

# thrift
THRIFT_DOWNLOAD="http://archive.apache.org/dist/thrift/0.9.3/thrift-0.9.3.tar.gz"
THRIFT_NAME=thrift-0.9.3.tar.gz
THRIFT_SOURCE=thrift-0.9.3

# llvm
LLVM_DOWNLOAD="http://releases.llvm.org/3.3/llvm-3.3.src.tar.gz"
LLVM_NAME=llvm-3.3.src.tar.gz
LLVM_SOURCE=llvm-3.3.src

# clang
CLANG_DOWNLOAD="http://releases.llvm.org/3.3/cfe-3.3.src.tar.gz"
CLANG_NAME=cfe-3.3.src.tar.gz
CLANG_SOURCE=cfe-3.3.src

# compiler-rt
COMPILER_RT_DOWNLOAD="http://releases.llvm.org/3.3/compiler-rt-3.3.src.tar.gz"
COMPILER_RT_NAME=compiler-rt-3.3.src.tar.gz
COMPILER_RT_SOURCE=compiler-rt-3.3.src

# protobuf
PROTOBUF_DOWNLOAD="https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gz"
PROTOBUF_NAME=protobuf-2.6.1.tar.gz
PROTOBUF_SOURCE=protobuf-2.6.1

# gflags
GFLAGS_DOWNLOAD="https://github.com/gflags/gflags/archive/v2.2.0.tar.gz"
GFLAGS_NAME=gflags-2.2.0.tar.gz
GFLAGS_SOURCE=gflags-2.2.0

# glog
GLOG_DOWNLOAD="https://github.com/google/glog/archive/v0.3.3.tar.gz"
GLOG_NAME=glog-0.3.3.tar.gz
GLOG_SOURCE=glog-0.3.3

# gtest
GTEST_DOWNLOAD="https://github.com/google/googletest/archive/release-1.8.0.tar.gz"
GTEST_NAME=googletest-release-1.8.0.tar.gz
GTEST_SOURCE=googletest-release-1.8.0

# snappy
SNAPPY_DOWNLOAD="https://github.com/google/snappy/releases/download/1.1.4/snappy-1.1.4.tar.gz"
SNAPPY_NAME=snappy-1.1.4.tar.gz
SNAPPY_SOURCE=snappy-1.1.4

# gperftools
GPERFTOOLS_DOWNLOAD="https://github.com/gperftools/gperftools/releases/download/gperftools-2.5.93/gperftools-2.5.93.tar.gz"
GPERFTOOLS_NAME=gperftools-2.5.93.tar.gz
GPERFTOOLS_SOURCE=gperftools-2.5.93

# zlib
ZLIB_DOWNLOAD="https://sourceforge.net/projects/libpng/files/zlib/1.2.11/zlib-1.2.11.tar.gz"
ZLIB_NAME=zlib-1.2.11.tar.gz
ZLIB_SOURCE=zlib-1.2.11

# lz4
LZ4_DOWNLOAD="https://github.com/lz4/lz4/archive/v1.7.5.tar.gz"
LZ4_NAME=lz4-1.7.5.tar.gz
LZ4_SOURCE=lz4-1.7.5

# bzip
BZIP_DOWNLOAD="http://www.bzip.org/1.0.6/bzip2-1.0.6.tar.gz"
BZIP_NAME=bzip2-1.0.6.tar.gz
BZIP_SOURCE=bzip2-1.0.6

# lzo2
LZO2_DOWNLOAD="https://github.com/damageboy/lzo2/archive/master.zip"
LZO2_NAME=lzo2-master.zip
LZO2_SOURCE=lzo2-master

# rapidjson
RAPIDJSON_DOWNLOAD="https://github.com/miloyip/rapidjson/archive/v1.1.0.tar.gz"
RAPIDJSON_NAME=rapidjson-1.1.0.tar.gz
RAPIDJSON_SOURCE=rapidjson-1.1.0

# ncurses
NCURSES_DOWNLOAD="https://ftp.gnu.org/gnu/ncurses/ncurses-6.0.tar.gz"
NCURSES_NAME=ncurses-6.0.tar.gz
NCURSES_SOURCE=ncurses-6.0

# curl
CURL_DOWNLOAD="https://curl.haxx.se/download/curl-7.54.0.tar.gz"
CURL_NAME=curl-7.54.0.tar.gz
CURL_SOURCE=curl-7.54.0

# RE2
RE2_DOWNLOAD="https://github.com/google/re2/archive/2017-05-01.tar.gz"
RE2_NAME=re2-2017-05-01.tar.gz
RE2_SOURCE=re2-2017-05-01

# boost
BOOST_DOWNLOAD="https://dl.bintray.com/boostorg/release/1.64.0/source/boost_1_64_0.tar.gz"
BOOST_NAME=boost_1_64_0.tar.gz
BOOST_SOURCE=boost_1_64_0

# mysql
MYSQL_DOWNLOAD="https://github.com/mysql/mysql-server/archive/mysql-5.7.18.tar.gz"
MYSQL_NAME=mysql-5.7.18.tar.gz
MYSQL_SOURCE=mysql-server-mysql-5.7.18

# boost for mysql
BOOST_FOR_MYSQL_DOWNLOAD="http://sourceforge.net/projects/boost/files/boost/1.59.0/boost_1_59_0.tar.gz"
BOOST_FOR_MYSQL_NAME=boost_1_59_0.tar.gz
BOOST_FOR_MYSQL_SOURCE=boost_1_59_0

# all thirdparties which need to be downloaded is set in array TP_ARCHIVES
export TP_ARCHIVES=(LIBEVENT OPENSSL THRIFT LLVM CLANG COMPILER_RT PROTOBUF GFLAGS GLOG GTEST RAPIDJSON SNAPPY GPERFTOOLS ZLIB LZ4 BZIP LZO2 NCURSES CURL RE2 BOOST MYSQL BOOST_FOR_MYSQL)


text:
FROM intermediate/slave-base

RUN apt-get install -y -qq git curl openjdk-7-jdk openjdk-7-jre


text:
package io.advant.orm.test.testsuite.postgresql;

import io.advant.orm.DBConnection;
import io.advant.orm.DBFactory;
import io.advant.orm.exception.ConnectionException;
import io.advant.orm.exception.OrmException;
import io.advant.orm.test.testcase.PrintUtil;
import io.advant.orm.test.testcase.TestDAO;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

/**
 * @author Marco Romagnolo
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PostgresqlTestDAO {

    private static TestDAO test;

    @BeforeClass
    public static void configure() throws ConnectionException {
        PrintUtil.suite(PostgresqlTestDAO.class.getName());
        DBConnection connection = DBFactory.newInstance(new PostgresqlConfig()).getConnection();
        test = new TestDAO(connection);
    }

    @Test
    public void test1_insert() throws OrmException {
        test.insert();
    }

    @Test
    public void test2_findAll() throws OrmException {
        test.findAll();
    }

    @Test
    public void test3_find() throws OrmException {
        test.find();
    }

    @Test
    public void test4_update() throws OrmException {
        test.update();
    }

    @Test
    public void test5_delete() throws OrmException {
        test.delete();
    }

    @Test
    public void test6_deleteAll() throws OrmException {
        test.deleteAll();
    }

    @AfterClass
    public static void disconnect() throws ConnectionException {
        DBFactory.getInstance().disconnect();
    }
}


text:
package com.sandradita.lg.quick_settings.properties;

import android.content.Context;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;

import com.sandradita.lg.quick_settings.R;
import com.sandradita.lg.quick_settings.helpers.ModeHelper;
import com.sandradita.lg.quick_settings.modes.Mode;
import com.sandradita.lg.quick_settings.properties.abs.Property;

/**
 * @author aditkovskaya
 */

public class SimProperty extends Property {

    private SubscriptionManager subscriptionManager;
    private TelephonyManager telephonyManager;

    public SimProperty(Context context) {
        super(context, R.string.property_title_sim_card, R.drawable.ic_sim_card);
        subscriptionManager = SubscriptionManager.from(context);
        telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        setChangeable(false);
    }

    @Override
    public Mode defineCurrentMode() {
        return getModeByCurrentId();
    }

    @Override
    public Mode getModeByCurrentId() {
        return ModeHelper.createOnMode(telephonyManager.getSimOperatorName(), 1, R.drawable.ic_sim_card);
    }

    @Override
    protected void applyMode(int mode) {
        // It can't be changed programmatically for now.
    }

    /**
     * @return true, if device has two sim cards.
     */
    public boolean isDualSim() {
        return subscriptionManager.getActiveSubscriptionInfoCount() == 2;
    }

}


text:
package com.unitybars.r2d2.entity.response;

/**
 * Created by oleg.nestyuk
 * Date: 06-Mar-17.
 */
public class TaskIdJson {
    private String taskId;

    public TaskIdJson() {
    }

    public TaskIdJson(String taskId) {
        this.taskId = taskId;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }
}


text: Ko te katoa o nga tangata i te whanaungatanga mai e watea ana i nga here katoa; e tauriterite ana hoki nga mana me nga tika. E whakawhiwhia ana hoki ki a ratou te ngakau whai whakaaro me te hinengaro mohio ki te tika me te he, a e tika ana kia meinga te mahi a tetahi ki tetahi me ma roto atu i te wairua o te noho tahi, ano he teina he tuakana i ringa i te whakaaro kotahi.


text:
{% load staticfiles i18n %}

  <title>Functional Accessibility Evaluator Invoice: {{payment.invoice_number}}</title>

  <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
  <link rel="stylesheet" href="{% static 'css/bootstrap-theme.css' %}">

  <link rel="stylesheet" href="{% static 'css/bootstrap-accessibility.css' %}">
  <link rel="stylesheet" href="{% static 'css/bootstrap-sortable.css' %}">

    <imFunctional Accessibility Evaluator

Invoice

Invoice Number: {{payment.invoice_number}}

Issue Date: {{payment.reference_time|date:"j M Y"}}

From:

Division of Disability Resources Education Services

College of Applied Health Sciences

University of Illinois

1207 S. Oak Street

Champaign, IL 61820

(217) 244-5870

To:

Username: {{payment.user.username}}

Name: {{payment.user.first_name}} {{payment.user.last_name}}

      {% if user_profile.dept %}
Department: {{user_profile.dept}}
{% endif %}
      {% if user_profile.org  %}
Organization: {{user_profile.org }}
{% endif %}

Charges and Payment

          Date
          Subscription Type
          Price

          {{payment.reference_time|date:"j M Y"}}
          {{payment.account_type}}

Permanent Archived Reports: {{payment.account_type.max_permanent}}

Max Depth of Spidering: {{payment.account_type.max_depth}}

Max web pages per report: {{payment.account_type.max_pages}}

Subscription end date: {{payment.subscription_end|date:"j M Y"}}

          ${{payment.subscription_cost}}

          Payment
          ${{payment.subscription_cost}}

          Balance
          $0


text:
using System;
using System.Collections.Generic;
using UnityEngine.Events;

// @cond doxygen ignore
namespace UnityEngine.UI
{
    public class MyObjectPool<T> where T : new()
    {
        private readonly Stack<T> m_Stack = new Stack<T>();

        private readonly UnityAction<T> m_ActionOnGet;

        private readonly UnityAction<T> m_ActionOnRelease;

        public int countAll
        {
            get;
            private set;
        }

        public int countActive
        {
            get
            {
                return this.countAll - this.countInactive;
            }
        }

        public int countInactive
        {
            get
            {
                return this.m_Stack.Count;
            }
        }

        public MyObjectPool(UnityAction<T> actionOnGet, UnityAction<T> actionOnRelease)
        {
            this.m_ActionOnGet = actionOnGet;
            this.m_ActionOnRelease = actionOnRelease;
        }

        public T Get()
        {
            T t;
            if (this.m_Stack.Count == 0)
            {
                t = ((default(T) == null) ? Activator.CreateInstance<T>() : default(T));
                this.countAll++;
            }
            else
            {
                t = this.m_Stack.Pop();
            }
            if (this.m_ActionOnGet != null)
            {
                this.m_ActionOnGet(t);
            }
            return t;
        }

        public void Release(T element)
        {
            if (this.m_Stack.Count > 0 && object.ReferenceEquals(this.m_Stack.Peek(), element))
            {
                if (Debug.isDebugBuild)
                    Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
            }
            if (this.m_ActionOnRelease != null)
            {
                this.m_ActionOnRelease(element);
            }
            this.m_Stack.Push(element);
        }
    }
}
// @endcond


text:
<!DOCTYPE html>

    <link rel="stylesheet" href="../bower_components/leaflet/dist/leaflet.css" />

        {{ geojson.selected.properties.name || 'No country'}}

Map center: [ lat: {{ center.lat | number:4 }}, lng: {{ center.lng | number:4 }} ]

{{ country.name }}

    <leaflet center="center" events="events" geojson="geojson"></leaflet>


text:
"""
Ensure that "pavement.py" are run with the expected paver version.

EXAMPLE:

    # -- file:pavement.py
    from paver.easy import *
    sys.path.insert(0, ".")
    from paver_ext import paver_require

    paver_require.min_version("1.2")
"""

from paver.easy import error
from paver.release import VERSION as paver_version
import sys

def min_version(min_version):
    """
    Utility function to ensure that a minimal paver version is used.
    Aborts paver execution if expectation is not met.

    :param min_version: Minimum paver version that is required (as string).
    """
    if not (paver_version >= min_version):
        error("REQUIRE: paver >= %s (actually: %s)" % (min_version, paver_version))
        error("ABORT: Here.")
        sys.exit(1)

def assert_min_version(min_version):
    assert paver_version >= min_version, \
           "REQUIRE: paver >= %s (actually: %s)" % (min_version, paver_version)


text:
#ifndef ALIGENAMPT_H
#define ALIGENAMPT_H

/* $Id$ */

#include "AliGenMC.h"
#include <TString.h>

class TAmpt;
class TParticle;
class TClonesArray;
class TGraph;
class AliGenHijingEventHeader;

class AliGenAmpt : public AliGenMC
{
  enum {kNoTrigger, kHardProcesses, kDirectPhotons};

  public:
    AliGenAmpt();
    AliGenAmpt(Int_t npart);
    virtual ~AliGenAmpt();

    virtual void    SetDecay(Bool_t b)                {fDecay = b;}
    virtual TAmpt  *Ampt() { return fAmpt; }
    virtual void    Generate();
    virtual void    Init();
    virtual void    SetSeed(UInt_t seed);
    virtual void    SetEnergyCMS(Float_t energy=5500) {fEnergyCMS=energy;}
    virtual void    SetReferenceFrame(TString frame="CMS")
	{fFrame=frame;}
    virtual void    SetImpactParameterRange(Float_t bmin = 0, Float_t bmax = 15.)
	{fMinImpactParam=bmin; fMaxImpactParam=bmax;}
    virtual void    KeepFullEvent()                   {fKeep      =1;     }
    virtual void    SetJetQuenching(Int_t flag=1)     {fQuench     = flag;}
    virtual void    SetShadowing(Int_t flag=1)        {fShadowing  = flag;}
    virtual void    SetDecaysOff(Int_t flag=1)        {fDecaysOff  = flag;}
    virtual void    SetTrigger(Int_t flag=kNoTrigger) {fTrigger    = flag;}
    virtual void    SetFlavor(Int_t flag=0)           {fFlavor     = flag;}
    virtual void    SetEvaluate(Int_t flag=0)         {fEvaluate   = flag;}
    virtual void    SetSelectAll(Int_t flag=0)        {fSelectAll  = flag;}
    virtual void    SetRadiation(Int_t flag=3)        {fRadiation  = flag;}
    virtual void    SetSpectators(Int_t spects=1)     {fSpectators = spects;}
    virtual void    SetDecayer(AliDecayer *decayer)   {fDecayer = decayer;}
    virtual void    SetPtHardMin(Float_t ptmin)       {fPtHardMin  = ptmin;}
    virtual void    SetPtHardMax(Float_t ptmax)       {fPtHardMax  = ptmax;}
    virtual void    SetPtJet(Float_t ptmin)           {fPtMinJet   = ptmin;}
    virtual void    SetSimpleJets(Int_t flag=0)       {fSimpleJet  = flag;}
    virtual void    SetNoGammas(Int_t flag=0)         {fNoGammas   = flag;}
    virtual void    SetJetEtaRange(Float_t etamin = -20., Float_t etamax = 20.)
	{fEtaMinJet = etamin; fEtaMaxJet = etamax;}
    virtual void    SetJetPhiRange(Float_t phimin = -180., Float_t phimax = 180.)
	{fPhiMinJet = TMath::Pi()*phimin/180.; fPhiMaxJet = TMath::Pi()*phimax/180.;}
    virtual void    SetBoostLHC(Int_t flag = 0)       {fLHC        = flag;}
    virtual void    SetRandomPz(Bool_t flag = 0)      {fRandomPz   = flag;}
    virtual void    SwitchOffHeavyQuarks(Bool_t flag = kTRUE) {fNoHeavyQuarks = flag;}
    virtual void    SetIsoft(Int_t i)                         {fIsoft = i;  }
    virtual void    SetNtMax(Int_t max)                       {fNtMax = max;}
    virtual void    SetIpop(Int_t pop)                        {fIpop  = pop;}
    virtual void    SetXmu(Float_t m)                         {fXmu   = m;  }
    virtual void    SetAlpha(Float_t alpha)                   {fAlpha = alpha;            }
    virtual void    SetStringFrag(Float_t a, Float_t b)       {fStringA = a; fStringB = b;}

    // Getters
    virtual TString GetReferenceFrame()  const {return fFrame;}
    virtual void    GetImpactParameterRange(Float_t& bmin, Float_t& bmax) const
	{bmin = fMinImpactParam; bmax = fMaxImpactParam;}
    virtual Int_t   GetJetQuenching()                    const {return fQuench;}
    virtual Int_t   GetShadowing()                       const {return fShadowing;}
    virtual Int_t   GetTrigger()                         const {return fTrigger;}
    virtual Int_t   GetFlavor()                          const {return fFlavor;}
    virtual Int_t   GetRadiation()                       const {return fRadiation;}
    virtual Int_t   GetSpectators()                      const {return fSpectators;}
    virtual Float_t GetPtHardMin()                       const {return fPtHardMin;}
    virtual Float_t GetPtHardMax()                       const {return fPtHardMax;}
    virtual Float_t GetPtJet()                           const {return fPtMinJet;}
    virtual void    GetJetEtaRange(Float_t& etamin, Float_t& etamax)      const
	{etamin = fEtaMinJet; etamax = fEtaMaxJet;}
    virtual void    GetJetPhiRange(Float_t& phimin, Float_t& phimax)      const
	{phimin = fPhiMinJet*180./TMath::Pi(); phimax = fPhiMaxJet*180./TMath::Pi();}
    const TClonesArray *GetParticles() const { return &fParticles; }

    // Physics Routines
    virtual Bool_t  ProvidesCollisionGeometry() const {return kTRUE;}
    virtual void    EvaluateCrossSections();
    virtual TGraph* CrossSection()     {return fDsigmaDb;}
    virtual TGraph* BinaryCollisions() {return fDnDb;}
    virtual Bool_t  CheckTrigger();
    virtual Bool_t  IsThisAKnownParticle(TParticle *thisGuy);
    virtual void    SetRandomReactionPlane(Bool_t on=kTRUE){fRotating=on;};

  protected:
    Bool_t      SelectFlavor(Int_t pid);
    void        MakeHeader();

    AliDecayer              *fDecayer;
    TString                  fFrame;           // Reference frame
    Float_t                  fMinImpactParam;  // minimum impact parameter
    Float_t                  fMaxImpactParam;  // maximum impact parameter
    Int_t                    fKeep;            // Flag to keep full event information
    Int_t                    fQuench;          // Flag to switch on jet quenching
    Int_t                    fShadowing;       // Flag to switch on nuclear effects on parton distribution function
    Int_t                    fDecaysOff;       // Flag to turn off decays of pi0, K_s, D, Lambda, sigma
    Int_t                    fTrigger;         // Trigger type
    Int_t                    fEvaluate;        // Evaluate total and partial cross-sections
    Int_t                    fSelectAll;       // Flag to write the full event
    Int_t                    fFlavor;          // Selected particle flavor 4: charm+beauty 5: beauty
    Float_t                  fKineBias;        // Bias from kinematic selection
    Int_t                    fTrials;          // Number of trials
    Float_t                  fXsection;        // Cross-section
    TAmpt                   *fAmpt;            //!Ampt
    Float_t                  fPtHardMin;       // lower pT-hard cut
    Float_t                  fPtHardMax;       // higher pT-hard cut
    Int_t                    fSpectators;      // put spectators on stack
    TGraph*                  fDsigmaDb;        // dSigma/db for the system
    TGraph*                  fDnDb;            // dNBinaryCollisions/db
    Float_t                  fPtMinJet;        // Minimum Pt of triggered Jet
    Float_t                  fEtaMinJet;       // Minimum eta of triggered Jet
    Float_t                  fEtaMaxJet;       // Maximum eta of triggered Jet
    Float_t                  fPhiMinJet;       // At least one of triggered Jets must be in this
    Float_t                  fPhiMaxJet;       // phi range
    Int_t                    fRadiation;       // Flag to switch on/off initial and final state radiation
    Int_t                    fSimpleJet;       // Flag to produce simple tiggered jet topology
    Int_t                    fNoGammas;        // Don't write gammas if flag "on"
    Int_t 	             fProjectileSpecn; // Num. of spectator neutrons from projectile nucleus
    Int_t 	             fProjectileSpecp; // Num. of spectator protons from projectile nucleus
    Int_t 	             fTargetSpecn;     // Num. of spectator neutrons from target nucleus
    Int_t 	             fTargetSpecp;     // Num. of spectator protons from target nucleus
    Int_t                    fLHC;             // Assume LHC as lab frame
    Bool_t                   fRandomPz;        // Randomise sign of pz event by event
    Bool_t                   fNoHeavyQuarks;   // If true no heavy quarks are produced
    Int_t                    fIsoft;           // ISOFT (D=1): select Default AMPT or String Melting
    Int_t                    fNtMax;           // NTMAX: number of timesteps (D=150)
    Int_t                    fIpop;            // (D=1,yes;0,no) flag for popcorn mechanism(netbaryon stopping)
    Float_t                  fXmu;             // parton screening mass in fm^(-1) (D=3.2264d0)
    Float_t                  fAlpha;           // alpha running (fixed) coupling
    Float_t                  fStringA;         // string frag parameter A
    Float_t                  fStringB;         // string frag parameter B
    Float_t                  fEventTime;       // The event time
    AliGenHijingEventHeader *fHeader;          // header
    Bool_t                   fDecay;           // decay "long-lived" particles
    Bool_t                   fRotating;        // Random reaction plane on/off

  private:
    AliGenAmpt(const AliGenAmpt &Ampt);
    AliGenAmpt &  operator=(const AliGenAmpt & rhs);

    // adjust the weight from kinematic cuts
    void   AdjustWeights();
    // check seleted daughters
    Bool_t DaughtersSelection(TParticle* iparticle);
    // check if stable
    Bool_t Stable(TParticle*  particle) const;

    ClassDef(AliGenAmpt, 4) // AliGenerator interface to Ampt
};
#endif


text:
<?php
namespace Kondrat\DesignPatterns\Factory\SimpleFactory;

class SimplePizzaFactory
{
    public function createPizza($type)
    {
        if ($type == PizzaStore::PIZZA_PEPPERONI) {
            return new PepperoniPizza();
        }

        if ($type == PizzaStore::PIZZA_VEGGIE) {
            return new VeggiePizza();
        }

        if ($type == PizzaStore::PIZZA_CLAM) {
            return new ClamPizza();
        }

        return new CheesePizza();
    }
}