text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Evgeniy Andreev, Thoralf Klein, Weijie Lin, Bjoern Esser,
 *          Viktor Gal
 */

#include <shogun/lib/CircularBuffer.h>
#include <shogun/lib/Tokenizer.h>
#include <shogun/io/SGIO.h>

#include <cstdio>
#include <cstring>

using namespace shogun;

CCircularBuffer::CCircularBuffer()
{
	init();
}

CCircularBuffer::CCircularBuffer(int32_t buffer_size)
{
	init();

	m_buffer=SGVector<char>(buffer_size);
	m_buffer_end=m_buffer.vector+m_buffer.vlen;

	m_begin_pos=m_buffer.vector;
	m_end_pos=m_begin_pos;

	m_bytes_available=m_buffer.vlen;
}

CCircularBuffer::~CCircularBuffer()
{
	SG_UNREF(m_tokenizer);
}

void CCircularBuffer::set_tokenizer(CTokenizer* tokenizer)
{
	SG_REF(tokenizer);
	SG_UNREF(m_tokenizer);
	m_tokenizer=tokenizer;
}

int32_t CCircularBuffer::push(SGVector<char> source)
{
	if (source.vector==NULL || source.vlen==0)
	{
		SG_ERROR("CCircularBuffer::push(SGVector<char>):: Invalid parameters! Source shouldn't be NULL or zero sized\n");
		return -1;
	}

	int32_t bytes_to_write;
	if (source.vlen>m_bytes_available)
		bytes_to_write=m_bytes_available;
	else
		bytes_to_write=source.vlen;

	if (bytes_to_write==0)
		return 0;

	// determine which part of the memory block is free to read
	if (m_end_pos>=m_begin_pos)
	{
		auto bytes_to_memory_end=m_buffer.vlen-std::distance(m_buffer.vector, m_end_pos);
		if (bytes_to_memory_end<bytes_to_write)
		{
			// we need write as at end of memory block and at begin
			// because logical structure of buffer is ring
			int32_t first_chunk_size=bytes_to_memory_end;
			int32_t second_chunk_size=bytes_to_write-first_chunk_size;

			bytes_to_write=append_chunk(source.vector, first_chunk_size, false);
			bytes_to_write+=append_chunk(source.vector+first_chunk_size, second_chunk_size, true);
		}
		else
		{
			bytes_to_write=append_chunk(source.vector, bytes_to_write, false);
		}
	}
	else
	{
		bytes_to_write=append_chunk(source.vector, bytes_to_write, false);
	}

	return bytes_to_write;
}

int32_t CCircularBuffer::push(FILE* source, int32_t source_size)
{
	if (source==NULL || source_size==0)
	{
		SG_ERROR("CCircularBuffer::push(FILE*, int32_t):: Invalid parameters! Source shouldn't be NULL or zero sized\n");
		return -1;
	}

	int32_t bytes_to_write;
	if (source_size>m_bytes_available)
		bytes_to_write=m_bytes_available;
	else
		bytes_to_write=source_size;

	if (bytes_to_write==0)
		return 0;

	// determine which part of the memory block is free to read
	if (m_end_pos>=m_begin_pos)
	{
		int32_t bytes_to_memory_end=m_buffer.vlen-std::distance(m_buffer.vector, m_end_pos);
		if (bytes_to_memory_end<bytes_to_write)
		{
			// we need write as at end of memory block and at begin
			// because logical structure of buffer is ring
			int32_t first_chunk_size=bytes_to_memory_end;
			int32_t second_chunk_size=bytes_to_write-first_chunk_size;

			bytes_to_write=append_chunk(source, first_chunk_size, false);
			bytes_to_write+=append_chunk(source, second_chunk_size, true);
		}
		else
		{
			bytes_to_write=append_chunk(source, bytes_to_write, false);
		}
	}
	else
	{
		bytes_to_write=append_chunk(source, bytes_to_write, false);
	}

	return bytes_to_write;
}

SGVector<char> CCircularBuffer::pop(int32_t num_bytes)
{
	SGVector<char> result;

	int32_t bytes_to_read;
	if (num_bytes>m_bytes_count)
		bytes_to_read=m_bytes_count;
	else
		bytes_to_read=num_bytes;

	if (bytes_to_read==0)
		return 0;

	// determine which part of the memory block will be read
	if (m_begin_pos>=m_end_pos)
	{
		int32_t bytes_to_memory_end=m_buffer.vlen-(m_begin_pos-m_buffer.vector);
		if (bytes_to_memory_end<bytes_to_read)
		{
			// read continious block from end of memory and from begin
			int32_t first_chunk_size=bytes_to_memory_end;
			int32_t second_chunk_size=bytes_to_read-first_chunk_size;

			detach_chunk(&result.vector, &result.vlen, 0, first_chunk_size, false);
			detach_chunk(&result.vector, &result.vlen, first_chunk_size, second_chunk_size, true);
		}
		else
		{
			detach_chunk(&result.vector, &result.vlen, 0, bytes_to_read, false);
		}
	}
	else
	{
		detach_chunk(&result.vector, &result.vlen, 0, bytes_to_read, false);
	}

	return result;
}

bool CCircularBuffer::has_next()
{
	if (m_tokenizer==NULL)
	{
		SG_ERROR("CCircularBuffer::has_next():: Tokenizer is not initialized\n");
		return false;
	}

	if (m_bytes_count==0)
		return false;

	auto head_length=std::distance(m_begin_pos, m_buffer_end);

	// determine position of finder pointer in memory block
	if (m_last_idx<head_length)
	{
		if (m_end_pos>=m_begin_pos && m_bytes_available!=0)
		{
			return has_next_locally(m_begin_pos+m_last_idx, m_end_pos);
		}
		else
		{
			bool temp=false;
			temp=has_next_locally(m_begin_pos+m_last_idx, m_buffer_end);
			return (temp > 0)
				? temp
				: has_next_locally(m_buffer.vector+m_last_idx-head_length, m_end_pos);
		}
	}
	else
	{
		return has_next_locally(m_buffer.vector+m_last_idx-head_length, m_end_pos);
	}

	return false;
}

index_t CCircularBuffer::next_token_idx(index_t &start)
{
	index_t end;

	if (m_tokenizer==NULL)
	{
		SG_ERROR("CCircularBuffer::next_token_idx(index_t&):: Tokenizer is not initialized\n");
		return 0;
	}

	if (m_bytes_count==0)
		return m_bytes_count;

	auto tail_length=std::distance(m_buffer.vector, m_end_pos);
	auto head_length=std::distance(m_begin_pos, m_buffer_end);

	// determine position of finder pointer in memory block
	if (m_last_idx<head_length)
	{
		if (m_end_pos>=m_begin_pos && m_bytes_available!=0)
		{
			end=next_token_idx_locally(start, m_begin_pos+m_last_idx, m_end_pos);
			if (end<=m_bytes_count)
				return end;
		}
		else
		{
			index_t temp_start;

			// in this case we should find first at end of memory block
			end=next_token_idx_locally(start, m_begin_pos+m_last_idx, m_buffer_end);

			if (end<head_length)
				return end;

			// and then at begin
			end=next_token_idx_locally(temp_start, m_buffer.vector+m_last_idx-head_length, m_end_pos);

			if (start>=head_length)
				start=temp_start;

			return end;
		}
	}
	else
	{
		end=next_token_idx_locally(start, m_buffer.vector+m_last_idx-head_length, m_end_pos);
		if (end-head_length<=tail_length)
			return end;
	}

	start=0;
	return start;
}

void CCircularBuffer::skip_characters(int32_t num_chars)
{
	auto head_length = std::distance(m_begin_pos, m_buffer_end);
	if (head_length >= num_chars)
		move_pointer(&m_begin_pos, m_begin_pos+num_chars);
	else
		move_pointer(&m_begin_pos, m_buffer.vector+num_chars-head_length);

	m_last_idx-=num_chars;
	if (m_last_idx<0)
		m_last_idx=0;

	m_bytes_available+=num_chars;
	m_bytes_count-=num_chars;
}

void CCircularBuffer::clear()
{
	m_begin_pos=m_buffer.vector;
	m_end_pos=m_begin_pos;

	m_last_idx=0;
	m_bytes_available=m_buffer.vlen;
	m_bytes_count=0;
}

void CCircularBuffer::init()
{
	m_buffer=SGVector<char>();
	m_buffer_end=NULL;
	m_tokenizer=NULL;

	m_begin_pos=NULL;
	m_end_pos=NULL;

	m_last_idx=0;
	m_bytes_available=0;
	m_bytes_count=0;
}

int32_t CCircularBuffer::append_chunk(const char* source, int32_t source_size,
					bool from_buffer_begin)
{
	if (source==NULL || source_size==0)
	{
		SG_ERROR("CCircularBuffer::append_chunk(const char*, int32_t, bool):: Invalid parameters!\
				Source shouldn't be NULL or zero sized\n");
		return -1;
	}

	if (from_buffer_begin)
		m_end_pos=m_buffer.vector;

	sg_memcpy(m_end_pos, source, source_size);
	move_pointer(&m_end_pos, m_end_pos+source_size);

	m_bytes_available-=source_size;
	m_bytes_count+=source_size;

	return source_size;
}

int32_t CCircularBuffer::append_chunk(FILE* source, int32_t source_size,
					bool from_buffer_begin)
{
	int32_t actually_read=fread(m_end_pos, sizeof(char), source_size, source);

	if (from_buffer_begin && actually_read==source_size)
		m_end_pos=m_buffer.vector;
	move_pointer(&m_end_pos, m_end_pos+actually_read);

	m_bytes_available-=actually_read;
	m_bytes_count+=actually_read;

	return actually_read;
}

void CCircularBuffer::detach_chunk(char** dest, int32_t* dest_size, int32_t dest_offset, int32_t num_bytes,
					bool from_buffer_begin)
{
	if (dest==NULL || dest_size==NULL)
	{
		SG_ERROR("CCircularBuffer::detach_chunk(...):: Invalid parameters! Pointers are NULL\n");
		return;
	}

	if (*dest==NULL)
	{
		*dest=SG_MALLOC(char, num_bytes+dest_offset);
		*dest_size=num_bytes+dest_offset;
	}

	if (*dest_size<num_bytes+dest_offset)
	{
		*dest=SG_REALLOC(char, *dest, *dest_size, num_bytes+dest_offset);
		*dest_size=num_bytes+dest_offset;
	}

	if (from_buffer_begin)
		m_begin_pos=m_buffer.vector;

	sg_memcpy(*dest+dest_offset, m_begin_pos, num_bytes);
	move_pointer(&m_begin_pos, m_begin_pos+num_bytes);

	m_last_idx-=num_bytes;
	if (m_last_idx<0)
		m_last_idx=0;

	m_bytes_available+=num_bytes;
	m_bytes_count-=num_bytes;
}

bool CCircularBuffer::has_next_locally(char* part_begin, char* part_end)
{
	auto num_bytes_to_search=std::distance(part_begin, part_end);

	SGVector<char> buffer_part(part_begin, num_bytes_to_search, false);
	m_tokenizer->set_text(buffer_part);

	return m_tokenizer->has_next();
}

index_t CCircularBuffer::next_token_idx_locally(index_t &start, char* part_begin, char* part_end)
{
	index_t end=0;
	auto num_bytes_to_search=std::distance(part_begin, part_end);
	if (num_bytes_to_search<=0)
	{
		start=0;
		return m_last_idx;
	}

	SGVector<char> buffer_part(part_begin, num_bytes_to_search, false);
	m_tokenizer->set_text(buffer_part);

	end=m_tokenizer->next_token_idx(start);

	start+=m_last_idx;
	m_last_idx+=end;

	if (end==num_bytes_to_search)
		return m_last_idx;
	else
		return m_last_idx++;
}

void CCircularBuffer::move_pointer(char** pointer, char* new_position)
{
	*pointer = (new_position >= m_buffer_end)
		? m_buffer.vector
		: new_position;
}


text:
'use strict';

const service = require('feathers-mongoose');
const game = require('./game-model');
const hooks = require('./hooks');

module.exports = function() {
  const app = this;

  const options = {
    Model: game,
    paginate: {
      default: 5,
      max: 25
    }
  };

  // Initialize our service with any options it requires
  app.use('/games', service(options));

  // Get our initialize service to that we can bind hooks
  const gameService = app.service('/games');

  // Set up our before hooks
  gameService.before(hooks.before);

  // Set up our after hooks
  gameService.after(hooks.after);
};

redpajama_set_name: RedPajamaGithub


text:
all: recover

recover: recover.c
	clang -ggdb3 -O0 -std=c11 -Wall -Werror -o recover recover.c

clean:
	rm -f *.o a.out core recover


text:
using System;
using System.Linq;
using Microsoft.Azure;

namespace Microsoft.WindowsAzure.Management.WebSites.Models
{
    /// <summary>
    /// The Is Hostname Available Web Site operation response.
    /// </summary>
    public partial class WebSiteIsHostnameAvailableResponse : AzureOperationResponse
    {
        private bool _isAvailable;

        /// <summary>
        /// Optional. Indicates if the site name is available.
        /// </summary>
        public bool IsAvailable
        {
            get { return this._isAvailable; }
            set { this._isAvailable = value; }
        }

        /// <summary>
        /// Initializes a new instance of the
        /// WebSiteIsHostnameAvailableResponse class.
        /// </summary>
        public WebSiteIsHostnameAvailableResponse()
        {
        }
    }
}


text:
package org.onosproject.incubator.net.virtual;

import org.onosproject.net.DeviceId;
import org.onosproject.net.meter.Meter;
import org.onosproject.net.meter.MeterEvent;
import org.onosproject.net.meter.MeterFailReason;
import org.onosproject.net.meter.MeterFeatures;
import org.onosproject.net.meter.MeterFeaturesKey;
import org.onosproject.net.meter.MeterKey;
import org.onosproject.net.meter.MeterOperation;
import org.onosproject.net.meter.MeterStoreDelegate;
import org.onosproject.net.meter.MeterStoreResult;

import java.util.Collection;
import java.util.concurrent.CompletableFuture;

public interface VirtualNetworkMeterStore
        extends VirtualStore<MeterEvent, MeterStoreDelegate> {

    /**
     * Adds a meter to the store.
     *
     * @param networkId a virtual network identifier
     * @param meter a meter
     * @return a future indicating the result of the store operation
     */
    CompletableFuture<MeterStoreResult> storeMeter(NetworkId networkId, Meter meter);

    /**
     * Deletes a meter from the store.
     *
     * @param networkId a virtual network identifier
     * @param meter a meter
     * @return a future indicating the result of the store operation
     */
    CompletableFuture<MeterStoreResult> deleteMeter(NetworkId networkId, Meter meter);

    /**
     * Adds the meter features to the store.
     *
     * @param networkId a virtual network identifier
     * @param meterfeatures the meter features
     * @return the result of the store operation
     */
    MeterStoreResult storeMeterFeatures(NetworkId networkId, MeterFeatures meterfeatures);

    /**
     * Deletes the meter features from the store.
     *
     * @param networkId a virtual network identifier
     * @param deviceId the device id
     * @return a future indicating the result of the store operation
     */
    MeterStoreResult deleteMeterFeatures(NetworkId networkId, DeviceId deviceId);

    /**
     * Updates a meter whose meter id is the same as the passed meter.
     *
     * @param networkId a virtual network identifier
     * @param meter a new meter
     * @return a future indicating the result of the store operation
     */
    CompletableFuture<MeterStoreResult> updateMeter(NetworkId networkId, Meter meter);

    /**
     * Updates a given meter's state with the provided state.
     *
     * @param networkId a virtual network identifier
     * @param meter a meter
     */
    void updateMeterState(NetworkId networkId, Meter meter);

    /**
     * Obtains a meter matching the given meter key.
     *
     * @param networkId a virtual network identifier
     * @param key a meter key
     * @return a meter
     */
    Meter getMeter(NetworkId networkId, MeterKey key);

    /**
     * Returns all meters stored in the store.
     *
     * @param networkId a virtual network identifier
     * @return a collection of meters
     */
    Collection<Meter> getAllMeters(NetworkId networkId);

    /**
     * Update the store by deleting the failed meter.
     * Notifies the delegate that the meter failed to allow it
     * to nofity the app.
     *
     * @param networkId a virtual network identifier
     * @param op a failed meter operation
     * @param reason a failure reason
     */
    void failedMeter(NetworkId networkId, MeterOperation op, MeterFailReason reason);

    /**
     * Delete this meter immediately.
     *
     * @param networkId a virtual network identifier
     * @param m a meter
     */
    void deleteMeterNow(NetworkId networkId, Meter m);

    /**
     * Retrieve maximum meters available for the device.
     *
     * @param networkId a virtual network identifier
     * @param key the meter features key
     * @return the maximum number of meters supported by the device
     */
    long getMaxMeters(NetworkId networkId, MeterFeaturesKey key);
}


text:
package org.appng.cli.commands.permission;

import org.appng.api.BusinessException;
import org.appng.cli.ExecutableCliCommand;
import org.appng.cli.prettytable.PrettyTable;
import org.appng.cli.prettytable.TableConstants;
import org.junit.Assert;

public class ListPermissionTest extends BasePermissionTest {

	private ListPermissions command;

	public ExecutableCliCommand getCommand() {
		try {
			new AddPermission(APPLICATION, ROLE, PERMISSIONS).execute(cliEnv);
		} catch (BusinessException e) {
			Assert.fail(e.getMessage());
		}
		this.command = new ListPermissions(APPLICATION, ROLE);
		return command;
	}

	public void validate() {
		PrettyTable prettyTable = command.getPrettyTable();
		validateTableSize(prettyTable, 2);
		validateCell(prettyTable, 1, TableConstants.ID, "1");
		validateCell(prettyTable, 1, TableConstants.NAME, "debug");
		validateCell(prettyTable, 2, TableConstants.ID, "2");
		validateCell(prettyTable, 2, TableConstants.NAME, "foobar");
	}

}


text:
CSBitVectors
============

This is:
---
a C# implementation of data structures known as _succinct bit vectors_.

A _Succinct Bit Vector_ is:
---
a bit vector augmented with an "index", such that
- the size of the index is "insignificant" compared to that of the vector itself,
- the index is exploited to answer the following queries in sublinear time:
  1. _rank_: returns the number of 0s or 1s within a given range of the vector

    ```
      rank : BitVector -> Nat -> {0, 1} -> Nat
      rank vec k b = |{i | i <- [0, ..., k) vec[i] = b }|
    ```

    (N.B. The above claims the specified range is _exclusive_: `i<- [0, ..., k)`,
     some formalisms instead employ _inclusive_ definition for a range: `i <- [0, ..., k]`)
  2. _select_: returns the position of the _k_-th occurrence of 0 or 1:

    ````
      select : BitVector -> Nat -> {0, 1} -> Nat
      select vec k b = i such that vec[i] = b && rank vec (i+1) b = k
    ````

This Implementation Offers:
---
two distinct representation of bit vectors:

- `BitVector` stores an _uncompressed_ bit sequence with its index, and
- `RRRBitVector` stores a _compressed_ bits with index, a la Raman, Raman and Rao, 2002.

Usage:
---
For both representations, an instance is built from a plain-vanilla bit sequence
stored in the helper class `Bits`:

1. Load your bulk data into a list of bytes:

  ```cs
  IList<byte> bulk = /* ...my precious... */;
  ```

2. Instantiate a `Bits` and copy the bulk:

  ```cs
  Bits bits = new Bits(bulk.Length / 8 /* is the initial capacity */);
  bits.push(bulk);
  ```

3. Build a bit vector from `bits`:

  ```cs
  (RRR)BitVector bv = new (RRR)BitVector(bits);
  ```

Supported operations are:

- `rank()/select()` as described above
- `get()` for random access to an arbitrary bit (N.B. random access over a _compressed_ vector is _slow_)
- `write()/read()` for serialization/de-serialization, respectively

See the interface `IBitVector` for the complete list.

Supplements:
---
Two helper classes are supplied besides:

- `Bits`: is, as introduced above, a container for plain-vanilla bit sequences.
  A sequence can be of an arbitrary length (i.e. not necessarily be a multiple of 8, 16, etc.)
- `EliasFanoSequence`: is another instance of "succinct data structures" to encode a
  _non-decreasing_ _finite_ _sequence_ _of_ _natural_ _numbers_ in a "space efficient" way.
  It is used as a part of compressed vector representation, but might be applied for other purposes in your code.

References:
---
Googling "succinct bit vector" or "succinct data structures" will give you a bunch of
well-organized introductory articles.

Specific publications and softwares which my implementation based upon are
listed in each source code.

License:
---
MIT License.


text:
import os
import sys
import yaml
import yoci_config
import logging
import logging.config

DEFAULT_BASE_LOGGING_LEVEL = logging.INFO
DEFAULT_VERBOSE_LOGGING_LEVEL = logging.DEBUG

DEFAULT_CONFIG_FILE = 'config.yml'

def init_logger(base_level=DEFAULT_BASE_LOGGING_LEVEL,
                verbose_level=DEFAULT_VERBOSE_LOGGING_LEVEL,
                logging_config=None):
    """initializes a base logger

    you can use this to init a logger in any of your files.
    this will use config.py's LOGGER param and logging.dictConfig to configure
    the logger for you.

    :param int|logging.LEVEL base_level: desired base logging level
    :param int|logging.LEVEL verbose_level: desired verbose logging level
    :param dict logging_dict: dictConfig based configuration.
     used to override the default configuration from config.py
    :rtype: `python logger`
    """
    if logging_config is None:
        logging_config = {}
    logging_config = logging_config or yoci_config.LOGGER
    # TODO: (IMPRV) only perform file related actions if file handler is
    # TODO: (IMPRV) defined.

    log_dir = os.path.expanduser(
        os.path.dirname(
            yoci_config.LOGGER['handlers']['file']['filename']))
    if os.path.isfile(log_dir):
        sys.exit('file {0} exists - log directory cannot be created '
                 'there. please remove the file and try again.'
                 .format(log_dir))
    try:
        logfile = yoci_config.LOGGER['handlers']['file']['filename']
        d = os.path.dirname(logfile)
        if not os.path.exists(d) and not len(d) == 0:
            os.makedirs(d)
        logging.config.dictConfig(logging_config)
        lgr = logging.getLogger('user')
        # lgr.setLevel(base_level) if not feeder_config.VERBOSE \
        lgr.setLevel(base_level)
        return lgr
    except ValueError as e:
        sys.exit('could not initialize logger.'
                 ' verify your logger config'
                 ' and permissions to write to {0} ({1})'
                 .format(logfile, e))

lgr = init_logger()

def import_config(config_file):
    """returns a configuration object

    :param string config_file: path to config file
    """
    # get config file path
    config_file = config_file or os.path.join(os.getcwd(), DEFAULT_CONFIG_FILE)
    lgr.debug('config file is: {}'.format(config_file))
    # append to path for importing
    # sys.path.append(os.path.dirname(config_file))
    try:
        lgr.debug('importing dict...')
        with open(config_file, 'r') as c:
            return yaml.safe_load(c.read())
    # TODO: (IMPRV) remove from path after importing
    except IOError as ex:
        lgr.error(str(ex))
        raise RuntimeError('cannot access config file')
    except ImportError:
        lgr.warning('config file not found: {}.'.format(config_file))
        raise RuntimeError('missing config file')
    except SyntaxError:
        lgr.error('config file syntax is malformatted. please fix '
                  'any syntax errors you might have and try again.')
        raise RuntimeError('bad config file')


text:
package com.echo5bravo.govre.UI;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.echo5bravo.govre.BLL.BusinessRoute;
import com.echo5bravo.govre.BLL.BusinessSchedule;
import com.echo5bravo.govre.BLL.BusinessStation;
import com.echo5bravo.govre.BLL.BusinessUpdate;
import com.echo5bravo.govre.BLL.BusinessVehicle;
import com.echo5bravo.govre.DAL.BusinessBaseCalDates;
import com.echo5bravo.govre.INFO.CalDates;
import com.echo5bravo.govre.INFO.Device;
import com.echo5bravo.govre.INFO.Route;
import com.echo5bravo.govre.INFO.Station;
import com.echo5bravo.govre.INFO.Update;
import com.echo5bravo.govre.INFO.Vehicle;
import com.echo5bravo.govre.INFO.VehicleBubble;
import com.echo5bravo.govre.UTILS.Common;
import com.echo5bravo.govre.UTILS.CustomItemizedOverlay;
import com.echo5bravo.govre.UTILS.CustomOverlayItem;
import com.echo5bravo.govre.UTILS.RouteOverlay;
import com.echo5bravo.govre.R;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;

public class ActivityGoogleMap extends MapActivity {
	/** Called when the activity is first created. */

	private static final String TAG = ActivityGoogleMap.class.getSimpleName();

	private GoogleAnalyticsTracker googleTracker;

	private static final String PREFS_NAME = "OldPreferences";
	private static final String PREFS_TIME_FORMAT_KEY = "OldTimeFormatKEY";
	private static final String PREFS_STATION_MARKER_KEY = "OldStationMarkerKEY";
	private static final String PREFS_SATELLITE_KEY = "OldSatelliteKEY";
	private static final String PREFS_TRAFFIC_KEY = "OldTrafficKEY";
	private String mOldTimeFormatValue;
	private String mOldStationMarkerValue;
	private boolean mOldSatelliteValue;
	private boolean mOldTrafficValue;

	MapView mapView;
	private Context context;

	private ImageView imgTwitter, imgAlerts, imgSched;
	private ImageView spinner;
	private TextView txtRefresh;
	private TextView txtArrivals;
	private AnimationDrawable spinnerAnim;
	private boolean spinnerOn;
	private ImageView imgNoSignal;
	private boolean noSignalOn;
	private boolean blnGTFSDataLoaded;
	private boolean blnLocalDataLoaded;
	//private int iRefreshCount;

	List<Overlay> mapOverlays;
	ArrayList<Route> myFBGRoutes;
	ArrayList<Route> myMSSRoutes;
	ArrayList<Station> myStations;
	ArrayList<Vehicle> myVehicles;
	ArrayList<Update> myUpdates;
	ArrayList<CalDates> myCalDates;
	//ArrayList<VehicleBubble> myVehicleBubbles;   STILL TESTING
	@SuppressWarnings("rawtypes")
	ArrayList<CustomItemizedOverlay> overlayStations;
	@SuppressWarnings("rawtypes")
	ArrayList<CustomItemizedOverlay> overlayVehicles;

	private MyLocationOverlay myLocationOverlay = null;

	String TodaysScheduleType;

	private ExecutorService TaskExecutorMap;
	private ScheduledExecutorService scheduleTaskExecutorVehicles;
	private ScheduledExecutorService scheduleTaskExecutorUiUpdates;

	double stationLat;
	double stationLong;
	double vehicleLat;
	double vehicleLong;

	private String stationIcon;
	private String stationIconString;
	private String stationAddress;
	private String stationIconName;

	private String vehicleIcon;
	private String vehicleIconString;
	private String vehicleInfo;
	private String vehicleIconName;

	private String stationMarker;

	GeoPoint srcGeoPoint;
	GeoPoint destGeoPoint;

	int LoopCounter = 0;

	String lblMsg = "";

	Drawable drawable2;
	CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(R.style.Theme_BlueMoon);
		this.setContentView(R.layout.googlemap_layout);

		//myVehicleBubbles = new ArrayList<VehicleBubble>();  STILL TESTING

		//Start Google Analytics Tracker
		//-------------------------------------------------------------------------------------------------
		googleTracker = GoogleAnalyticsTracker.getInstance();
		googleTracker.setDebug(Boolean.parseBoolean(this.getString(R.bool.ga_debug)));
		googleTracker.setDryRun(Boolean.parseBoolean(this.getString(R.bool.ga_dryrun)));
		googleTracker.startNewSession(this.getString(R.string.ga_api_key), 60, this);

		int CV_SLOT_1 = 1;	//Slot 1 Tracks Device Orientation
		//int CV_SLOT_2 = 2;	//Slot 2 Unassigned
		//int CV_SLOT_3 = 3;	//Slot 3 Unassigned
		//int CV_SLOT_4 = 4;	//Slot 4 Unassigned
		//int CV_SLOT_5 = 5;	//Slot 5 Unassigned

		//Track Device's Current Orientation
		googleTracker.setCustomVar(CV_SLOT_1,	 //SLOT (Can only track up to 5)
		   "Device Orientation", //NAME
		   Device.getDeviceOrientation(this.getApplicationContext()), 	//VALUE
		   1);	//SCOPE

		/*-------------------------------------------------------------------------------------------------
		NOTE: Add to Activity Handlers:
		 onResume():  googleTracker.trackPageView("/" + TAG);
		 onDestroy(): googleTracker.stopSession();
		-------------------------------------------------------------------------------------------------*/

		context = this;

		mapView = (MapView) findViewById(R.id.mapview);

		spinner = (ImageView) findViewById(R.id.splashSpinner);
		txtRefresh = (TextView) findViewById(R.id.txtrefresh);
		txtArrivals = (TextView) findViewById(R.id.txtarrivals);
		spinnerAnim = (AnimationDrawable) spinner.getBackground();
		imgNoSignal  = (ImageView) findViewById(R.id.imgNoSignal);

		double src_lat = 0.0;
		double src_long = 0.0;

		//Orient the Map Center Point based on the user's device orientation
		if (Device.getDeviceOrientation(this.getApplicationContext()).equals("portrait")){
			//Location: Rippon
			src_lat = 38.613158999999996;
			src_long = -77.254272;
		}
		else
		{
			//Location: Lorton
			src_lat = 38.71252799999999;
			src_long = -77.217865;
		}

		//Location: Union Station
		double dest_lat = 38.897346;
		double dest_long = -77.007337;

		//Set GeoPoints as defaults until the TrainLines are drawn
		srcGeoPoint = new GeoPoint((int) (src_lat * 1E6), (int) (src_long * 1E6));
		destGeoPoint = new GeoPoint((int) (dest_lat * 1E6), (int) (dest_long * 1E6));

		//DrawMap(srcGeoPoint, destGeoPoint, mapView);

		mapView.setBuiltInZoomControls(true);

		mapView.getController().animateTo(srcGeoPoint);  //Focus to Quantico, both TrainLines are visible, looks cleaner.
		mapView.getController().setZoom(11);

		addListenerOnTwitterImage();
        addListenerOnAlert();
        addListenerOnSched();

        //Location and Compass Managers
        myLocationOverlay = new MyLocationOverlay(this, mapView);
        //**mapView.getOverlays().add(myLocationOverlay);

	}

	@Override
    protected void onStop(){
       super.onStop();

       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       SharedPreferences.Editor editor = settings.edit();
       editor.putString(PREFS_TIME_FORMAT_KEY, mOldTimeFormatValue);
       editor.putString(PREFS_STATION_MARKER_KEY, mOldStationMarkerValue);
       editor.putBoolean(PREFS_SATELLITE_KEY, mOldSatelliteValue);
       editor.putBoolean(PREFS_TRAFFIC_KEY, mOldTrafficValue);

       // Commit the edits!
       editor.commit();

       //Moved to OnPause();
       TaskExecutorMap.shutdown();
	   scheduleTaskExecutorVehicles.shutdown();
	   scheduleTaskExecutorUiUpdates.shutdown();

	}

	@Override
	protected void onPause(){
		super.onPause();

		//Stop Progress Spinner
	    spinnerAnim.stop();
		spinner.setVisibility(View.INVISIBLE);

		//Disable location manager
		myLocationOverlay.disableMyLocation();
		myLocationOverlay.disableCompass();
	}

	@Override
	protected void onStart(){
		super.onStart();

		 TaskExecutorMap = Executors.newSingleThreadExecutor();
			TaskExecutorMap.execute(new Runnable() {
			    public void run() {

			    	//Log.d(TAG, "LOCAL ARRAYS LOADING....");

			    	//Load Singleton ArrayLists
			    	LoadCalDates();
				    TodaysScheduleType = Common.TodaysScheduleType(context, myCalDates, true);
		    		LoadFBGRoute();
			    	LoadMSSRoute();
			    	LoadStationStop();

				   	//Log.d(TAG, "LOCAL ARRAYS LOADED."); /

				   	// Update the UI Thread
			        runOnUiThread(new Runnable() {
			        public void run() {

			        	//Ensure local values are loaded before committing to blnLocalDataLoaded=true
					   	if (myFBGRoutes != null && myMSSRoutes != null && myStations != null){
					   		//Log.d(TAG, "DRAWING RAIL LINES AND STATIONS.");

					   		//Pull user's preferred Map Settings
				    		SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
				    		String prefLine = getPrefs.getString("listTrainLine", "FBG,ALL");
				    		stationMarker = getPrefs.getString("listStationMarker", "abbv");

				    		//Draw user lines by preference.  This will insure the preferred line
				    		//overlays correctly for when the lines Merger in Alexandria
				    		if (prefLine.equals("MSS,ALL")){
				    			DrawFBGRouteOverlay(srcGeoPoint, destGeoPoint);
							    DrawMSSRouteOverlay(srcGeoPoint, destGeoPoint);
				    		}
				    		else{
							    DrawMSSRouteOverlay(srcGeoPoint, destGeoPoint);
							    DrawFBGRouteOverlay(srcGeoPoint, destGeoPoint);
				    		}

					   		if (mOldStationMarkerValue.equals(stationMarker) || mOldStationMarkerValue.length() == 0){
					   			mOldStationMarkerValue = stationMarker;
					   			DrawStationStopOverlay(srcGeoPoint, destGeoPoint);
					   		}

						   	//Log.d(TAG, "DRAWING RAIL LINES AND STATIONS... COMPLETE");
						   	blnLocalDataLoaded = true;

						   	//Log.d(TAG, "CHECKING MAPVIEW SETTINGS FOR CHANGES.");

				    		//Pull user's preferred Map Settings
				    		boolean satelliteOn = getPrefs.getBoolean("chkSatellite", false);
				    		boolean trafficOn = getPrefs.getBoolean("chkTraffic", false);

				    		mapView.setSatellite(satelliteOn);
				    		mapView.setTraffic(trafficOn);

				    		//Log.d(TAG, "CHECK COMPLETE");
					   	}
					   	else{
					   		blnLocalDataLoaded = false;
					   	}
			        }
			        });
			    }
			});

			scheduleTaskExecutorVehicles = Executors.newSingleThreadScheduledExecutor();

		    // This schedule a task to run every X Seconds:
			scheduleTaskExecutorVehicles.scheduleAtFixedRate(new Runnable() {
		    public void run() {

		    	try{

		    		if (Device.isDeviceOnline(context.getApplicationContext()))
			    		noSignalOn = false;
		    		else
		    			noSignalOn = true;

		    		spinnerOn = true;

				   	//Get GTFS data on separate thread (Requires Network)
			    	if (noSignalOn==false && blnGTFSDataLoaded == false && blnLocalDataLoaded == true){

			    		//Log.d(TAG, "CALLING VRE GTFS INTERFACE...");
						doRefreshGTFSFeeds();
						//Log.d(TAG, "CALL COMPELTE.");

						//Log.d(TAG, "GTFS ARRAYS LOADING....");
						LoadVehicleStop();
			    		LoadUpdates();
			    		//Log.d(TAG, "GTFS ARRAYS LOADED.");

			    		//Ensure local values are loaded before committing to blnLocalDataLoaded=true
					   	if (myVehicles != null && myUpdates != null)
					   		blnGTFSDataLoaded = true;
					   	else
					   		blnGTFSDataLoaded = false;
			    	}

					spinnerOn = false;

		    	}
		    	catch(Exception ex)
		    	{
		    		spinnerOn = false;
		    	}

		    	if (LoopCounter == 0){
		    		LoopCounter = 59;
		    		blnGTFSDataLoaded = false;
		    	}
		    	else
		    	{
		    		LoopCounter--;

		    	}

		        // Update the UI Thread
		        runOnUiThread(new Runnable() {
		          public void run() {

			          try{
			        	  /***********************************************************************************
			        	   * Since there are 1,000s of GeoPoints for the Rail Lines and the Stations
			        	   * are static locations, to redraw these every time a vehicle update is posted
			        	   * causes the map to crash.
			        	   *
			        	   * The logic below keeps the FBG, MSS Lines and the Stations on the map
			        	   * and only re-draws the Vehicles.
			        	   *
			        	   * -Check the mapView for our itemizedOverlay, both Station and Train use them
			        	   * but the overlayVehicles ArrayList collection will contain the old objects we
			        	   * want to clear before adding the new Vehicle locations to the map.
			        	   **********************************************************************************/
			        	  if (!spinnerOn){
						      if (mapView.getOverlays().contains(itemizedOverlay)){

							   	  //If user selected a new Station Marker Icon, destroy the old stations and add new
							   	  if (!(mOldStationMarkerValue.equals(stationMarker))){

						    		  for (@SuppressWarnings("rawtypes") CustomItemizedOverlay each: overlayStations){
							    		  //mapOverlays.remove(each);
								    	  mapView.getOverlays().remove(each);
							    	  }

						    		  DrawStationStopOverlay(srcGeoPoint, destGeoPoint);
						    		  mOldStationMarkerValue = stationMarker;
						    		  mapView.postInvalidate();

						    	  }

						    	 //Always Destroy and re-draw vehicles
							     for (CustomItemizedOverlay each: overlayVehicles){
							    	  //mapOverlays.remove(each);
								      mapView.getOverlays().remove(each);
							      }
							      DrawVehicleOverlay(srcGeoPoint, destGeoPoint);
							      DrawUserLocation();
							  	  mapView.postInvalidate();
							 }
							 else
							 {
							      DrawVehicleOverlay(srcGeoPoint, destGeoPoint);
							      DrawUserLocation();
							      mapView.postInvalidate();
							  }
			        	  }

				       	  spinnerOn = false;

			          }
			          catch(Exception e)
			          {
			        	  //Log.d(TAG, "runOnUiThread: " + e.toString());
			          }

		        	  if (LoopCounter == 0)
		        		  txtRefresh.setText("Loading...");
		        	  else
		        		  txtRefresh.setText(" Refreshing: " + Integer.toString(LoopCounter) + " ");

		        	  txtArrivals.setText(lblMsg);
		          }
		        });
		      }
		   }, 0, 1, TimeUnit.SECONDS);

			scheduleTaskExecutorUiUpdates = Executors.newScheduledThreadPool(4);

		    // This schedule a task to run every x minutes:
			scheduleTaskExecutorUiUpdates.scheduleAtFixedRate(new Runnable() {
		      public void run() {

		        // Update the UI Thread
		        runOnUiThread(new Runnable() {
		          public void run() {

		        	  if (spinnerOn){
		        		  spinnerAnim.start();
		        		  spinner.setVisibility(View.VISIBLE);
		        	  }
		        	  else
		        	  {
		        		  spinnerAnim.stop();
		        		  spinner.setVisibility(View.INVISIBLE);
		        	  }

		        	  if (noSignalOn){
		        		  imgNoSignal.setVisibility(View.VISIBLE);
		        	  }
		        	  else
		        	  {
		        		  imgNoSignal.setVisibility(View.INVISIBLE);
		        	  }
		          }
		        });
		      }
			}, 0, 1, TimeUnit.SECONDS);
		    //}, 0, 500, TimeUnit.MILLISECONDS);

	}

	@Override
	protected void onResume(){
		super.onResume();

		//Track current Activity
		googleTracker.trackPageView("/" + TAG);

		/* Variables to check if user preferences have changed */
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
	    mOldTimeFormatValue = settings.getString(PREFS_TIME_FORMAT_KEY, "");
	    mOldStationMarkerValue = settings.getString(PREFS_STATION_MARKER_KEY, "");
	    mOldSatelliteValue = settings.getBoolean(PREFS_SATELLITE_KEY, false);
	    mOldTrafficValue = settings.getBoolean(PREFS_TRAFFIC_KEY, false);

	    //Manage Location Manager
	    if (myLocationOverlay != null){
	    	myLocationOverlay.enableMyLocation();
	    	myLocationOverlay.enableCompass();
	    }
	}

	private void doRefreshGTFSFeeds() {

		/* Verify the Device is Connected before invoking a method requiring INTERNET*/
    	//if (Device.isDeviceOnline(context.getApplicationContext())){

    		//Pull Vehicles from VRE GTFS and Load them to SQL
    		BusinessVehicle.LoadVehiclesFromGTFS(this);

    		//Pull Trip Updates from VRE GTFS and Load them to SQL
    		BusinessUpdate.LoadUpdatesFromGTFS(this);
    	//}
	}

	private void LoadFBGRoute(){

		//Get Route Based on route_id
		myFBGRoutes = BusinessRoute.getAllRoutes(context, 2); //FBG (RED)
	}

	private void LoadMSSRoute(){

	    //Get Route Based on route_id
		myMSSRoutes = BusinessRoute.getAllRoutes(context, 4); //MSS (BLUE)
	}

	private void LoadStationStop(){

		//Get Stations
		myStations = BusinessStation.getAllStations(context);
	}

	private void LoadVehicleStop(){

		//Get Vehicles
		myVehicles = BusinessVehicle.getAllVehicles(context);
	}

	private void LoadUpdates(){

		//Current Station Collection
		myUpdates = BusinessUpdate.getAllUpdates(context);
	}

	private void LoadCalDates(){

		//Current CalDates Collection
		myCalDates = BusinessBaseCalDates.getAllCalDates(this);
	}

	private void DrawFBGRouteOverlay(GeoPoint src, GeoPoint dest){

		DrawRoute(src, dest, myFBGRoutes, Color.RED);
	}

	private void DrawMSSRouteOverlay(GeoPoint src, GeoPoint dest){

		DrawRoute(src, dest, myMSSRoutes, Color.BLUE);
	}

	//Draws User Location, must draw LocationOverlay last so it appears on-top of
	//All other layers: Rail Line, Stations, Vehicles.  Note: LocationOverlay is created
	//OnCreate and is Enabled/Disabled from OnResume and OnPause
	private void DrawUserLocation(){

		//Remove Old
		if (myLocationOverlay != null)
			mapView.getOverlays().remove(myLocationOverlay);

		//Add New
		mapView.getOverlays().add(myLocationOverlay);

	}

	private void DrawStationStopOverlay(GeoPoint src, GeoPoint dest){

		overlayStations = new ArrayList<CustomItemizedOverlay>();

		try{
			for (Station each : myStations) {

				stationLat = Double.parseDouble(each.STATION_LATITUDE());
				stationLong = Double.parseDouble(each.STATION_LONGITUDE());

				//Train Station Icon
				stationIconString = "drawable/station_icon_" + each.STATION_ID().toLowerCase();
				stationIcon = String.valueOf(getResources().getIdentifier(stationIconString, null, getPackageName()));
				stationAddress = each.ZONE() + "\n";
				stationAddress += each.ADDRESS() + "\n";
				stationAddress += each.CITY() + ", " + each.STATE() + " " + each.ZIP() + "\n";

				mapOverlays = mapView.getOverlays();

				//Train Station Map Icon
				if (stationMarker.equals("abbv"))
					stationIconName = "drawable/station_" + each.STATION_ID().toLowerCase();
				else
					stationIconName = "drawable/stop_marker";

			    int imageResource = getResources().getIdentifier(stationIconName, null, getPackageName());
			    Drawable drawable = getResources().getDrawable(imageResource);

				itemizedOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);

				GeoPoint point = new LatLonPoint(stationLat, stationLong);
				CustomOverlayItem overlayItem = new CustomOverlayItem(point, each.STATION_STOP_NAME(), stationAddress, stationIcon);
				itemizedOverlay.addOverlay(overlayItem);

				overlayStations.add(itemizedOverlay);
			}

			if (!(overlayStations == null))
				mapOverlays.addAll(overlayStations);

		}
		catch(Exception e)
		{
			//Log.d(TAG, "DrawStationStopOverlay ERROR: " + e.toString());
		}
	}

	/*
	 * DrawVehicleOverlay
	 *
	 * Requires Special Logic:  Since it is too expensive to re-draw the mapView everytime a Vehicle
	 * change occurs, load the vehicles into a collection and clear their old location and draw the
	 * new location on the background thread.
	 */
	@SuppressWarnings("unused")
	private void DrawVehicleOverlay(GeoPoint src, GeoPoint dest){

		overlayVehicles = new ArrayList<CustomItemizedOverlay>();

		boolean VehicleAtStation = false;

		String StationLat = "";
		String StationLong = "";
		String VehicLat = "";
		String VehicLong = "";
		String iconColor = ""; //Default is Green

		lblMsg = "";	//Clear

		VehicleBubble myVehicleBubble = null;  //IDEA!  Convert to Collection refresh collection only when Spinner recycles

		if (!(myVehicles == null)){

		try{

			for (Vehicle eachVehicle : myVehicles) {

				vehicleLat = Double.parseDouble(eachVehicle.VEHICLE_LATITUDE());
				vehicleLong = Double.parseDouble(eachVehicle.VEHCILE_LONGITUDE());

				/* Pull user's preferred default train line */
				SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
				String timeformat = getPrefs.getString("listTimeFormat", "12");

				if (myStations != null && myUpdates != null && TodaysScheduleType != null)
				    myVehicleBubble = BusinessSchedule.fetchVehicleBubble(this, eachVehicle, myUpdates, myStations, TodaysScheduleType, timeformat);

				if (myVehicleBubble != null){

					if (myVehicleBubble.AT_STATION())
					{

						if (lblMsg.length() == 0)
							lblMsg = (" " + myVehicleBubble.VEHICLE_ID() + "@" + myVehicleBubble.CURRENT_STOP() + " ");
						else
							lblMsg = (lblMsg + "\n " + myVehicleBubble.VEHICLE_ID() + "@" + myVehicleBubble.CURRENT_STOP() + " ");
					}

					//Train Station Icon
					vehicleIconString = "drawable/train";
					vehicleIcon = String.valueOf(getResources().getIdentifier(vehicleIconString, null, getPackageName()));

					//vehicleInfo = myVehicleBubble.VEHICLE_LABLE() + " \n";
					vehicleInfo = myVehicleBubble.STATUS() + " \n";
					vehicleInfo += myVehicleBubble.NEXT_STOP_AND_TIME() + " \n";
					vehicleInfo += "To: " + myVehicleBubble.HEADING() + " \n";
					vehicleInfo += myVehicleBubble.STOPS_REMAINING();

					//Determine which color icon to display
					iconColor = "green";  //Default: green

					if (myVehicleBubble.DELAYED())  //Delayed turns orange
						iconColor = "orange";

					if (myVehicleBubble.LOST_COMM()) 	//Lost Comms overrides Default and Delay turns gray
						iconColor = "gray";

					mapOverlays = mapView.getOverlays();

					int imageResource;

					//Train Station Map Icon
					if (myVehicleBubble.AT_STATION()){
						if (LoopCounter%2==0)
							vehicleIconName = "drawable/map_train_" + iconColor + "_" + eachVehicle.VEHICLE_ID().toLowerCase();
						else
							vehicleIconName = "drawable/map_train_" + iconColor + "_arrive";
					}
					else
					{
						vehicleIconName = "drawable/map_train_" + iconColor + "_" + eachVehicle.VEHICLE_ID().toLowerCase();
					}

					try{

						imageResource = getResources().getIdentifier(vehicleIconName, null, getPackageName());
					}
					catch(Exception e)
					{
						vehicleIconName = "drawable/map_train_green";
						imageResource = getResources().getIdentifier(vehicleIconName, null, getPackageName());
					}

				    Drawable drawable = getResources().getDrawable(imageResource);

					itemizedOverlay = new CustomItemizedOverlay<CustomOverlayItem>(drawable, mapView);

					GeoPoint point = new LatLonPoint(vehicleLat, vehicleLong);
					CustomOverlayItem overlayItem = new CustomOverlayItem(point, myVehicleBubble.VEHICLE_LABLE(), vehicleInfo, vehicleIcon);
					itemizedOverlay.addOverlay(overlayItem);

					overlayVehicles.add(itemizedOverlay);
				}
			}
			if (!(overlayVehicles == null))
				mapOverlays.addAll(overlayVehicles);
		}
		catch(Exception e)
		{
			//Log.d(TAG, "DrawVehicleOverlay: " + e.toString());
		}

		}
	}

	private static final class LatLonPoint extends GeoPoint {
	    public LatLonPoint(double latitude, double longitude) {
	        super((int) (latitude * 1E6), (int) (longitude * 1E6));
	    }
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	private void DrawRoute(GeoPoint src, GeoPoint dest, ArrayList<Route> route, int DefaultColor){

		Integer counter = 0;
		GeoPoint startGP = null;
		GeoPoint gp1;
		GeoPoint gp2 = null;

		for (Route each : route) {
			if (counter == 0){
				startGP = new GeoPoint((int) (Double.parseDouble(each.ROUTE_LATITUDE()) * 1E6), (int) (Double.parseDouble(each.ROUTE_LONGITUDE()) * 1E6));
				mapView.getOverlays().add(new RouteOverlay(startGP, startGP, DefaultColor));
				gp2 = startGP;
				counter++;
			}
			else
			{
				gp1 = gp2;
				gp2 = new GeoPoint((int) (Double.parseDouble(each.ROUTE_LATITUDE()) * 1E6),	(int) (Double.parseDouble(each.ROUTE_LONGITUDE()) * 1E6));
				mapView.getOverlays().add(new RouteOverlay(gp1, gp2, 3, DefaultColor));
			}
		}
		mapView.getOverlays().add(new RouteOverlay(dest, dest, DefaultColor));
	}

	 @Override
	 public boolean onCreateOptionsMenu(Menu menu) {
	     MenuInflater inflater = getMenuInflater();
	     inflater.inflate(R.menu.mapmenu, menu);
	     return true;
	 }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    if (item.getItemId() == R.id.about) {
			//Track GoogleAnalytics Event
			googleTracker.trackEvent("ui_interaction",	//category
									 "from_menu",		//action
									 "about",			//label
									 0);				//value
			Intent a = new Intent(ActivityGoogleMap.this, ActivityAbout.class);
			a.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(a);
		} else if (item.getItemId() == R.id.options) {
			//Track GoogleAnalytics Event
			googleTracker.trackEvent("ui_interaction",	//category
									 "from_menu",		//action
									 "options",			//label
									 0);				//value
			Intent p = new Intent(ActivityGoogleMap.this, ActivityPreferences.class);
			p.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(p);
		} else if (item.getItemId() == R.id.oldmap) {
			//Track GoogleAnalytics Event
			googleTracker.trackEvent("ui_interaction",	//category
									 "from_menu",		//action
									 "oldmap",		//label
									 0);				//value
			Intent o = new Intent(ActivityGoogleMap.this, ActivityOldMap.class);
			o.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(o);
		} else if (item.getItemId() == R.id.alerts) {
			//Track GoogleAnalytics Event
			googleTracker.trackEvent("ui_interaction",	//category
									 "from_menu",		//action
									 "alerts",			//label
									 0);				//value
			Intent x = new Intent(ActivityGoogleMap.this, ActivityAlerts.class);
			x.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(x);
		} else if (item.getItemId() == R.id.schedules) {
			//Track GoogleAnalytics Event
			googleTracker.trackEvent("ui_interaction",	//category
									 "from_menu",		//action
									 "schedules",		//label
									 0);				//value
			Intent e = new Intent(ActivityGoogleMap.this, ActivityStationSchedule.class);
			e.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(e);
		}
	    return true;
	}

	private void  addListenerOnAlert() {

		imgAlerts = (ImageView) findViewById(R.id.imgAlerts);

		imgAlerts.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				//Track GoogleAnalytics Event
				googleTracker.trackEvent("ui_interaction",		//category
					        			 "from_icon",			//action
					        			 "alerts",				//label
					        			 0);					//value

				//Do Something
				Intent myIntent = new Intent(ActivityGoogleMap.this, ActivityAlerts.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(myIntent);
			}
		});
	}

	private void  addListenerOnSched() {

		imgSched = (ImageView) findViewById(R.id.imgSched);

		imgSched.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				//Track GoogleAnalytics Event
				googleTracker.trackEvent("ui_interaction",		//category
					        			 "from_icon",			//action
					        			 "schedule",			//label
					        			 0);					//value

				//Do Something
				Intent myIntent = new Intent(ActivityGoogleMap.this, ActivityStationSchedule.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(myIntent);
			}
		});
	}

	private void addListenerOnTwitterImage() {

		imgTwitter = (ImageView) findViewById(R.id.imgTwitter);

		imgTwitter.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				//Track GoogleAnalytics Event
				googleTracker.trackEvent("ui_interaction",		//category
					        			 "from_icon",			//action
					        			 "twitter",				//label
					        			 0);					//value

				//Do Something
				Intent myIntent = new Intent(ActivityGoogleMap.this, ActivityTwitterFeed.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(myIntent);
			}
		});
	}

	@Override
	protected void onDestroy() {
		 super.onDestroy();

		// Stop the tracker when it is no longer needed.
		googleTracker.stopSession();
	}
}


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import sys

from colors import cyan, green, red, yellow

from pants.option import custom_types
from pants.option.config import Config
from pants.option.errors import ParseError

migrations = {
  ('backends', 'packages'): ('DEFAULT', 'backend_packages'),
  ('backends', 'plugins'): ('DEFAULT', 'plugins'),
  ('DEFAULT', 'bootstrap_buildfiles'): ('goals', 'bootstrap_buildfiles'),

  ('jvm', 'missing_deps_target_whitelist'): ('compile.jvm-dep-check', 'missing_deps_whitelist'),
  ('jvm', 'jdk_paths'): ('jvm-distributions', 'paths'),
  ('compile.java', 'missing_deps'): ('compile.jvm-dep-check', 'missing_deps'),
  ('compile.java', 'missing_direct_deps'): ('compile.jvm-dep-check', 'missing_direct_deps'),
  ('compile.java', 'missing_deps_whitelist'): ('compile.jvm-dep-check', 'missing_deps_whitelist'),
  ('compile.java', 'unnecessary_deps'): ('compile.jvm-dep-check', 'unnecessary_deps'),

  ('java-compile', 'partition_size_hint'): ('compile.java', 'partition_size_hint'),
  ('java-compile', 'javac_args'): ('compile.java', 'args'),
  ('java-compile', 'jvm_args'): ('compile.java', 'jvm_options'),
  ('java-compile', 'confs'): ('compile.java', 'confs'),
  ('java-compile', 'locally_changed_targets_heuristic_limit'): ('compile.java',
                                                                'changed_targets_heuristic_limit'),
  ('java-compile', 'warning_args'): ('compile.java', 'warning_args'),
  ('java-compile', 'no_warning_args'): ('compile.java', 'no_warning_args'),
  ('java-compile', 'use_nailgun'): ('compile.java', 'use_nailgun'),

  ('scala-compile', 'partition_size_hint'): ('compile.scala', 'partition_size_hint'),
  ('scala-compile', 'jvm_args'): ('compile.scala', 'jvm_options'),
  ('scala-compile', 'confs'): ('compile.scala', 'confs'),
  ('scala-compile', 'locally_changed_targets_heuristic_limit'): ('compile.scala',
                                                                 'changed_targets_heuristic_limit'),
  ('scala-compile', 'warning_args'): ('compile.scala', 'warning_args'),
  ('scala-compile', 'no_warning_args'): ('compile.scala', 'no_warning_args'),
  ('scala-compile', 'runtime-deps'): ('compile.scala', 'runtime-deps'),
  ('scala-compile', 'use_nailgun'): ('compile.scala', 'use_nailgun'),
  ('scala-compile', 'args'): ('compile.scala', 'args'),

  ('javadoc-gen', 'include_codegen'): ('gen.javadoc', 'include_codegen'),
  ('scaladoc-gen', 'include_codegen'): ('gen.scaladoc', 'include_codegen'),

  ('nailgun', 'autokill'): ('DEFAULT', 'kill_nailguns'),

  ('jvm-run', 'jvm_args'): ('run.jvm', 'jvm_options'),
  ('benchmark-run', 'jvm_args'): ('bench', 'jvm_options'),
  ('specs-run', 'jvm_args'): ('test.specs', 'jvm_options'),
  ('junit-run', 'jvm_args'): ('test.junit', 'jvm_options'),
  ('scala-repl', 'jvm_args'): ('repl.scala', 'jvm_options'),
  ('ivy-resolve', 'jvm_args'): ('resolve.ivy', 'jvm_options'),

  ('jvm-run', 'confs'): ('run.jvm', 'confs'),
  ('benchmark-run', 'confs'): ('bench', 'confs'),
  ('specs-run', 'confs'): ('test.specs', 'confs'),
  ('junit-run', 'confs'): ('test.junit', 'confs'),
  ('scala-repl', 'confs'): ('repl.scala', 'confs'),
  ('ivy-resolve', 'confs'): ('resolve.ivy', 'confs'),

  ('scala-repl', 'args'): ('repl.scala', 'args'),

  ('checkstyle', 'bootstrap-tools'): ('compile.checkstyle', 'bootstrap_tools'),
  ('checkstyle', 'configuration'): ('compile.checkstyle', 'configuration'),
  ('checkstyle', 'properties'): ('compile.checkstyle', 'properties'),

  ('scalastyle', 'config'): ('compile.scalastyle', 'config'),
  ('scalastyle', 'excludes'): ('compile.scalastyle', 'excludes'),

  # These must now be defined for each JvmTask subtask, so we temporarily put them
  # in the DEFAULT section as a convenience.
  # These will soon move into a subsystem, which will fix this.
  ('jvm', 'debug_config'): ('DEFAULT', 'debug_config'),
  ('jvm', 'debug_port'): ('DEFAULT', 'debug_port'),

  ('scala-compile', 'scalac-plugins'): ('compile.scala', 'plugins'),
  ('scala-compile', 'scalac-plugin-args'): ('compile.scala', 'plugin_args'),

  ('markdown-to-html', 'extensions'): ('markdown', 'extensions'),
  ('markdown-to-html', 'code-style'): ('markdown', 'code_style'),

  # Note: This assumes that ConfluencePublish is registered as the only task in a
  #       goal called 'confluence'.  Adjust if this is not the case in your pants.ini.
  ('confluence-publish', 'url'): ('confluence', 'url'),

  # JVM tool migrations.
  ('antlr-gen', 'javadeps'): ('gen.antlr', 'antlr3'),
  ('antlr4-gen', 'javadeps'): ('gen.antlr', 'antlr4'),
  ('scrooge-gen', 'bootstrap-tools'): ('gen.scrooge', 'scrooge'),
  ('thrift-linter', 'bootstrap-tools'): ('thrift-linter', 'scrooge_linter'),
  ('wire-gen', 'bootstrap-tools'): ('gen.wire', 'wire_compiler'),
  ('benchmark-run', 'bootstrap-tools'): ('bench', 'benchmark_tool'),
  ('benchmark-run', 'agent-bootstrap-tools'): ('bench', 'benchmark_agent'),
  ('compile.checkstyle', 'bootstrap-tools'): ('compile.checkstyle', 'checkstyle'),
  ('ivy-resolve', 'bootstrap-tools'): ('resolve.ivy', 'xalan'),
  ('jar-tool', 'bootstrap-tools'): ('DEFAULT', 'jar-tool'),
  ('junit-run', 'junit-bootstrap-tools'): ('test.junit', 'junit'),
  ('junit-run', 'emma-bootstrap-tools'): ('test.junit', 'emma'),
  ('junit-run', 'cobertura-bootstrap-tools'): ('test.junit', 'cobertura'),
  ('java-compile', 'jmake-bootstrap-tools'): ('compile.java', 'jmake'),
  ('java-compile', 'compiler-bootstrap-tools'): ('compile.java', 'java_compiler'),
  # Note: compile-bootstrap-tools is not a typo.
  ('scala-compile', 'compile-bootstrap-tools'): ('compile.scala', 'scalac'),
  ('scala-compile', 'zinc-bootstrap-tools'): ('compile.scala', 'zinc'),
  ('scala-compile', 'scalac-plugin-bootstrap-tools'): ('compile.scala', 'plugin_jars'),
  ('scala-repl', 'bootstrap-tools'): ('repl.scala', 'scala_repl'),
  ('specs-run', 'bootstrap-tools'): ('test.specs', 'specs'),

  # Artifact cache spec migration.
  ('dx-tool', 'read_artifact_caches'): ('dex', 'read_artifact_caches'),
  ('thrift-gen', 'read_artifact_caches'): ('gen.thrift', 'read_artifact_caches'),
  ('ivy-resolve', 'read_artifact_caches'): ('resolve.ivy', 'read_artifact_caches'),
  ('java-compile', 'read_artifact_caches'): ('compile.java', 'read_artifact_caches'),
  ('scala-compile', 'read_artifact_caches'): ('compile.scala', 'read_artifact_caches'),

  ('dx-tool', 'write_artifact_caches'): ('dex', 'write_artifact_caches'),
  ('thrift-gen', 'write_artifact_caches'): ('gen.thrift', 'write_artifact_caches'),
  ('ivy-resolve', 'write_artifact_caches'): ('resolve.ivy', 'write_artifact_caches'),
  ('java-compile', 'write_artifact_caches'): ('compile.java', 'write_artifact_caches'),
  ('scala-compile', 'write_artifact_caches'): ('compile.scala', 'write_artifact_caches'),

  ('protobuf-gen', 'version'): ('gen.protoc', 'version'),
  ('protobuf-gen', 'supportdir'): ('gen.protoc', 'supportdir'),
  ('protobuf-gen', 'plugins'): ('gen.protoc', 'plugins'),
  ('protobuf-gen', 'javadeps'): ('gen.protoc', 'javadeps'),
  ('protobuf-gen', 'pythondeps'): ('gen.protoc', 'pythondeps'),

  ('thrift-gen', 'strict'): ('gen.thrift', 'strict'),
  ('thrift-gen', 'supportdir'): ('gen.thrift', 'supportdir'),
  ('thrift-gen', 'version'): ('gen.thrift', 'version'),
  ('thrift-gen', 'java'): ('gen.thrift', 'java'),
  ('thrift-gen', 'python'): ('gen.thrift', 'python'),

  ('backend', 'python-path'): ('DEFAULT', 'pythonpath'),

  ('python-ipython', 'entry-point'): ('repl.py', 'ipython_entry_point'),
  ('python-ipython', 'requirements'): ('repl.py', 'ipython_requirements'),

  ('jar-publish', 'restrict_push_branches'): ('publish.jar', 'restrict_push_branches'),
  ('jar-publish', 'ivy_jvmargs'): ('publish.jar', 'jvm_options'),
  ('jar-publish', 'repos'): ('publish.jar', 'repos'),
  ('jar-publish', 'publish_extras'): ('publish.jar', 'publish_extras'),

  ('publish', 'individual_plugins'): ('publish.jar', 'individual_plugins'),
  ('publish', 'ivy_settings'): ('publish.jar', 'ivy_settings'),
  ('publish', 'jvm_options'): ('publish.jar', 'jvm_options'),
  ('publish', 'publish_extras'): ('publish.jar', 'publish_extras'),
  ('publish', 'push_postscript'): ('publish.jar', 'push_postscript'),
  ('publish', 'repos'): ('publish.jar', 'repos'),
  ('publish', 'restrict_push_branches'): ('publish.jar', 'restrict_push_branches'),

  # Three changes are pertinent to migrate 'ide' to both idea and & eclipse. I tried to capture
  # that in notes
  ('ide', 'python_source_paths'): ('idea', 'python_source_paths'),
  ('ide', 'python_lib_paths'): ('idea', 'python_lib_paths'),
  ('ide', 'python_test_paths'): ('idea', 'python_test_paths'),
  ('ide', 'extra_jvm_source_paths'): ('idea', 'extra_jvm_source_paths'),
  ('ide', 'extra_jvm_test_paths'): ('idea', 'extra_jvm_test_paths'),
  ('ide', 'debug_port'): ('idea', 'debug_port'),

  ('reporting', 'reports_template_dir'): ('reporting', 'template_dir'),

  ('DEFAULT', 'stats_upload_url'): ('run-tracker', 'stats_upload_url'),
  ('DEFAULT', 'stats_upload_timeout'): ('run-tracker', 'stats_upload_timeout'),
  ('DEFAULT', 'num_foreground_workers'): ('run-tracker', 'num_foreground_workers'),
  ('DEFAULT', 'num_background_workers'): ('run-tracker', 'num_background_workers'),

  # These changes migrate all possible scoped configuration of --ng-daemons to --use-nailgun leaf
  # options.
  ('DEFAULT', 'ng_daemons'): ('DEFAULT', 'use_nailgun'),

  # NB: binary.binary -> binary is a leaf scope
  ('binary', 'ng_daemons'): ('binary', 'use_nailgun'),
  ('binary.dex', 'ng_daemons'): ('binary.dex', 'use_nailgun'),
  ('binary.dup', 'ng_daemons'): ('binary.dup', 'use_nailgun'),

  # NB: bundle.bundle -> bundle is a leaf scope
  ('bundle', 'ng_daemons'): ('bundle', 'use_nailgun'),
  ('bundle.dup', 'ng_daemons'): ('bundle.dup', 'use_nailgun'),

  ('compile', 'ng_daemons'): None,  # Intermediate scope - note only, no direct migration path
  ('compile.scalastyle', 'ng_daemons'): ('compile.scalastyle', 'use_nailgun'),
  ('compile.scala', 'ng_daemons'): ('compile.scala', 'use_nailgun'),
  ('compile.apt', 'ng_daemons'): ('compile.apt', 'use_nailgun'),
  ('compile.java', 'ng_daemons'): ('compile.java', 'use_nailgun'),
  ('compile.checkstyle', 'ng_daemons'): ('compile.checkstyle', 'use_nailgun'),

  ('detect-duplicates', 'ng_daemons'): ('detect-duplicates', 'use_nailgun'),

  ('gen', 'ng_daemons'): None,  # Intermediate scope - note only, no direct migration path
  ('gen.antlr', 'ng_daemons'): ('gen.antlr', 'use_nailgun'),
  ('gen.jaxb', 'ng_daemons'): ('gen.jaxb', 'use_nailgun'),
  ('gen.scrooge', 'ng_daemons'): ('gen.scrooge', 'use_nailgun'),

  ('imports', 'ng_daemons'): None,  # Intermediate scope - note only, no direct migration path
  ('imports.ivy-imports', 'ng_daemons'): ('imports.ivy-imports', 'use_nailgun'),

  ('jar', 'ng_daemons'): ('jar', 'use_nailgun'),
  ('publish', 'ng_daemons'): ('publish', 'use_nailgun'),

  ('resolve', 'ng_daemons'): None,  # Intermediate scope - note only, no direct migration path
  ('resolve.ivy', 'ng_daemons'): ('resolve.ivy', 'use_nailgun'),

  ('thrift-linter', 'ng_daemons'): ('thrift-linter', 'use_nailgun'),

  # Migration of the scrooge contrib module to the new options system.
  ('java-thrift-library', 'compiler'): ('DEFAULT', 'thrift_default_compiler'),
  ('java-thrift-library', 'language'): ('DEFAULT', 'thrift_default_language'),
  ('java-thrift-library', 'rpc_style'): ('DEFAULT', 'thrift_default_rpc_style'),
  ('scrooge-gen', 'jvm_args'): ('gen.scrooge', 'jvm_options'),
  ('scrooge-gen', 'jvm_options'): ('gen.scrooge', 'jvm_options'),
  ('scrooge-gen', 'strict'): ('gen.scrooge', 'strict'),
  ('scrooge-gen', 'verbose'): ('gen.scrooge', 'verbose'),
  ('thrift-linter', 'strict'): ('thrift-linter', 'strict_default'),
  # NB: For the following two options, see the notes below.
  ('scrooge-gen', 'scala'): ('gen.scrooge', 'service_deps'),
  ('scrooge-gen', 'java'): ('gen.scrooge', 'service_deps'),

  # jar-tool subsystem.
  ('jar-tool', 'bootstrap-tools'): ('jar-tool', 'jar-tool'),
  ('jar-tool', 'jvm_args'): ('jar-tool', 'jvm_options'),

  # Technically 'indices' and 'indexes' are both acceptable plural forms of 'index'. However
  # usage has led to the former being used primarily for mathematical indices and the latter
  # for book indexes, database indexes and the like.
  ('python-repos', 'indices'): ('python-repos', 'indexes'),

  ('ragel-gen', 'supportdir'): ('gen.ragel', 'supportdir'),
  ('ragel-gen', 'version'): ('gen.ragel', 'version'),

  ('prepare-resources', 'confs'): ('resources.prepare', 'confs'),

  ('compile.scala', 'runtime-deps'): ('scala-platform', 'runtime'),
  ('compile.scala', 'scalac'): ('scala-platform', 'scalac'),

  ('DEFAULT', 'thrift_default_compiler'): ('thrift-defaults', 'compiler'),
  ('DEFAULT', 'thrift_default_language'): ('thrift-defaults', 'language'),
  ('DEFAULT', 'thrift_default_rpc_style'): ('thrift-defaults', 'rpc_style'),

  ('python-setup', 'egg_cache_dir'): ('python_setup', 'resolver_cache_dir'),
  ('DEFAULT', 'python_chroot_requirements_ttl'): ('python-setup', 'resolver_cache_ttl'),

  ('DEFAULT', 'pants_support_baseurls'): ('binaries', 'baseurls'),
  ('DEFAULT', 'pants_support_fetch_timeout_secs'): ('binaries', 'fetch_timeout_secs'),

  ('gen.thrift', 'supportdir'): ('thrift-binary', 'supportdir'),
  ('gen.thrift', 'version'): ('thrift-binary', 'version'),

  ('gen.thrift', 'java'): None,  # Notes only one to many migration: see notes below.
  ('gen.thrift', 'python'): None,  # Notes only pure deletion migration: see notes below.

  ('compile.zinc-java', 'enabled'): ('compile.java', 'use-jmake'),

  ('compile.scala', 'args'): ('compile.zinc', 'args'),

  ('compile.cpp-compile', 'cc_options'): ('compile.cpp', 'cc_options'),
  ('compile.cpp-compile', 'cc_extensions'): ('compile.cpp', 'cc_extensions'),

  ('test.junit', 'coverage_html_open'): ('test.junit', 'coverage_open'),

  # On by default.
  ('compile.apt', 'jar'): None,
  ('compile.java', 'jar'): None,
  ('compile.zinc', 'jar'): None,

  ('unknown-arguments', 'ignored'): None,

  # Tool specs, migrated from a list to a single string.
  ('bench', 'benchmark-agent'): None,
  ('bench', 'benchmark-tool'): None,
  ('binary', 'nailgun-server'): None,
  ('binary.dex', 'nailgun-server'): None,
  ('binary.dup', 'nailgun-server'): None,
  ('bootstrap.bootstrap-jvm-tools', 'jarjar'): None,
  ('bootstrap.bootstrap-jvm-tools', 'nailgun-server'): None,
  ('bundle', 'nailgun-server'): None,
  ('bundle.dup', 'nailgun-server'): None,
  ('compile.apt', 'java-compiler'): None,
  ('compile.apt', 'jmake'): None,
  ('compile.apt', 'nailgun-server'): None,
  ('compile.checkstyle', 'checkstyle'): None,
  ('compile.checkstyle', 'nailgun-server'): None,
  ('compile.java', 'java-compiler'): None,
  ('compile.java', 'jmake'): None,
  ('compile.java', 'nailgun-server'): None,
  ('compile.scalastyle', 'nailgun-server'): None,
  ('compile.scalastyle', 'scalastyle'): None,
  ('compile.zinc', 'compiler-interface'): None,
  ('compile.zinc', 'nailgun-server'): None,
  ('compile.zinc', 'plugin-jars'): None,
  ('compile.zinc', 'sbt-interface'): None,
  ('compile.zinc', 'zinc'): None,
  ('detect-duplicates', 'nailgun-server'): None,
  ('gen.antlr', 'antlr3'): None,
  ('gen.antlr', 'antlr4'): None,
  ('gen.antlr', 'nailgun-server'): None,
  ('gen.jaxb', 'nailgun-server'): None,
  ('gen.scrooge', 'nailgun-server'): None,
  ('gen.scrooge', 'scrooge-gen'): None,
  ('gen.spindle', 'nailgun-server'): None,
  ('gen.spindle', 'spindle-codegen'): None,
  ('gen.wire', 'javadeps'): None,
  ('gen.wire', 'wire-compiler'): None,
  ('imports.ivy-imports', 'nailgun-server'): None,
  ('jar', 'nailgun-server'): None,
  ('jar-tool', 'jar-tool'): None,
  ('publish.jar', 'nailgun-server'): None,
  ('repl-dirty.scala-dirty', 'scala-repl'): None,
  ('repl.scala', 'scala-repl'): None,
  ('resolve.ivy', 'nailgun-server'): None,
  ('resolve.ivy', 'xalan'): None,
  ('scala-platform', 'scalac'): None,
  ('test.junit', 'cobertura-instrument'): None,
  ('test.junit', 'cobertura-report'): None,
  ('test.junit', 'cobertura-run'): None,
  ('test.junit', 'emma'): None,
  ('test.junit', 'junit'): None,
  ('thrift-linter', 'nailgun-server'): None,
  ('thrift-linter', 'scrooge-linter'): None,

  # Global strategy removal.
  ('compile.apt', 'changed-targets-heuristic-limit'): None,
  ('compile.apt', 'partition-size-hint'): None,
  ('compile.apt', 'strategy'): None,
  ('compile.java', 'changed-targets-heuristic-limit'): None,
  ('compile.java', 'partition-size-hint'): None,
  ('compile.java', 'strategy'): None,
  ('compile.zinc', 'changed-targets-heuristic-limit'): None,
  ('compile.zinc', 'partition-size-hint'): None,
  ('compile.zinc', 'strategy'): None,
}

jvm_global_strategy_removal = ('The JVM global compile strategy was removed in favor of the '
                               'isolated strategy, which uses a different set of options.')

ng_daemons_note = ('The global "ng_daemons" option has been replaced by a "use_nailgun" option '
                   'local to each task that can use a nailgun.  A default can no longer be '
                   'specified at intermediate scopes; ie: "compile" when the option is present in '
                   '"compile.apt", "compile.checkstyle", "compile.java", "compile.scala" and '
                   '"compile.scalastyle".  You must over-ride in each nailgun task section that '
                   'should not use the default "use_nailgun" value of sTrue.  You can possibly '
                   'limit the number of overrides by inverting the default with a DEFAULT section '
                   'value of False.')

scrooge_gen_deps_note = ('The scrooge-gen per-language config fields have been refactored into '
                         'two options: one for service deps, and one for structs deps.')
compile_jar_note = ('The isolated jvm compile `jar` option is critical to performant operation '
                    'and can no longer be disabled.')

jvm_tool_spec_override = ('JVM tool classpath spec overrides have migrated from a list of target'
                          'addresses to a single target address.  To migrate a list of addresses '
                          'you\'ll need to create a new aggregator target to hold the list like '
                          'so: `target(name=<your choice>, dependencies=[<list of addresses>])` '
                          'and then point to its single address.')

notes = {
  ('jvm', 'missing_deps_target_whitelist'): 'This should be split into compile.java or '
                                            'compile.scala',
  ('jvm', 'debug_port'): 'For now must be defined for each JvmTask subtask separately.  Will soon '
                         'move to a subsystem, which will fix this requirement.',
  ('jvm', 'debug_args'): 'For now must be defined for each JvmTask subtask separately.  Will soon '
                         'move to a subsystem, which will fix this requirement.',
  ('java-compile', 'javac_args'): 'Source, target, and bootclasspath args should be specified in '
                                  'the jvm-platform subsystem. Other args can be placed in args: '
                                  'and prefixed with -C, or also be included in the jvm-platform '
                                  'args.',
  ('java-compile', 'source'): 'source and target args should be defined using the jvm-platform '
                              'subsystem, rathern than as arguments to java-compile.',
  ('java-compile', 'target'): 'source and target args should be defined using the jvm-platform '
                              'subsystem, rathern than as arguments to java-compile.',
  ('jar-tool', 'bootstrap_tools'): 'Each JarTask sub-task can define this in its own section. or '
                                   'this can be defined for everyone in the DEFAULT section.',
  ('ivy-resolve', 'jvm_args'): 'If needed, this should be repeated in resolve.ivy, '
                               'bootstrap.bootstrap-jvm-tools and imports.ivy-imports '
                               '(as jvm_options). Easiest way to do this is to define '
                               'ivy_jvm_options in DEFAULT and then interpolate it: '
                               'jvm_options: %(ivy_jvm_options)s',
  ('protobuf-gen', 'version'): 'The behavior of the "version" and "javadeps" parameters '
                               'have changed.\n  '
                               'The old behavior to was to append the  "version" paraemter to the '
                               'target name \'protobuf-\' as the default for "javadeps".  Now '
                               '"javadeps" defaults to the value \'protobuf-java\'.',
  ('protobuf-gen', 'plugins'): 'The behavior of the "plugins" parameter has changed. '
                               'The old behavior was to unconditionally append "_protobuf" to the '
                               'end of the plugin name.  This will not work for plugins that have '
                               'a name that does not end in "_protobuf".',
  ('thrift-gen', 'verbose'): 'This flag is no longer supported. Use -ldebug instead.',
  ('ide', 'python_source_path'): 'python_source_path now must be specified separately for idea and '
                                 'eclipse goals.',
  ('ide', 'python_lib_paths'): 'python_lib_path now must be specified separately for idea and '
                              'eclipse goals.',
  ('ide', 'python_test_paths'): 'python_test_path now must be specified separately for idea and '
                               'eclipse goals.',
  ('ide', 'extra_jvm_source_paths'): 'extra_jvm_source_paths now must be specified separately for '
                                     'idea and eclipse goals.',
  ('ide', 'extra_jvm_test_paths'): 'extra_jvm_test_paths now must be specified separately for '
                                   'idea and eclipse goals.',
  ('ide', 'debug_port'): 'debug_port now must be specified separately for idea and eclipse '
                         'goals.  Also, IDE goals now use their own debug setting and do not '
                         'inherit from jvm configuration.',

  ('tasks', 'build_invalidator'): 'This is no longer configurable. The default will be used.',

  ('compile', 'ng_daemons'): ng_daemons_note,
  ('gen', 'ng_daemons'): ng_daemons_note,
  ('imports', 'ng_daemons'): ng_daemons_note,
  ('resolve', 'ng_daemons'): ng_daemons_note,
  ('scrooge-gen', 'scala'): scrooge_gen_deps_note,
  ('scrooge-gen', 'java'): scrooge_gen_deps_note,

  ('gen.thrift', 'version'): 'You can either set the apache thrift compiler version globally for '
                             'java and python using the [thrift-binary] scope or else you can '
                             'configure the languages separately using the '
                             '[thrift-binary.gen.thrift] scope to control the version used for '
                             'java.',

  ('gen.thrift', 'java'): 'The java configuration has migrated from a single dict with 3 keys to '
                          '3 options.\n'
                          'The "gen" key has migrated to the `gen_options` option and the value '
                          'should just be the option portion of the thrift --gen argument.  For '
                          'example, if you had `"gen": "java:hashcode"` as your java dict entry '
                          'you\'d now use the top-level option `gen_options: hashcode`.\n'
                          'The "deps.structs" nested key has migrated to the `deps` option and the '
                          'value remains the same.\n'
                          'The "deps.service" nested key as migrated to the `service_deps` option '
                          'and the value remains the same, but is now optional if service deps are '
                          'the same as non-service deps.',

  ('gen.thrift', 'python'): 'The python configuration for gen.thrift has never been used and '
                            'should be removed.',

  ('resolve.ivy', 'automatic_excludes'): 'Enabled by default.',
  ('imports.ivy-imports', 'automatic_excludes'): 'Enabled by default.',

  ('compile.zinc-java', 'enabled'): 'The enabled flag has moved from "enable zinc for java" '
                                    'to "disable jmake for java", more precisely, instead of '
                                    '--compile-zinc-java-enabled, use --no-compile-java-use-jmake',
  ('compile.scala', 'args'): 'ALL `compile.scala` options have moved to `compile.zinc`.',

  ('compile.cpp-compile', 'cc_options'): 'Value used to be a string, is now a list.',
  ('compile.cpp-compile', 'cc_extensions'): 'Value used to be a string (but default was a list), '
                                            'is now a list. Values also now include the dot, e.g.,'
                                            'it\'s now .cpp, not cpp.',
  ('test.junit', 'coverage_console'): 'Option no longer exists. Coverage always written to stdout.',
  ('test.junit', 'coverage_html'): 'Option no longer exists. Coverage always written to html file.',
  ('test.junit', 'coverage_xml'): 'Option no longer exists. Coverage always written to xml file.',

  ('compile.apt', 'jar'): compile_jar_note,
  ('compile.java', 'jar'): compile_jar_note,
  ('compile.zinc', 'jar'): compile_jar_note,

  ('unknown-arguments', 'ignored'): 'Target name keys are now expected to be the alias used in '
                                    'BUILD files and not the target type\'s simple class name. '
                                    'For example, if you had \'JavaLibrary\' key you\'d now use '
                                    '\'java_library\' instead.',

  ('bench', 'benchmark-agent'): jvm_tool_spec_override,
  ('bench', 'benchmark-tool'): jvm_tool_spec_override,
  ('binary', 'nailgun-server'): jvm_tool_spec_override,
  ('binary.dex', 'nailgun-server'): jvm_tool_spec_override,
  ('binary.dup', 'nailgun-server'): jvm_tool_spec_override,
  ('bootstrap.bootstrap-jvm-tools', 'jarjar'): jvm_tool_spec_override,
  ('bootstrap.bootstrap-jvm-tools', 'nailgun-server'): jvm_tool_spec_override,
  ('bundle', 'nailgun-server'): jvm_tool_spec_override,
  ('bundle.dup', 'nailgun-server'): jvm_tool_spec_override,
  ('compile.apt', 'java-compiler'): jvm_tool_spec_override,
  ('compile.apt', 'jmake'): jvm_tool_spec_override,
  ('compile.apt', 'nailgun-server'): jvm_tool_spec_override,
  ('compile.checkstyle', 'checkstyle'): jvm_tool_spec_override,
  ('compile.checkstyle', 'nailgun-server'): jvm_tool_spec_override,
  ('compile.java', 'java-compiler'): jvm_tool_spec_override,
  ('compile.java', 'jmake'): jvm_tool_spec_override,
  ('compile.java', 'nailgun-server'): jvm_tool_spec_override,
  ('compile.scalastyle', 'nailgun-server'): jvm_tool_spec_override,
  ('compile.scalastyle', 'scalastyle'): jvm_tool_spec_override,
  ('compile.zinc', 'compiler-interface'): jvm_tool_spec_override,
  ('compile.zinc', 'nailgun-server'): jvm_tool_spec_override,
  ('compile.zinc', 'plugin-jars'): jvm_tool_spec_override,
  ('compile.zinc', 'sbt-interface'): jvm_tool_spec_override,
  ('compile.zinc', 'zinc'): jvm_tool_spec_override,
  ('detect-duplicates', 'nailgun-server'): jvm_tool_spec_override,
  ('gen.antlr', 'antlr3'): jvm_tool_spec_override,
  ('gen.antlr', 'antlr4'): jvm_tool_spec_override,
  ('gen.antlr', 'nailgun-server'): jvm_tool_spec_override,
  ('gen.jaxb', 'nailgun-server'): jvm_tool_spec_override,
  ('gen.scrooge', 'nailgun-server'): jvm_tool_spec_override,
  ('gen.scrooge', 'scrooge-gen'): jvm_tool_spec_override,
  ('gen.spindle', 'nailgun-server'): jvm_tool_spec_override,
  ('gen.spindle', 'spindle-codegen'): jvm_tool_spec_override,
  ('gen.wire', 'javadeps'): jvm_tool_spec_override,
  ('gen.wire', 'wire-compiler'): jvm_tool_spec_override,
  ('imports.ivy-imports', 'nailgun-server'): jvm_tool_spec_override,
  ('jar', 'nailgun-server'): jvm_tool_spec_override,
  ('jar-tool', 'jar-tool'): jvm_tool_spec_override,
  ('publish.jar', 'nailgun-server'): jvm_tool_spec_override,
  ('repl-dirty.scala-dirty', 'scala-repl'): jvm_tool_spec_override,
  ('repl.scala', 'scala-repl'): jvm_tool_spec_override,
  ('resolve.ivy', 'nailgun-server'): jvm_tool_spec_override,
  ('resolve.ivy', 'xalan'): jvm_tool_spec_override,
  ('scala-platform', 'scalac'): jvm_tool_spec_override,
  ('test.junit', 'cobertura-instrument'): jvm_tool_spec_override,
  ('test.junit', 'cobertura-report'): jvm_tool_spec_override,
  ('test.junit', 'cobertura-run'): jvm_tool_spec_override,
  ('test.junit', 'emma'): jvm_tool_spec_override,
  ('test.junit', 'junit'): jvm_tool_spec_override,
  ('thrift-linter', 'nailgun-server'): jvm_tool_spec_override,
  ('thrift-linter', 'scrooge-linter'): jvm_tool_spec_override,

  # Global strategy removal.
  ('compile.apt', 'changed-targets-heuristic-limit'): jvm_global_strategy_removal,
  ('compile.apt', 'partition-size-hint'): jvm_global_strategy_removal,
  ('compile.apt', 'strategy'): jvm_global_strategy_removal,
  ('compile.java', 'changed-targets-heuristic-limit'): jvm_global_strategy_removal,
  ('compile.java', 'partition-size-hint'): jvm_global_strategy_removal,
  ('compile.java', 'strategy'): jvm_global_strategy_removal,
  ('compile.zinc', 'changed-targets-heuristic-limit'): jvm_global_strategy_removal,
  ('compile.zinc', 'partition-size-hint'): jvm_global_strategy_removal,
  ('compile.zinc', 'strategy'): jvm_global_strategy_removal,
}

def check_option(cp, src, dst):
  def has_explicit_option(section, key):
    # David tried to avoid poking into cp's guts in https://rbcommons.com/s/twitter/r/1451/ but
    # that approach fails for the important case of boolean options.  Since this is a ~short term
    # tool and its highly likely its lifetime will be shorter than the time the private
    # ConfigParser_sections API we use here changes, it's worth the risk.
    if section == 'DEFAULT':
      # NB: The 'DEFAULT' section is not tracked via `has_section` or `_sections`, so we use a
      # different API to check for an explicit default.
      return key in cp.defaults()
    else:
      return cp.has_section(section) and (key in cp._sections[section])

  def sect(s):
    return cyan('[{}]'.format(s))

  src_section, src_key = src
  if has_explicit_option(src_section, src_key):
    if dst is not None:
      dst_section, dst_key = dst
      print('Found {src_key} in section {src_section}. Should be {dst_key} in section '
            '{dst_section}.'.format(src_key=green(src_key), src_section=sect(src_section),
                                    dst_key=green(dst_key), dst_section=sect(dst_section)),
            file=sys.stderr)
    elif src not in notes:
      print('Found {src_key} in section {src_section} and there is no automated migration path'
            'for this option.  Please consult the '
            'codebase.'.format(src_key=red(src_key), src_section=red(src_section)))

    if (src_section, src_key) in notes:
      print('  Note for {src_key} in section {src_section}: {note}'
            .format(src_key=green(src_key),
                    src_section=sect(src_section),
                    note=yellow(notes[(src_section, src_key)])))

def check_config_file(path):
  cp = Config._create_parser()
  with open(path, 'r') as ini:
    cp.readfp(ini)

  print('Checking config file at {} for unmigrated keys.'.format(path), file=sys.stderr)

  def section(s):
    return cyan('[{}]'.format(s))

  for src, dst in migrations.items():
    check_option(cp, src, dst)

  # Special-case handling of per-task subsystem options, so we can sweep them up in all
  # sections easily.

  def check_task_subsystem_options(subsystem_sec, options_map, sections=None):
    sections = sections or cp.sections()
    for src_sec in ['DEFAULT'] + sections:
      dst_sec = subsystem_sec if src_sec == 'DEFAULT' else '{}.{}'.format(subsystem_sec, src_sec)
      for src_key, dst_key in options_map.items():
        check_option(cp, (src_sec, src_key), (dst_sec, dst_key))

  artifact_cache_options_map = {
    'read_from_artifact_cache': 'read',
    'write_to_artifact_cache': 'write',
    'overwrite_cache_artifacts': 'overwrite',
    'read_artifact_caches': 'read_from',
    'write_artifact_caches': 'write_to',
    'cache_compression': 'compression_level',
  }
  check_task_subsystem_options('cache', artifact_cache_options_map)

  jvm_options_map = {
    'jvm_options': 'options',
    'args': 'program_args',
    'debug': 'debug',
    'debug_port': 'debug_port',
    'debug_args': 'debug_args',
  }
  jvm_options_sections = [
    'repl.scala', 'test.junit', 'run.jvm', 'bench', 'doc.javadoc', 'doc.scaladoc'
  ]
  check_task_subsystem_options('jvm', jvm_options_map, sections=jvm_options_sections)

  # Check that all values are parseable.
  for sec in ['DEFAULT'] + cp.sections():
    for key, value in cp.items(sec):
      value = value.strip()
      if value.startswith('['):
        try:
          custom_types.list_option(value)
        except ParseError:
          print('Value of {key} in section {section} is not a valid '
                'JSON list.'.format(key=green(key), section=section(sec)))
      elif value.startswith('{'):
        try:
          custom_types.dict_option(value)
        except ParseError:
          print('Value of {key} in section {section} is not a valid '
                'JSON object.'.format(key=green(key), section=section(sec)))

if __name__ == '__main__':
  if len(sys.argv) > 2:
    print('Usage: migrate_config.py [path to pants.ini file]', file=sys.stderr)
    sys.exit(1)
  elif len(sys.argv) > 1:
    path = sys.argv[1]
  else:
    path = './pants.ini'
  check_config_file(path)


text:
GitHub Repos
------------

| Script Name        | Description   |
| -------------      | ------------- |
| [PackUI]           | Package a .py script and its .pyui file into a self-extracting bundle |
| [Task-List][]      | Create, read, update, and delete task lists |
| [ui-tutorial][]    | UI Tutorial gives you a running start in using the ui module |
| [uicomponents][]   | Various specialized ui components |

GitHub Gists
------------
| Script Name        | Description   |
| -------------      | ------------- |
| [Nav view example][]     | An example on how to use the nav view |
| [proplistener][]     | Observe changes in ui properties, and take action|
| [zoomview][]     | Pinch zoomable window example  |
| [tabbedview][]     | View with tabs that switch subview |
| [touchdispatcher][]     | Intercept touch events before sending to subviews|

Custom Modules
------------

| Script Name        | Description   |
| -------------      | ------------- |
| [Hydrogen][]      | A lightweight GUI framework for Pythonista that requires [HydrogenLayouts][] and [HydrogenDemo][]|

[PackUI]: https://github.com/dgelessus/pythonista-scripts/blob/master/PackUI.py
[Task-List]: https://github.com/robinsiebler/Task-List
[ui-tutorial]: https://github.com/humberry/ui-tutorial
[Nav view example]: https://gist.github.com/tjferry14/9ea8bfc0c8d089cdb530
[Hydrogen]: https://gist.github.com/BashedCrab/5924965
[HydrogenLayouts]: https://gist.github.com/BashedCrab/6103019
[HydrogenDemo]: https://gist.github.com/BashedCrab/5953776
[uicomponents]: https://github.com/jsbain/uicomponents
[zoomview]: https://gist.github.com/jsbain/6e4e406b07f52a68d961
[touchdispatcher]: https://gist.github.com/jsbain/1cf350e92bb5f59706ca
[tabbedview]: https://gist.github.com/jsbain/fcadaffff4be09c4ec78
[proplistener]: https://gist.github.com/jsbain/87cf25db0d3f1b16c512


text: bin\phantomjs.exe src\get_youtube.js https://www.youtube.com/watch?v=e8HnVdTrVrA 500 1


text:
require 'rails_helper'

module FormolApi
  RSpec.describe Forum, :type => :model do
    describe "Structure" do
      it { is_expected.to have_db_column(:category_id) }
      it { is_expected.to have_db_column(:name) }
      it { is_expected.to have_db_column(:description) }
      it { is_expected.to have_db_column(:position) }
      it { is_expected.to have_db_column(:created_at) }
      it { is_expected.to have_db_column(:updated_at) }
    end

    describe "Associations" do
      it { is_expected.to belong_to(:category).counter_cache(true) }
    end

    describe "Scopes" do
      let(:category){ FactoryGirl.create(:category) }
      let!(:forums){ FactoryGirl.create_list(:forum, 2, :category => category) }
      let!(:first_forum){ FactoryGirl.create(:forum, :category => category) }

      before do
        first_forum.insert_at(1)
      end

      subject { Forum.ordered }

      it { is_expected.to eq([first_forum] + forums) }
    end
  end
end


text:
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.View;
import org.jgroups.util.Util;

import java.io.*;
import java.util.List;
import java.util.LinkedList;

public class SimpleChat extends ReceiverAdapter {
    JChannel channel;
    String user_name=System.getProperty("user.name", "n/a");
    final List<String> state=new LinkedList<>();

    public void viewAccepted(View new_view) {
        System.out.println("** view: " + new_view);
    }

    public void receive(Message msg) {
        String line=msg.getSrc() + ": " + msg.getObject();
        System.out.println(line);
        synchronized(state) {
            state.add(line);
        }
    }

    public void getState(OutputStream output) throws Exception {
        synchronized(state) {
            Util.objectToStream(state, new DataOutputStream(output));
        }
    }

    @SuppressWarnings("unchecked")
    public void setState(InputStream input) throws Exception {
        List<String> list=Util.objectFromStream(new DataInputStream(input));
        synchronized(state) {
            state.clear();
            state.addAll(list);
        }
        System.out.println("received state (" + list.size() + " messages in chat history):");
        list.forEach(System.out::println);
    }

    private void start() throws Exception {
        channel=new JChannel().setReceiver(this);
        channel.connect("ChatCluster");
        channel.getState(null, 10000);
        eventLoop();
        channel.close();
    }

    private void eventLoop() {
        BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
        while(true) {
            try {
                System.out.print("> "); System.out.flush();
                String line=in.readLine().toLowerCase();
                if(line.startsWith("quit") || line.startsWith("exit")) {
                    break;
                }
                line="[" + user_name + "] " + line;
                Message msg=new Message(null, line);
                channel.send(msg);
            }
            catch(Exception e) {
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new SimpleChat().start();
    }
}


text:
package org.elasticsearch.common.xcontent;

import org.apache.lucene.util.BytesRef;

import java.io.Closeable;
import java.io.IOException;
import java.util.Map;

/**
 *
 */
public interface XContentParser extends Closeable {

    enum Token {
        START_OBJECT {
            @Override
            public boolean isValue() {
                return false;
            }
        },

        END_OBJECT {
            @Override
            public boolean isValue() {
                return false;
            }
        },

        START_ARRAY {
            @Override
            public boolean isValue() {
                return false;
            }
        },

        END_ARRAY {
            @Override
            public boolean isValue() {
                return false;
            }
        },

        FIELD_NAME {
            @Override
            public boolean isValue() {
                return false;
            }
        },

        VALUE_STRING {
            @Override
            public boolean isValue() {
                return true;
            }
        },

        VALUE_NUMBER {
            @Override
            public boolean isValue() {
                return true;
            }
        },

        VALUE_BOOLEAN {
            @Override
            public boolean isValue() {
                return true;
            }
        },

        // usually a binary value
        VALUE_EMBEDDED_OBJECT {
            @Override
            public boolean isValue() {
                return true;
            }
        },

        VALUE_NULL {
            @Override
            public boolean isValue() {
                return false;
            }
        };

        public abstract boolean isValue();
    }

    enum NumberType {
        INT, LONG, FLOAT, DOUBLE
    }

    XContentType contentType();

    Token nextToken() throws IOException;

    void skipChildren() throws IOException;

    Token currentToken();

    String currentName() throws IOException;

    Map<String, Object> map() throws IOException;

    Map<String, Object> mapOrdered() throws IOException;

    Map<String, Object> mapAndClose() throws IOException;

    Map<String, Object> mapOrderedAndClose() throws IOException;

    String text() throws IOException;

    String textOrNull() throws IOException;

    BytesRef bytesOrNull() throws IOException;

    BytesRef bytes() throws IOException;

    Object objectText() throws IOException;

    Object objectBytes() throws IOException;

    boolean hasTextCharacters();

    char[] textCharacters() throws IOException;

    int textLength() throws IOException;

    int textOffset() throws IOException;

    Number numberValue() throws IOException;

    NumberType numberType() throws IOException;

    /**
     * Is the number type estimated or not (i.e. an int might actually be a long, its just low enough
     * to be an int).
     */
    boolean estimatedNumberType();

    short shortValue(boolean coerce) throws IOException;

    int intValue(boolean coerce) throws IOException;

    long longValue(boolean coerce) throws IOException;

    float floatValue(boolean coerce) throws IOException;

    double doubleValue(boolean coerce) throws IOException;

    short shortValue() throws IOException;

    int intValue() throws IOException;

    long longValue() throws IOException;

    float floatValue() throws IOException;

    double doubleValue() throws IOException;

    /**
     * returns true if the current value is boolean in nature.
     * values that are considered booleans:
     * - boolean value (true/false)
     * - numeric integers (=0 is considered as false, !=0 is true)
     * - one of the following strings: "true","false","on","off","yes","no","1","0"
     */
    boolean isBooleanValue() throws IOException;

    boolean booleanValue() throws IOException;

    byte[] binaryValue() throws IOException;

    void close();
}


text:
import { getIn } from './getIn';
import { hasValueEqual } from './hasValueEqual';

export function hasValueEqualIn(targetValue: any, targetKeys: string, srcValue: any, srcKeys: string): boolean {
  return hasValueEqual(getIn(targetValue, targetKeys), getIn(srcValue, srcKeys));
}


text:
package org.apache.river.jeri.internal.runtime;

/**
 * Wraps collection elements (such as hash table keys) so that two
 * wrapped elements are only considered to be equal if they have the
 * same class (as well as being equal by Object.equals).
 *
 * This class is used to wrap elements in a collection when their
 * classes are not all trusted, with the restriction that only
 * elements of the same class can be considered equal.  This class
 * never invokes Object.equals on an underlying element with an
 * argument that has a different class than the element, to avoid
 * leaking sensitive information to untrusted elements.
 *
 * For this isolation scheme to work, the Object.equals method of any
 * trusted element class should not invoke comparison methods (such as
 * Object.equals) on any pluggable component without first verifying
 * that the component's implementation is at least as trusted as the
 * implementation of the corresponding component in the Object.equals
 * argument (such as by verifying that the corresponding component
 * objects have the same actual class).  If any such verification
 * fails, the Object.equals method should return false without
 * invoking a comparison method on the component.  Furthermore, these
 * guidelines should be recursively obeyed by the comparison methods
 * of each such component for its subcomponents.
 *
 * @author Sun Microsystems, Inc.
 **/
final class SameClassKey {

    private final Object key;

    SameClassKey(Object key) {
	this.key = key;
    }

    public int hashCode() {
	return key.hashCode();
    }

    public boolean equals(Object obj) {
	if (obj == this) {
	    return true;
	} else if (!(obj instanceof SameClassKey)) {
	    return false;
	}
	SameClassKey other = (SameClassKey) obj;
	return Util.sameClassAndEquals(key, other.key);
    }
}


text:
#ifndef StorageStrategy_h
#define StorageStrategy_h

#include <wtf/Forward.h>

namespace WebCore {

class Page;
class PageGroup;
class SecurityOrigin;
class StorageNamespace;

class StorageStrategy {
public:
    virtual PassRefPtr<StorageNamespace> localStorageNamespace(PageGroup*);
    virtual PassRefPtr<StorageNamespace> transientLocalStorageNamespace(PageGroup*, SecurityOrigin*);
    virtual PassRefPtr<StorageNamespace> sessionStorageNamespace(Page*);

protected:
    virtual ~StorageStrategy()
    {
    }
};

} // namespace WebCore

#endif // StorageStrategy_h


text:
goal-oriented-action-planning-for-artificial-intelligence
=========================================================