text:
from abc import ABCMeta, abstractmethod, abstractproperty
import warnings

import numpy as np
import sympy
import sympy.physics.quantum as sq

from parampy import Parameters

from .operator import Operator

class Basis(object):
	'''
	A Basis instance describes a particular basis, and allows transformations
	of objects (such as `Operator`s) from one basis to another. A Basis
	is an abstract class, and must be subclassed to be useful.

	:param dim: The dimension of the basis. If not specified, the dimension will
		be extracted from the Operator returned by Basis.operator; except during
		`Basis.init`, where `Basis.dim` will return the raw value stored (e.g. None).
	:type dim: int or None
	:param parameters: A Parameters instance, if required.
	:type parameters: parampy.Parameters
	:param kwargs: Additional keyword arguments to pass to `Basis.init`.
	:type kwargs: dict

	Subclassing Basis:
		Subclasses of Basis must implement the following methods, which function according to
		their respective documentation below:
		- init
		- operator
		Subclasses may optionally implement:
		- state_info
		- state_toString
		- state_fromString
		- state_latex
		These latter methods are used to allow convenient conversion of strings to states
		and also later representation of states as strings/LaTeX. Otherwise, these
		methods are not required. Since they are not used except when the user desires
		to change the state's representation, the implementer has a lot of freedom
		about the way these functions work, and what they return. The documentation
		for these methods indicates the way in which the original author intended
		for them to function.
	'''
	__metaclass__ = ABCMeta

	def __init__(self, dim=None, parameters=None, **kwargs):
		self.dim = dim
		self.p = parameters

		self._basis_initialising = True
		self.init(**kwargs)
		del self._basis_initialising

	@abstractmethod
	def init(self, **kwargs):
		'''
		This method should do whatever is necessary to prepare the
		Basis instance for use. When this method is called by the
		Python __init__ method, you can use `Basis.dim` to access
		the raw value of `dim`. If `dim` is necessary to construct
		the operator, and it is not set, this method should raise an
		exception. All keyword arguments except `dim` and `parameters`
		passed to the `Basis` instance constructor will also be passed to
		this method.
		'''
		pass

	def __repr__(self):
		return "<%s(Basis) of dimension %d>" % (self.__class__.__name__, self.dim)

	@property
	def dim(self):
		'''
		The dimension of the basis; or equivalently, the number of basis states.
		'''
		if self.__dim == None and not getattr(self,'_basis_initialising',False):
			self.__dim = self.operator().shape[0]
		return self.__dim
	@dim.setter
	def dim(self, dim):
		try:
			if self.__dim is not None:
				raise ValueError("Attempt to change Basis dimension after initialisation. This is not supported.")
		except AttributeError:
			pass
		self.__dim = int(dim) if dim is not None else None

	@property
	def p(self):
		'''
		A reference to the Parameters instance used by this object.
		'''
		if self.__p is None:
			raise ValueError("Parameters instance required by Basis object, a Parameters object has not been configured.")
		return self.__p
	@p.setter
	def p(self, parameters):
		if parameters is not None and not isinstance(parameters, Parameters):
			raise ValueError("Parameters reference must be an instance of Parameters or None.")
		self.__p = parameters

	def __p_ref(self):
		'''
		This method allows child Operator objects to automatically be kept up to date with
		changes to the Parameters instance associated with the StateOperator object. This
		cannot be used directly, but is used by the StateOperator.Operator method.
		'''
		return self.__p

	def Operator(self, components, basis=None, exact=False):
		'''
		This method is a shorthand for constructing Operator objects which refer
		to the same Parameters instance as this Basis instance.

		:param components: Specification for Operator.
		:type components: Operator, dict, numpy.ndarray or sympy.MatrixBase
		:param basis: The basis in which the Operator is represented.
		:type basis: Basis or None
		:param exact: True if Operator should maintain exact representations of numbers,
			and False otherwise.
		:type exact: bool

		If *components* is already an Operator object, it is returned with its
		Parameters reference updated to point the Parameters instance associated
		with this Basis instance. Otherwise, a new Operator is constructed according
		to the specifications, again with a reference to this Basis's
		Parameters instance.

		For more information, refer to the documentation for Operator.
		'''
		if not isinstance(components, Operator):
			operator = Operator(components)
		operator.p = self.__p_ref
		return operator

	@abstractproperty
	def operator(self):
		'''
		This method should return a two dimensional `Operator` object, with basis states as
		columns. The `Operator` object should use the `Parameters` instance provided by the
		Basis instance. The simplest way to ensure this is to use the `Basis.Operator` method.
		'''
		raise NotImplementedError("Basis operator has not been implemented.")

	def states(self, **params):
		'''
		This method returns the basis states (columns of the `Operator` returned by
		`basis.operator`) as a list. The Operator is first evaluated with the
		parameter overrides in params.

		:param params: A dictionary of parameter overrides. (see `parampy.Parameters`)
		:type params: dict
		'''
		i = xrange(self.dim)
		O = self.operator(**params)
		return map(lambda i: O[:, i], i)

	def state_info(self, state, params={}):
		'''
		This method (if implemented) should return a dictionary with more information
		about the state provided. There are no further constraints upon what might be
		returned.

		:param state: The state about which information should be returned.
		:type state: str or iterable
		:param params: A dictionary of parameter overrides. (see `parampy.Parameters`)
		:type params: dict
		'''
		return NotImplementedError("Basis.state_info has not been implemented.")

	def state_toString(self, state, params={}):
		'''
		This method (if implemented) should return a string representation of the
		provided state, which should then be able to be converted back into the same
		state using `Basis.state_fromString`.

		:param state: The state which should be represented as a string.
		:type state: iterable
		:param params: A dictionary of parameter overrides. (see `parampy.Parameters`)
		:type params: dict
		'''
		raise NotImplementedError("Basis.state_toString has not been implemented.")

	def state_fromString(self, string, params={}):
		'''
		This method (if implemented) should return the state as a numerical array that
		is represented as a string in `string`. Calling `basis.state_toString` should then
		return the same (or equivalent) string representation.

		:param string: A string representation of a state.
		:type state: str
		:param params: A dictionary of parameter overrides. (see `parampy.Parameters`)
		:type params: dict
		'''
		raise NotImplementedError("Basis.state_fromString has not been implemented.")

	def state_latex(self, state, params={}):
		'''
		This method (if implemented) should return string that when compiled by
		LaTeX would represent the state.

		:param state: The state which should be represented as a string.
		:type state: iterable
		:param params: A dictionary of parameter overrides. (see `parampy.Parameters`)
		:type params: dict
		'''
		raise NotImplementedError("Basis.state_latex has not been implemented.")

	def state_toSymbolic(self, state):
		'''
		This method is a stub, and may be implemented in the future to provide the
		logical inverse of `Basis.state_fromSymbolic`.
		'''
		raise NotImplementedError("Conversion of a state to a symbolic representation has not yet been implemented.")

	def state_fromSymbolic(self, expr):
		'''
		This method converts a sympy representation of a quantum state into
		an array or vector (as used by QuBricks). It uses internally `Basis.state_fromString`
		to recognise ket and bra names, and to substitute them appropriately with the right
		state vectors.

		.. warning:: Support for conversion from symbolic representations is not fully
			baked, but seems to work reasonably well.
		'''

		r = np.array(sq.represent(expr, basis=self.__sympy_basis).tolist(), dtype=object)

		if len(r.shape) == 2:
			if r.shape[0] == 1:
				r = r[0, :]
			else:
				r = r[:, 0]
		return r

	@property
	def __sympy_basis(self):
		'''
		Sympy requires an operator instance to determine how states should represent
		themselves. This property provides such an instance.
		'''
		op = QubricksBasis(self.__class__.__name__)
		op.qubricks = self
		return op

	#
	# Transform vector and matrix elements from the standard basis to this basis
	def transform(self, state, inverse=False, threshold=False, params={}):
		'''
		This method allows one to transform states from the standard basis to
		this basis; or, if the inverse flag is provided, to transform from this
		basis to the standard basis. This is chained in the Basis.transform_to and
		Basis.transform_from methods to convert states between bases. State objects
		can be Operator or numpy array objects; and can be one or two dimensional.
		The basis states are evaluated in the parameter context specified in `params`
		before being used in this method.

		This method can automatically try to set elements in the transformed object that
		are different from zero by some small amount to zero, in the hope of ignoring
		numerical error. If threshold is `False`, no attempts to clean the transformed state are made.
		If a numerical threshold is provided, any elements of the resulting
		transformed state with amplitude less than the supplied value will be set
		to zero. If threshold is set to True, the transformation operation attempts
		to determine the threshold automatically. This automatic algorithm looks
		for the smallest entry in `Basis.operator` and then multiplies it by 10**-8.
		This value is then used as the threshold. One should use this feature with
		caution.

		:param state: The state to be transformed.
		:type state: 1D or 2D Operator or numpy.ndarray
		:param inverse: `True` for transformation from this basis to the standard basis,
			and `False` for transformation to this basis from the standard basis.
		:type inverse: bool
		:param threshold: True or False to specify that the threshold should be automatically
			determined or not used respectively. If a float is provided, that value is used as
			the threshold.
		:type threshold: bool or float
		:param params: The parameter overrides to use during the transformation (see `Operator`).
		:type params: dict
		'''

		if isinstance(state, Operator):
			self.operator.basis = "*"

			if len(state.shape) == 1:
				if inverse:
					output = self.operator * state
				else:
					output = self.operator.inverse() * state

			elif len(state.shape) == 2:  # assume square
				if inverse:
					output = self.operator * state * self.operator.inverse()
				else:
					output = self.operator.inverse() * state * self.operator
			else:
				raise ValueError

			return self.__filter(output, state=state, threshold=threshold, params=params)

		elif isinstance(state, str):
			state = self.state_fromString(state, params)

		elif not isinstance(state, np.ndarray):
			state = np.array(state)

		state = np.array(state)
		output = None

		o = self.operator(**params)

		# If input is a vector
		if state.ndim == 1:
			if not inverse:
				o = np.linalg.inv(o)
			output = np.dot(o, state)
		elif state.ndim == 2:
			od = np.linalg.inv(o)
			if inverse:
				output = np.dot(o, np.dot(state, od))
			else:
				output = np.dot(od, np.dot(state, o))
		else:
			raise ValueError("Invalid number of dimensions.")

		return self.__filter(output, state=state, threshold=threshold, params=params)

	def __filter(self, output, state=None, threshold=False, params={}):
		'''
		Basis.__filter is a private method that implements the thresholding described in
		the documentation for Basis.transform .
		'''

		def __filter_threshold(a):
			# TODO: DO THIS MORE NEATLY?
			'''
			Determine the minimum threshold over real and imaginary components which should capture everything.
			'''
			try:
				real_ind = np.where(np.abs(a.real) > 1e-15)
				t_real = np.min(np.abs(a[real_ind])) if len(real_ind[0]) > 0 else np.inf

				imag_ind = np.where(np.abs(a.imag) > 1e-15)
				t_imag = np.min(np.abs(a[imag_ind])) if len(imag_ind[0]) > 0 else np.inf

				return min(t_real, t_imag)
			except:
				return False

		if threshold is False:
			return output

		warnings.warn("Be careful with auto-thresholding.")
		threshold = __filter_threshold(self.operator(**params))
		# print "op threshold", threshold
		if state is not None:
			if isinstance(state, Operator):
				threshold = np.min(map(__filter_threshold, state.components.values()))  # TODO: do more abstractly?
			else:
				threshold = min(__filter_threshold(state), threshold)
		# print "w/ state threshold", threshold
		if threshold is False:
			return output

		threshold *= 1e-8
		# print "final threshold", threshold

		if isinstance(state, Operator):
			output.clean(threshold)
		else:
			ind = np.where(np.abs(output) < threshold)
			output[ind] = 0
		return output

	def transform_from(self, state, basis=None, threshold=False, params={}):
		'''
		This method transforms the given state to this basis from the basis provided in
		`basis` (which must be a Basis instance). If `basis` is note provided, the
		standard basis is assumed.

		:param state: The state to be transformed.
		:type state: 1D or 2D Operator or numpy.ndarray
		:param basis: The basis into which the state should be transformed.
		:type basis: Basis or None
		:param threshold: True or False to specify that the threshold should be automatically
			determined or not used respectively. If a float is provided, that value is used as
			the threshold.
		:type threshold: bool or float
		:param params: The parameter overrides to use during the transformation (see `Operator`).
		:type params: dict
		'''
		if basis is not None:
			if not isinstance(basis, Basis):
				raise ValueError('`basis` must be a Basis object; received `%s` of type `%s`.' % (str(basis), type(basis)))
			state = basis.transform(state, inverse=True, threshold=threshold, params=params)

		return self.transform(state, threshold=threshold, params=params)

	def transform_to(self, state, basis=None, threshold=False, params={}):
		'''
		This method transforms the given state from this basis to the basis provided in
		`basis` (which must be a Basis instance). If `basis` is note provided, the
		standard basis is assumed.

		:param state: The state to be transformed.
		:type state: 1D or 2D Operator or numpy.ndarray
		:param basis: The basis into which the state should be transformed.
		:type basis: Basis or None
		:param threshold: True or False to specify that the threshold should be automatically
			determined or not used respectively. If a float is provided, that value is used as
			the threshold.
		:type threshold: bool or float
		:param params: The parameter overrides to use during the transformation (see `Operator`).
		:type params: dict
		'''
		if basis is not None:
			if not isinstance(basis, Basis):
				raise ValueError('`basis` must be a Basis object.')
			return basis.transform_from(state, basis=self, threshold=threshold, params=params)

		return self.transform(state, inverse=True, threshold=threshold, params=params)

	def transform_op(self, basis=None, inverse=False, threshold=False, params={}):
		'''
		This method returns a function which can be used to transform any 1D or 2D
		`Operator` or numpy array to (from) this basis from (to) the basis provided
		in `basis`, if `inverse` is False (True). If basis is not provided, the
		standard basis is assumed.

		:param state: The state to be transformed.
		:type state: 1D or 2D Operator or numpy.ndarray
		:param basis: The basis into which the state should be transformed.
		:type basis: Basis or None
		:param inverse: `True` for transformation from this basis to the `basis` provided,
			and `False` for transformation to this basis from the the `basis` provided.
		:type inverse: bool
		:param threshold: True or False to specify that the threshold should be automatically
			determined or not used respectively. If a float is provided, that value is used as
			the threshold.
		:type threshold: bool or float
		:param params: The parameter overrides to use during the transformation (see `Operator`).
		:type params: dict

		For example:

		>>> f = Basis.transform_op()
		>>> state_transformed = f(state)
		'''
		if inverse:
			return lambda y: self.transform_to(y, basis=basis, threshold=threshold, params=params)
		return lambda y: self.transform_from(y, basis=basis, threshold=threshold, params=params)

############ SYMBOLIC STATE REPRESENTATION HELPERS #################################################

class QubricksBasis(sq.Operator):
	'''
	This object is used internally to support symbolic representations of states.
	'''
	pass

# TODO: Flesh out sympy symbolic representation
class QubricksKet(sq.Ket):
	'''
	This object is used to represent states analytically.

	For example:

	>>> ket = QubricksKet('0')

	These objects then obey standard arithmetic, for example:

	>>> 2*ket
	2|0>

	You can convert from a symbolic representation of states
	to a QuBricks array using `Basis.state_fromSymbolic`.
	'''
	def _represent_QubricksBasis(self, basis, **options):
		if getattr(basis, 'qubricks') is None:
			raise ValueError("The `qubricks` attribute must be set on the basis object for ket representation.")
		# print str(self)
		# print sympy.Matrix( basis.qubricks.state_fromString(str(self)) ).applyfunc(sympy.nsimplify)
		return sympy.Matrix(basis.qubricks.state_fromString(str(self))).applyfunc(sympy.nsimplify)

	def _eval_innerproduct_QubricksBra(self, bra, **hints):
		return 1 if bra.label == self.label else 0

	def _eval_conjugate(self):
		return QubricksBra(*self.label)

	@property
	def strlabel(self):
		return ",".join(map(str, self.label))

	def __mul__(self, other):
		if isinstance(other, QubricksKet):
			return QubricksKet(",".join((self.strlabel, other.strlabel)))
		return super(QubricksKet, self).__mul__(other)

	def __rmul__(self, other):
		if isinstance(other, QubricksKet):
			return QubricksKet(",".join((other.strlabel, self.strlabel)))
		return super(QubricksKet, self).__rmul__(other)

	def __pow__(self, power):
		r = 1
		for _ in xrange(power):
			r *= self
		return r

	@classmethod
	def dual_class(self):
		return QubricksBra

class QubricksBra(sq.Bra):
	'''
	This object is used to represent states analytically.

	For example:

	>>> bra = QubricksBra('0')

	These objects then obey standard arithmetic, for example:

	>>> 2*bra
	2<0|

	You can convert from a symbolic representation of states
	to a QuBricks array using `Basis.state_fromSymbolic`.
	'''

	@classmethod
	def dual_class(self):
		return QubricksKet

	def _represent_QubricksBasis(self, basis, **options):
		if 'qubricks_basis' not in options:
			raise ValueError("Qubricks basis object must be passed to ket for representation.")
		basis = options['qubricks_basis']
		l = ",".join(map(str, self.label))
		return sympy.Matrix(basis.state_fromString("|%s>" % l).transpose()).applyfunc(sympy.nsimplify)


text:
tagCameraData::tagCameraData ( )
{
	// setup default values for the structure, by creating a constructor
	// here it saves us having to call memset every time we create an instance
	// of it and we can also setup default values

	// clear the structure
	memset ( this, 0, sizeof ( tagCameraData ) );

	// mike - 250903 - override camera
	bOverride = false;

	//Dave extra camera flags
	dwCameraSwitchBank = 0;

	// setup default values
	fAspect     = 0.0f;							// the aspect will come in later on
	fAspectMod  = 0.0f;							// modifier
	fFOV        = D3DX_PI / 4;						// setup the field of view (degrees)
	fZNear      = 1.0;							// near clipping range
	fZFar       = 3000.0;						// far clipping range
	vecLook     = D3DXVECTOR3 ( 0, 0, 1 );		// look vector
	vecUp       = D3DXVECTOR3 ( 0, 1, 0 );		// up vector
	vecRight    = D3DXVECTOR3 ( 1, 0, 0 );		// right vector
	vecPosition = D3DXVECTOR3 ( 0, 0, 0 );		// position

	D3DXMatrixIdentity ( &matFreeFlightRotate );// freeflight

	bRotate     = true;							// rotation for x, y and then z

	iBackdropState=0;							// used as an automatic clear
	// aaron - 20120813 - give backdrop new color for DB3
	//dwBackdropColor=D3DCOLOR_XRGB(0,0,128);		// color of backdrop
	dwBackdropColor = 0xFF194C7F;				// color of backdrop

	dwForegroundColor=0;						// U75 - 070410 - color of foreground (used to WIPE OUT textures/effects)

	iBackdropTextureMode=0;						// no backdrop texture by default
	pBackdropTexture=NULL;
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="net.grappendorf.buyright">

  <uses-feature android:name="android.hardware.type.watch"/>

  <application
      android:allowBackup="true"
      android:label="@string/app_name"
      android:icon="@mipmap/logo"
      android:theme="@style/AppTheme">

    <meta-data android:name="com.google.android.gms.version"
               android:value="@integer/google_play_services_version"/>

    <activity
        android:name=".ProductsActivity"
        android:icon="@mipmap/logo"
        android:launchMode="singleTask">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>

    <activity android:name=".BuyrightPreferences"
              android:parentActivityName=".ProductsActivity"/>

  </application>

</manifest>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="XMenu">
        <attr name="LeftShadowDrawable" format="reference" />
        <attr name="touchModeAbove" format="integer" />
        <attr name="edgeWidth" format="integer" />
    </declare-styleable>
</resources>


text:
<form method="post" action="<?php echo site_url('mailer/send_invoice/' . $invoice->invoice_id) ?>">
    <input type="hidden" name="_ip_csrf" value="<?= $this->security->get_csrf_hash() ?>">

<?php _trans('email_invoice'); ?>

                <button class="btn btn-primary ajax-loader" name="btn_send" value="1">

                    <?php _trans('send'); ?>
                </button>
                <button class="btn btn-danger" name="btn_cancel" value="1">

                    <?php _trans('cancel'); ?>
                </button>

                <?php $this->layout->load_view('layout/alerts'); ?>

                    <?php _trans('to_email'); ?>
                    <input type="email" name="to_email" id="to_email" class="form-control" required
                           value="<?php echo $invoice->client_email; ?>">

                    <?php _trans('email_template'); ?>
                    <select name="email_template" id="email_template" class="form-control simple-select">
                        <option value=""><?php _trans('none'); ?></option>
                        <?php foreach ($email_templates as $email_template): ?>
                            <option value="<?php echo $email_template->email_template_id; ?>"
                                <?php check_select($selected_email_template, $email_template->email_template_id); ?>>
                                <?php _htmlsc($email_template->email_template_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <?php _trans('from_name'); ?>
                    <input type="text" name="from_name" id="from_name" class="form-control"
                           value="<?php _htmlsc($invoice->user_name); ?>">

                    <?php _trans('from_email'); ?>
                    <input type="email" name="from_email" id="from_email" class="form-control"
                           value="<?php echo $invoice->user_email; ?>">

                    <?php _trans('cc'); ?>
                    <input type="text" name="cc" id="cc" value="" class="form-control">

                    <?php _trans('bcc'); ?>
                    <input type="text" name="bcc" id="bcc" value="" class="form-control">

                    <?php _trans('subject'); ?>
                    <input type="text" name="subject" id="subject" class="form-control"
                           value="<?php echo trans('invoice') . ' #' . $invoice->invoice_number; ?>">

                    <?php _trans('pdf_template'); ?>
                    <select name="pdf_template" id="pdf_template" class="form-control simple-select">
                        <option value=""><?php _trans('none'); ?></option>
                        <?php foreach ($pdf_templates as $pdf_template): ?>
                            <option value="<?php echo $pdf_template; ?>"
                                <?php check_select($selected_pdf_template, $pdf_template); ?>>
                                <?php echo $pdf_template; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>

                    <?php _trans('body'); ?>

                        H1
                        H2
                        H3
                        H4

                            <hr/>

                            CSS

                    <textarea name="body" id="body" rows="8"
                              class="email-template-body form-control taggable"></textarea>

                            <?php _trans('preview'); ?>

                <?php $this->layout->load_view('email_templates/template-tags'); ?>

                    <?php $this->layout->load_view('upload/dropzone-invoice-html'); ?>

<?php _trans('guest_url'); ?>

                        <input type="text" id="invoice-guest-url" readonly class="form-control"
                               value="<?php echo site_url('guest/view/invoice/' . $invoice->invoice_url_key) ?>">

</form>

<?php $this->layout->load_view('upload/dropzone-invoice-scripts'); ?>


text:
package com.mysql.jdbc;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

public class StandardLoadBalanceExceptionChecker implements
		LoadBalanceExceptionChecker {

	private List sqlStateList;
	private List sqlExClassList;

	public boolean shouldExceptionTriggerFailover(SQLException ex) {
		String sqlState = ex.getSQLState();

		if (sqlState != null) {
			if (sqlState.startsWith("08")) {
				// connection error
				return true;
			}
			if(this.sqlStateList != null){
				// check against SQLState list
				for(Iterator i = sqlStateList.iterator(); i.hasNext(); ){
					if(sqlState.startsWith(i.next().toString())){
						return true;
					}
				}
			}
		}

		// always handle CommunicationException
		if(ex instanceof CommunicationsException){
			return true;
		}
		if(this.sqlExClassList != null){
			// check against configured class lists
			for(Iterator i = sqlExClassList.iterator(); i.hasNext(); ){
				if(((Class)i.next()).isInstance(ex)){
					return true;
				}
			}
		}
		// no matches
		return false;

	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void init(Connection conn, Properties props) throws SQLException {
		configureSQLStateList(props.getProperty("loadBalanceSQLStateFailover", null));
		configureSQLExceptionSubclassList(props.getProperty("loadBalanceSQLExceptionSubclassFailover", null));

	}

	private void configureSQLStateList(String sqlStates){
		if(sqlStates == null || "".equals(sqlStates)){
			return;
		}
		List states = StringUtils.split(sqlStates, ",", true);
		List newStates = new ArrayList();
		Iterator i = states.iterator();

		while(i.hasNext()){
			String state = i.next().toString();
			if(state.length() > 0){
				newStates.add(state);
			}
		}
		if(newStates.size() > 0){
			this.sqlStateList = newStates;
		}

	}
	private void configureSQLExceptionSubclassList(String sqlExClasses){
		if(sqlExClasses == null || "".equals(sqlExClasses)){
			return;
		}
		List classes = StringUtils.split(sqlExClasses, ",", true);
		List newClasses = new ArrayList();
		Iterator i = classes.iterator();

		while(i.hasNext()){
			String exClass = i.next().toString();
			try{
				Class c = Class.forName(exClass);
				newClasses.add(c);
			} catch (Exception e){
				// ignore and don't check, class doesn't exist
			}
		}
		if(newClasses.size() > 0){
			this.sqlExClassList = newClasses;
		}

	}

}


text:
package org.apache.log4j.scheduler;

import java.util.List;
import java.util.Vector;

/**
 * A simple but still useful implementation of a Scheduler (in memory only).
 *

 * This implementation will work very well when the number of scheduled job is
 * small, say less than 100 jobs. If a larger number of events need to be
 * scheduled, than a better adapted data structure for the jobList can give
 * improved performance.
 *
 * @author Ceki
 */
public class Scheduler extends Thread {

    /**
     * Job list.
     */
    List jobList;
    /**
     * If set true, scheduler has or should shut down.
     */
    boolean shutdown = false;

    /**
     * Create new instance.
     */
    public Scheduler() {
        super();
        jobList = new Vector();
    }

    /**
     * Find the index of a given job.
     * @param job job
     * @return -1 if the job could not be found.
     */
    int findIndex(final Job job) {
        int size = jobList.size();
        boolean found = false;

        int i = 0;
        for (; i < size; i++) {
            ScheduledJobEntry se = (ScheduledJobEntry) jobList.get(i);
            if (se.job == job) {
                found = true;
                break;
            }
        }
        if (found) {
            return i;
        } else {
            return -1;
        }
    }

    /**
     * Delete the given job.
     * @param job job.
     * @return true if the job could be deleted, and
     * false if the job could not be found or if the Scheduler is about to
     * shutdown in which case deletions are not permitted.
     */
    public synchronized boolean delete(final Job job) {
        // if already shutdown in the process of shutdown, there is no
        // need to remove Jobs as they will never be executed.
        if (shutdown) {
            return false;
        }
        int i = findIndex(job);
        if (i != -1) {
            ScheduledJobEntry se = (ScheduledJobEntry) jobList.remove(i);
            if (se.job != job) { // this should never happen
                new IllegalStateException("Internal programming error");
            }
            // if the job is the first on the list,
            // then notify the scheduler thread to schedule a new job
            if (i == 0) {
                this.notifyAll();
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * Schedule a {@link Job} for execution at system time given by
     * the desiredTime parameter.
     * @param job job to schedule.
     * @param desiredTime desired time of execution.
     */
    public synchronized void schedule(final Job job,
                                      final long desiredTime) {
        schedule(new ScheduledJobEntry(job, desiredTime));
    }

    /**
     * Schedule a {@link Job} for execution at system time given by
     * the desiredTime parameter.
     *

     * The job will be rescheduled. It will execute with a frequency determined
     * by the period parameter.
     * @param job job to schedule.
     * @param desiredTime desired time of execution.
     * @param period repeat period.
     */
    public synchronized void schedule(final Job job,
                                      final long desiredTime,
                                      final long period) {
        schedule(new ScheduledJobEntry(job, desiredTime, period));
    }

    /**
     * Change the period of a job. The original job must exist for its period
     * to be changed.
     *

     * The method returns true if the period could be changed, and false
     * otherwise.
     * @param job job.
     * @param newPeriod new repeat period.
     * @return true if period could be changed.
     */
    public synchronized boolean changePeriod(final Job job,
                                             final long newPeriod) {
        if (newPeriod <= 0) {
            throw new IllegalArgumentException(
                    "Period must be an integer langer than zero");
        }

        int i = findIndex(job);
        if (i == -1) {
            return false;
        } else {
            ScheduledJobEntry se = (ScheduledJobEntry) jobList.get(i);
            se.period = newPeriod;
            return true;
        }
    }

    /**
     * Schedule a job.
     * @param newSJE new job entry.
     */
    private synchronized void schedule(final ScheduledJobEntry newSJE) {
        // disallow new jobs after shutdown
        if (shutdown) {
            return;
        }
        int max = jobList.size();
        long desiredExecutionTime = newSJE.desiredExecutionTime;

        // find the index i such that timeInMillis < jobList[i]
        int i = 0;
        for (; i < max; i++) {

            ScheduledJobEntry sje = (ScheduledJobEntry) jobList.get(i);

            if (desiredExecutionTime < sje.desiredExecutionTime) {
                break;
            }
        }
        jobList.add(i, newSJE);
        // if the jobList was empty, then notify the scheduler thread
        if (i == 0) {
            this.notifyAll();
        }
    }

    /**
     * Shut down scheduler.
     */
    public synchronized void shutdown() {
        shutdown = true;
    }

    /**
     * Run scheduler.
     */
    public synchronized void run() {
        while (!shutdown) {
            if (jobList.isEmpty()) {
                linger();
            } else {
                ScheduledJobEntry sje = (ScheduledJobEntry) jobList.get(0);
                long now = System.currentTimeMillis();
                if (now >= sje.desiredExecutionTime) {
                    executeInABox(sje.job);
                    jobList.remove(0);
                    if (sje.period > 0) {
                        sje.desiredExecutionTime = now + sje.period;
                        schedule(sje);
                    }
                } else {
                    linger(sje.desiredExecutionTime - now);
                }
            }
        }
        // clear out the job list to facilitate garbage collection
        jobList.clear();
        jobList = null;
        System.out.println("Leaving scheduler run method");
    }

    /**
     * We do not want a single failure to affect the whole scheduler.
     * @param job job to execute.
     */
    void executeInABox(final Job job) {
        try {
            job.execute();
        } catch (Exception e) {
            System.err.println("The execution of the job threw an exception");
            e.printStackTrace(System.err);
        }
    }

    /**
     * Wait for notification.
     */
    void linger() {
        try {
            while (jobList.isEmpty() && !shutdown) {
                this.wait();
            }
        } catch (InterruptedException ie) {
            shutdown = true;
        }
    }

    /**
     * Wait for notification or time to elapse.
     * @param timeToLinger time to linger.
     */
    void linger(final long timeToLinger) {
        try {
            this.wait(timeToLinger);
        } catch (InterruptedException ie) {
            shutdown = true;
        }
    }

    /**
     * Represents an entry in job scheduler.
     */
    static final class ScheduledJobEntry {
        /**
         * Desired execution time.
         */
        long desiredExecutionTime;
        /**
         * Job to run.
         */
        Job job;
        /**
         * Repeat period.
         */
        long period = 0;

        /**
         * Create new instance.
         * @param job job
         * @param desiredTime desired time.
         */
        ScheduledJobEntry(final Job job, final long desiredTime) {
            this(job, desiredTime, 0);
        }

        /**
         * Create new instance.
         * @param job job
         * @param desiredTime desired time
         * @param period repeat period
         */
        ScheduledJobEntry(final Job job,
                          final long desiredTime,
                          final long period) {
            super();
            this.desiredExecutionTime = desiredTime;
            this.job = job;
            this.period = period;
        }
    }

}


text:
import Ember from 'ember';
import DS from 'ember-data';
import toPromise from '../utils/to-promise';
import forEach from 'lodash/collection/forEach';
import filter from 'lodash/collection/filter';
import map from 'lodash/collection/map';
import includes from 'lodash/collection/includes';
import indexOf from 'lodash/array/indexOf';
import find from 'lodash/collection/find';

var fmt = Ember.String.fmt;
var Promise = Ember.RSVP.Promise;

var uniq = function (arr) {
  var ret = Ember.A();

  arr.forEach(function(k) {
    if (indexOf(ret, k) < 0) {
      ret.push(k);
    }
  });

  return ret;
};

/**
  The Firebase adapter allows your store to communicate with the Firebase
  realtime service. To use the adapter in your app, extend DS.FirebaseAdapter
  and customize the endpoint to point to the Firebase URL where you want this
  data to be stored.

  The adapter will automatically communicate with Firebase to persist your
  records as neccessary. Importantly, the adapter will also update the store
  in realtime when changes are made to the Firebase by other clients or
  otherwise.
*/
export default DS.Adapter.extend(Ember.Evented, {

  defaultSerializer: '-firebase',

  /**
    Endpoint paths can be customized by setting the Firebase property on the
    adapter:

    ```js
    DS.FirebaseAdapter.extend({
      firebase: new Firebase('https://<my-firebase>.firebaseio.com/')
    });
    ```

    Requests for `App.Post` now target `https://<my-firebase>.firebaseio.com/posts`.

    @property firebase
    @type {Firebase}
  */

  init: function() {
    var firebase = this.get('firebase');
    if (!firebase || typeof firebase !== 'object') {
      throw new Error('Please set the `firebase` property on the adapter.');
    }
    // If provided Firebase reference was a query (eg: limits), make it a ref.
    this._ref = firebase.ref();
    // Keep track of what types `.findAll()` has been called for
    this._findAllMapForType = {};
    // Keep a cache to check modified relationships against
    this._recordCacheForType = {};
    // Used to batch records into the store
    this._queue = [];
  },

  /**
    Uses push() to generate chronologically ordered unique IDs.
  */
  generateIdForRecord: function() {
    return this._getKey(this._ref.push());
  },

  /**
    Use the Firebase DataSnapshot's key as the record id

    @param {Object} snapshot - A Firebase snapshot
    @param {Object} payload - The payload that will be pushed into the store
    @return {Object} payload
  */
  _assignIdToPayload: function(snapshot) {
    var payload = snapshot.val();
    if (payload !== null && typeof payload === 'object' && typeof payload.id === 'undefined') {
      payload.id = this._getKey(snapshot);
    }
    return payload;
  },

  /**
    Called by the store to retrieve the JSON for a given type and ID. The
    method will return a promise which will resolve when the value is
    successfully fetched from Firebase.

    Additionally, from this point on, the object's value in the store will
    also be automatically updated whenever the remote value changes.
  */
  findRecord: function(store, typeClass, id) {
    var adapter = this;
    var ref = this._getCollectionRef(typeClass, id);

    return new Promise(function(resolve, reject) {
      ref.once('value', function(snapshot) {
        var payload = adapter._assignIdToPayload(snapshot);
        adapter._updateRecordCacheForType(typeClass, payload);
        if (payload === null) {
          var error = new Error(fmt('no record was found at %@', [ref.toString()]));
              error.recordId = id;
          reject(error);
        }
        else {
          resolve(payload);
        }
      },
      function(err) {
        reject(err);
      });
    }, fmt('DS: FirebaseAdapter#findRecord %@ to %@', [typeClass.modelName, ref.toString()]));
  },

  recordWasPushed: function(store, modelName, record) {
    if (!record.__listening) {
      var typeClass = store.modelFor(modelName);
      this.listenForChanges(store, typeClass, record);
    }
  },

  recordWillUnload: function(store, record) {
    if (record.__listening) {
      this.stopListening(store, record.constructor, record);
    }
  },

  recordWillDelete: function(store, record) {
    var adapter = this;

    record.eachRelationship(function (key, relationship) {
      if (relationship.kind === 'belongsTo') {
        var parentRecord = record.get(relationship.key);
        var inverseKey = record.inverseFor(relationship.key);
        if (inverseKey && parentRecord.get('id')) {
          var parentRef = adapter._getCollectionRef(inverseKey.type, parentRecord.get('id'));
          adapter._removeHasManyRecord(store, parentRef, inverseKey.name, record.id);
        }
      }
    });
  },

  listenForChanges: function(store, typeClass, record) {
    // embedded records will get their changes from parent listeners
    if (!this.isRecordEmbedded(record)) {
      record.__listening = true;
      var adapter = this;
      var ref = this._getCollectionRef(typeClass, record.id);
      var called = false;
      ref.on('value', function FirebaseAdapter$changeListener(snapshot) {
        if (called) {
          adapter._handleChildValue(store, typeClass, snapshot);
        }
        called = true;
      });
    }
  },

  stopListening: function (store, typeClass, record) {
    if (record.__listening) {
      var ref = this._getCollectionRef(typeClass, record.id);
      ref.off('value');
      record.__listening = false;
    }
  },

  /**
   findMany
  */
  findMany: undefined,

  /**
    Called by the store to retrieve the JSON for all of the records for a
    given type. The method will return a promise which will resolve when the
    value is successfully fetched from Firebase.

    Additionally, from this point on, any records of this type that are added,
    removed or modified from Firebase will automatically be reflected in the
    store.
  */
  findAll: function(store, typeClass) {
    var adapter = this;
    var ref = this._getCollectionRef(typeClass);

    return new Promise(function(resolve, reject) {
      // Listen for child events on the type
      ref.once('value', function(snapshot) {
        if (!adapter._findAllHasEventsForType(typeClass)) {
          adapter._findAllAddEventListeners(store, typeClass, ref);
        }
        var results = [];
        snapshot.forEach(function(childSnapshot) {
          var payload = adapter._assignIdToPayload(childSnapshot);
          adapter._updateRecordCacheForType(typeClass, payload);
          results.push(payload);
        });
        resolve(results);
      }, function(error) {
        reject(error);
      });
    }, fmt('DS: FirebaseAdapter#findAll %@ to %@', [typeClass.modelName, ref.toString()]));
  },

  query: function(store, typeClass, query, recordArray) {
    var adapter = this;
    var ref = this._getCollectionRef(typeClass);
    var modelName = typeClass.modelName;

    ref = this.applyQueryToRef(ref, query);

    ref.on('child_added', function(snapshot) {
      var record = store.peekRecord(modelName, snapshot.key());

      if (!record || !record.__listening) {
        var payload = adapter._assignIdToPayload(snapshot);
        var normalizedData = store.normalize(typeClass.modelName, payload);
        adapter._updateRecordCacheForType(typeClass, payload);
        record = store.push(normalizedData);
      }

      if (record) {
        recordArray.get('content').addObject(record._internalModel);
      }
    });

    // `child_changed` is already handled by the record's
    // value listener after a store.push. `child_moved` is
    // a much less common case because it relates to priority

    ref.on('child_removed', function(snapshot) {
      var record = store.peekRecord(modelName, snapshot.key());
      if (record) {
        recordArray.get('content').removeObject(record._internalModel);
      }
    });

    // clean up event handlers when the array is being destroyed
    // so that future firebase events wont keep trying to use a
    // destroyed store/serializer
    recordArray.__firebaseCleanup = function () {
      ref.off('child_added');
      ref.off('child_removed');
    };

    return new Promise(function(resolve, reject) {
      // Listen for child events on the type
      ref.once('value', function(snapshot) {
        if (!adapter._findAllHasEventsForType(typeClass)) {
          adapter._findAllAddEventListeners(store, typeClass, ref);
        }
        var results = [];
        snapshot.forEach(function(childSnapshot) {
          var payload = adapter._assignIdToPayload(childSnapshot);
          adapter._updateRecordCacheForType(typeClass, payload);
          results.push(payload);
        });
        resolve(results);
      }, function(error) {
        reject(error);
      });
    }, fmt('DS: FirebaseAdapter#query %@ with %@', [modelName, query]));
  },

  applyQueryToRef: function (ref, query) {

    if (!query.orderBy) {
      query.orderBy = '_key';
    }

    if (query.orderBy === '_key'){
      ref = ref.orderByKey();
    } else if (query.orderBy === '_value') {
      ref = ref.orderByValue();
    } else if (query.orderBy === '_priority') {
      ref = ref.orderByPriority();
    } else {
      ref = ref.orderByChild(query.orderBy);
    }

    ['limitToFirst', 'limitToLast', 'startAt', 'endAt', 'equalTo'].forEach(function (key) {
      if (query[key] || query[key] === '') {
        ref = ref[key](query[key]);
      }
    });

    return ref;
  },

  /**
    Keep track of what types `.findAll()` has been called for
    so duplicate listeners aren't added
  */
  _findAllMapForType: undefined,

  /**
    Determine if the current type is already listening for children events
  */
  _findAllHasEventsForType: function(typeClass) {
    return !Ember.isNone(this._findAllMapForType[typeClass.modelName]);
  },

  /**
    After `.findAll()` is called on a modelName, continue to listen for
    `child_added`, `child_removed`, and `child_changed`
  */
  _findAllAddEventListeners: function(store, typeClass, ref) {
    var modelName = typeClass.modelName;
    this._findAllMapForType[modelName] = true;

    var adapter = this;
    ref.on('child_added', function(snapshot) {
      if (!store.hasRecordForId(modelName, adapter._getKey(snapshot))) {
        adapter._handleChildValue(store, typeClass, snapshot);
      }
    });
  },

  /**
    Push a new child record into the store
  */
  _handleChildValue: function(store, typeClass, snapshot) {
    // No idea why we need this, we are already turning off the callback by
    // calling ref.off in recordWillUnload. Something is fishy here
    if (store.isDestroying) {
      return;
    }
    var value = snapshot.val();
    if (value === null) {
      var id = this._getKey(snapshot);
      var record = store.peekRecord(typeClass.modelName, id);
      // TODO: refactor using ED
      if (!record.get('isDeleted')) {
        record.deleteRecord();
      }
    } else {
      var payload = this._assignIdToPayload(snapshot);

      this._enqueue(function FirebaseAdapter$enqueueStorePush() {
        if (!store.isDestroying) {
          var normalizedData = store.normalize(typeClass.modelName, payload);
          store.push(normalizedData);
        }
      });
    }
  },

  /**
    `createRecord` is an alias for `updateRecord` because calling \
    `ref.set()` would wipe out any existing relationships
  */
  createRecord: function(store, typeClass, snapshot) {
    var adapter = this;
    return this.updateRecord(store, typeClass, snapshot).then(function() {
      adapter.listenForChanges(store, typeClass, snapshot.record);
    });
  },

  /**
    Called by the store when a record is created/updated via the `save`
    method on a model record instance.

    The `updateRecord` method serializes the record and performs an `update()`
    at the the Firebase location and a `.set()` at any relationship locations
    The method will return a promise which will be resolved when the data and
    any relationships have been successfully saved to Firebase.

    We take an optional record reference, in order for this method to be usable
    for saving nested records as well.

  */
  updateRecord: function(store, typeClass, snapshot) {
    var adapter = this;
    var recordRef = this._getAbsoluteRef(snapshot.record);
    var recordCache = adapter._getRecordCache(typeClass, snapshot.id);

    var pathPieces = recordRef.path.toString().split('/');
    var lastPiece = pathPieces[pathPieces.length-1];
    var serializedRecord = snapshot.serialize({
      includeId: (lastPiece !== snapshot.id) // record has no firebase `key` in path
    });

    return new Promise(function(resolve, reject) {
      var savedRelationships = Ember.A();
      snapshot.record.eachRelationship(function(key, relationship) {
        var save;
        if (relationship.kind === 'hasMany') {
          if (serializedRecord[key]) {
            save = adapter._saveHasManyRelationship(store, typeClass, relationship, serializedRecord[key], recordRef, recordCache);
            savedRelationships.push(save);
            // Remove the relationship from the serializedRecord because otherwise we would clobber the entire hasMany
            delete serializedRecord[key];
          }
        } else {
          if (adapter.isRelationshipEmbedded(store, typeClass.modelName, relationship) && serializedRecord[key]) {
            save = adapter._saveEmbeddedBelongsToRecord(store, typeClass, relationship, serializedRecord[key], recordRef);
            savedRelationships.push(save);
            delete serializedRecord[key];
          }
        }
      });

      var relationshipsPromise = Ember.RSVP.allSettled(savedRelationships);
      var recordPromise = adapter._updateRecord(recordRef, serializedRecord);

      Ember.RSVP.hashSettled({relationships: relationshipsPromise, record: recordPromise}).then(function(promises) {
        var rejected = Ember.A(promises.relationships.value).filterBy('state', 'rejected');
        if (promises.record.state === 'rejected') {
          rejected.push(promises.record);
        }
        // Throw an error if any of the relationships failed to save
        if (rejected.length !== 0) {
          var error = new Error(fmt('Some errors were encountered while saving %@ %@', [typeClass, snapshot.id]));
              error.errors = rejected.mapBy('reason');
          reject(error);
        } else {
          resolve();
        }
      });
    }, fmt('DS: FirebaseAdapter#updateRecord %@ to %@', [typeClass, recordRef.toString()]));
  },

  //Just update the record itself without caring for the relationships
  _updateRecord: function(recordRef, serializedRecord) {
    return toPromise(recordRef.update, recordRef, [serializedRecord]);
  },

  /**
    Call _saveHasManyRelationshipRecord on each record in the relationship
    and then resolve once they have all settled
  */
  _saveHasManyRelationship: function(store, typeClass, relationship, ids, recordRef, recordCache) {
    if (!Ember.isArray(ids)) {
      throw new Error('hasMany relationships must must be an array');
    }
    var adapter = this;
    var idsCache = Ember.A(recordCache[relationship.key]);
    var dirtyRecords = [];

    // Added
    var addedRecords = filter(ids, function(id) {
      return !idsCache.contains(id);
    });

    // Dirty
    dirtyRecords = filter(ids, function(id) {
      var relatedModelName = relationship.type;
      return store.hasRecordForId(relatedModelName, id) && store.peekRecord(relatedModelName, id).get('hasDirtyAttributes') === true;
    });

    dirtyRecords = map(uniq(dirtyRecords.concat(addedRecords)), function(id) {
      return adapter._saveHasManyRecord(store, typeClass, relationship, recordRef, id);
    });

    // Removed
    var removedRecords = filter(idsCache, function(id) {
      return !includes(ids, id);
    });

    removedRecords = map(removedRecords, function(id) {
      return adapter._removeHasManyRecord(store, recordRef, relationship.key, id);
    });
    // Combine all the saved records
    var savedRecords = dirtyRecords.concat(removedRecords);
    // Wait for all the updates to finish
    return Ember.RSVP.allSettled(savedRecords).then(function(savedRecords) {
      var rejected = Ember.A(Ember.A(savedRecords).filterBy('state', 'rejected'));
      if (rejected.get('length') === 0) {
        // Update the cache
        recordCache[relationship.key] = ids;
        return savedRecords;
      }
      else {
        var error = new Error(fmt('Some errors were encountered while saving a hasMany relationship %@ -> %@', [relationship.parentType, relationship.type]));
            error.errors = Ember.A(rejected).mapBy('reason');
        throw error;
      }
    });
  },

  /**
    If the relationship is `async: true`, create a child ref
    named with the record id and set the value to true

    If the relationship is `embedded: true`, create a child ref
    named with the record id and update the value to the serialized
    version of the record
  */
  _saveHasManyRecord: function(store, typeClass, relationship, parentRef, id) {
    var ref = this._getRelationshipRef(parentRef, relationship.key, id);
    var record = store.peekRecord(relationship.type, id);
    var isEmbedded = this.isRelationshipEmbedded(store, typeClass.modelName, relationship);
    if (isEmbedded) {
      return record.save();
    }

    return toPromise(ref.set, ref,  [true]);
  },

  /**
   * Determine from the serializer if the relationship is embedded via the
   * serializer's `attrs` hash.
   *
   * @return {Boolean}              Is the relationship embedded?
   */
  isRelationshipEmbedded(store, modelName, relationship) {
    var serializer = store.serializerFor(modelName);
    return serializer.hasDeserializeRecordsOption(relationship.key);
  },

  /**
   * Determine from if the record is embedded via implicit relationships.
   *
   * @return {Boolean}              Is the relationship embedded?
   */
  isRecordEmbedded(record) {
    if (record._internalModel) {
      record = record._internalModel;
    }

    var found = this.getFirstEmbeddingParent(record);

    return !!found;
  },

  /**
    Remove a relationship
  */
  _removeHasManyRecord: function(store, parentRef, key, id) {
    var ref = this._getRelationshipRef(parentRef, key, id);
    return toPromise(ref.remove, ref, [], ref.toString());
  },

  /**
   * Save an embedded belongsTo record and set its internal firebase ref
   *
   * @return {Promise<DS.Model>}
   */
  _saveEmbeddedBelongsToRecord: function(store, typeClass, relationship, id, parentRef) {
    var record = store.peekRecord(relationship.type, id);
    if (record) {
      return record.save();
    }
    return Ember.RSVP.Promise.reject(new Error(`Unable to find record with id ${id} from embedded relationship: ${JSON.stringify(relationship)}`));
  },

  /**
    Called by the store when a record is deleted.
  */
  deleteRecord: function(store, typeClass, snapshot) {
    var ref = this._getAbsoluteRef(snapshot.record);
    return toPromise(ref.remove, ref);
  },

  /**
    Determines a path fo a given type
  */
  pathForType: function(modelName) {
    var camelized = Ember.String.camelize(modelName);
    return Ember.String.pluralize(camelized);
  },

  /**
    Return a Firebase reference for a given modelName and optional ID.
  */
  _getCollectionRef: function(typeClass, id) {
    var ref = this._ref;
    if (typeClass) {
      ref = ref.child(this.pathForType(typeClass.modelName));
    }
    if (id) {
      ref = ref.child(id);
    }
    return ref;
  },

  /**
   * Returns a Firebase reference for a record taking into account if the record is embedded
   *
   * @param  {DS.Model} record
   * @return {Firebase}
   */
  _getAbsoluteRef: function(record) {
    if (record._internalModel) {
      record = record._internalModel;
    }

    var embeddingParent = this.getFirstEmbeddingParent(record);

    if (embeddingParent) {
      var { record: parent, relationship } = embeddingParent;
      var recordRef = this._getAbsoluteRef(parent).child(relationship.key);

      if (relationship.kind === 'hasMany') {
        recordRef = recordRef.child(record.id);
      }
      return recordRef;
    }

    return this._getCollectionRef(record.type, record.id);
  },

  /**
   * Returns the parent record and relationship where any embedding is detected
   *
   * @param  {DS.InternalModel} internalModel
   * @return {Object}
   */
  getFirstEmbeddingParent(internalModel) {
    var embeddingParentRel = find(internalModel._implicitRelationships, (implicitRel) => {
      var members = implicitRel.members.toArray();
      var parent = members[0];

      if (!parent) {
        return false;
      }

      var parentRel = parent._relationships.get(implicitRel.inverseKey);
      return this.isRelationshipEmbedded(this.store, parent.type.modelName, parentRel.relationshipMeta);
    });

    if (embeddingParentRel) {
      var parent = embeddingParentRel.members.toArray()[0];
      var parentKey = embeddingParentRel.inverseKey;
      var parentRel = parent._relationships.get(parentKey).relationshipMeta;
      return { record: parent, relationship: parentRel };
    }
  },

  /**
    Return a Firebase reference based on a relationship key and record id
  */
  _getRelationshipRef: function(ref, key, id) {
    return ref.child(key).child(id);
  },

  /**
    The amount of time (ms) before the _queue is flushed
  */
  _queueFlushDelay: (1000/60), // 60fps

  /**
    Called after the first item is pushed into the _queue
  */
  _queueScheduleFlush: function() {
    Ember.run.later(this, this._queueFlush, this._queueFlushDelay);
  },

  /**
    Call each function in the _queue and the reset the _queue
  */
  _queueFlush: function() {
    forEach(this._queue, function FirebaseAdapter$flushQueueItem(queueItem) {
      var fn = queueItem[0];
      var args = queueItem[1];
      fn.apply(null, args);
    });
    this._queue.length = 0;
  },

  /**
    Push a new function into the _queue and then schedule a
    flush if the item is the first to be pushed
  */
  _enqueue: function(callback, args) {
    //Only do the queueing if we scheduled a delay
    if (this._queueFlushDelay) {
      var length = this._queue.push([callback, args]);
      if (length === 1) {
        this._queueScheduleFlush();
      }
    } else {
      callback.apply(null, args);
    }
  },

  /**
    A cache of hasMany relationships that can be used to
    diff against new relationships when a model is saved
  */
  _recordCacheForType: undefined,

  /**
    _updateHasManyCacheForType
  */
  _updateRecordCacheForType: function(typeClass, payload) {
    if (!payload) { return; }
    var id = payload.id;
    var cache = this._getRecordCache(typeClass, id);
    // Only cache relationships for now
    typeClass.eachRelationship(function(key, relationship) {
      if (relationship.kind === 'hasMany') {
        var ids = payload[key];
        cache[key] = !Ember.isNone(ids) ? Ember.A(Object.keys(ids)) : Ember.A();
      }
    });
  },

  /**
    Get or create the cache for a record
   */
  _getRecordCache: function (typeClass, id) {
    var modelName = typeClass.modelName;
    var cache = this._recordCacheForType;
    cache[modelName] = cache[modelName] || {};
    cache[modelName][id] = cache[modelName][id] || {};
    return cache[modelName][id];
  },

  /**
   * A utility for retrieving the key name of a Firebase ref or
   * DataSnapshot. This is backwards-compatible with `name()`
   * from Firebase 1.x.x and `key()` from Firebase 2.0.0+. Once
   * support for Firebase 1.x.x is dropped in EmberFire, this
   * helper can be removed.
   */
  _getKey: function(refOrSnapshot) {
    return (typeof refOrSnapshot.key === 'function') ? refOrSnapshot.key() : refOrSnapshot.name();
  },

  /**
   * We don't need background reloading, because firebase!
   */
  shouldBackgroundReloadRecord: function() {
    return false;
  },
  shouldReloadAll: function() {
    return false;
  },
});


text:
<?php
class DeletarUsuario{
	public function deletar($id){
        // Exclui do rank primeiro
        $this->deletarRank($id);
        // Exclui os testes feitos pelo usuário
        $this->deletarTestes($id);
		// Excluindo usuario do banco
		return $result = Db::queryCount("DELETE FROM login WHERE log_id=?", array($id));
	}

    private function deletarRank($id){
        $result = Db::queryCount("DELETE FROM rank WHERE rank_log_id=?", array($id));
        return $result;
    }

    private function deletarTestes($id){
        $result = Db::queryCount("DELETE FROM teste WHERE test_log_id=?", array($id));
    }
}
?>


text:
Locker - the "me" platform [![Build Status](https://secure.travis-ci.org/LockerProject/Locker.png)](http://travis-ci.org/LockerProject/Locker)
======================

This is an open source project that helps me collect all of my personal data, from wherever it is, into one place, and then lets me do really awesome stuff with it.

[Background Video](http://www.youtube.com/watch?v=pTNO5npNq28)

STATUS: eager-developer-friendly only at this point, we're working hard to make it usable for early adopters very soon, keep an eye on [@lockerproject](http://twitter.com/lockerproject) and [@jeremie](http://twitter.com/jeremie) for progress, and come hang out with us on freenode IRC in [#lockerproject](http://webchat.freenode.net/?channels=lockerproject).

We also have a [mailing list](http://bit.ly/singly-dev-list) setup.  Join and say hello!

## Getting Started

### The Fast Way

Lockerbox (by [pib](https://www.github.com/pib)) is a straightforward way to get all the high-level dependencies installed at once. It will make a single directory called lockerbox and get everything set up inside of there.

    curl https://raw.github.com/LockerProject/lockerbox/master/lockerbox.sh > lockerbox.sh
    chmod 0755 lockerbox.sh
    ./lockerbox.sh

When that successfully completes, add lockerbox/local/bin to your path:

    echo 'export PATH=$PATH:'`pwd`/lockerbox/local/bin >> ~/.profile
    source ~/.profile

Then:

    cd lockerbox/Locker
    make
    ./locker

now open [http://localhost:8042/](http://localhost:8042/) in your browser!

### The Detailed Way

If you encounter errors in "the fast way", or if you want to go through the process of setting everything up manually, check out the [detailed set up instructions](https://github.com/LockerProject/Locker/wiki/Detailed-Set-Up-Instructions).

## What are these things? ##

* **Connectors** - A service that knows how to connect to and sync data with a place where I have data about myself, such as an account on a site or service, or in some desktop app, on my phone, or even from a device.
* **Collections** - My data from the many different sources gets organized into common collections, such as places, contacts, messages, statuses, links, etc.
* **Apps** - Once my data is in my locker I need apps that do useful or fun things for me, with the ability to control where my data goes and not have to give up access to my online accounts.

Once I "install" them in my locker (giving them some working space, a local port, and some config), I can browse to them where they provide their own instructions/steps (for now, it's early yet and pretty manual).  To learn a bit more about the innards, I can install and run the Dev Docs app. :)

We need *TONS* of help and it's welcomed across the board, particularly in adding and advancing more of the connectors, just don a hard-hat and dig in, all patches welcomed, personal data FTW!

**I am the platform.**


text:
import _ from 'underscore';
import util from 'util';
import path from 'path';
import assert from 'assert';
import chalk from 'chalk';
import semver from 'semver';

import isopackets from '../tool-env/isopackets.js';
import files from '../fs/files.js';
import utils from '../utils/utils.js';
import { Console } from '../console/console.js';
import buildmessage from '../utils/buildmessage.js';
import main from '../cli/main.js';
import httpHelpers from '../utils/http-helpers.js';
import { execFileSync, execFileAsync } from '../utils/processes.js';

import './protect-string-proto.js'; // must always come before 'cordova-lib'
import { cordova as cordova_lib, events as cordova_events, CordovaError }
  from 'cordova-lib';
import cordova_util from 'cordova-lib/src/cordova/util.js';
import superspawn from 'cordova-lib/src/cordova/superspawn.js';
import PluginInfoProvider from 'cordova-lib/src/PluginInfoProvider.js';

import { AVAILABLE_PLATFORMS, displayNameForPlatform, displayNamesForPlatforms,
  newPluginId, convertPluginVersions, convertToGitUrl,
  installationInstructionsUrlForPlatform } from './index.js';
import { CordovaBuilder } from './builder.js';

cordova_events.on('results', logIfVerbose);
cordova_events.on('log', logIfVerbose);
cordova_events.on('warn', log);

function logIfVerbose(...args) {
  if (Console.verbose) {
    log(...args);
  }
};

function log(...args) {
  Console.rawInfo(`%% ${util.format.apply(null, args)}\n`);
}

export class CordovaProject {
  constructor(projectContext, options = {}) {
    if (process.platform === 'win32') {
      Console.warn(`Building mobile apps on a Windows system is not \
yet supported.`);
      throw new main.ExitWithCode(1);
    }

    this.projectContext = projectContext;

    this.projectRoot = projectContext.getProjectLocalDirectory('cordova-build');
    this.options = options;

    this.pluginsDir = files.pathJoin(this.projectRoot, 'plugins');

    this.createIfNeeded();
  }

  createIfNeeded() {
    buildmessage.assertInJob();

    // Check if we have an existing Cordova project directory with outdated
    // platforms. In that case, we remove the whole directory to avoid issues.
    if (files.exists(this.projectRoot)) {
      const installedPlatforms = this.listInstalledPlatforms();

      // XXX Decide whether to update these if we update cordova-lib.
      // If we can guarantee there are no issues going forward, we may want to
      // use updatePlatforms instead of removing the whole directory.
      const minPlatformVersions = {
        'android': '4.1.0',
        'ios': '3.9.0'
      }

      const outdated = _.some(minPlatformVersions, (minVersion, platform) => {
        // If the platform is not installed, it cannot be outdated
        if (!_.contains(installedPlatforms, platform)) return false;

        const installedVersion = this.installedVersionForPlatform(platform);
        // If we cannot establish the installed version, we consider it outdated
        if (!installedVersion) return true;

        return semver.lt(installedVersion, minVersion);
      });

      if (outdated) {
        Console.debug(`Removing Cordova project directory to avoid issues with
outdated platforms`);
        // Remove Cordova project directory to start afresh
        // and avoid a broken project
        files.rm_recursive(this.projectRoot);
      }
    }

    if (!files.exists(this.projectRoot)) {
      // We create a temporary directory with a generated config.xml
      // to use as a template for creating the Cordova project
      // This way, we are not dependent on the contents of
      // cordova-app-hello-world but we base our initial project state on
      // our own defaults and optionally a mobile-config.js

      const templatePath = files.mkdtemp('cordova-template-');

      // If we don't create an empty hooks directory, cordova-lib will attempt
      // to install one from a hardcoded path to cordova-app-hello-world
      files.mkdir_p(files.pathJoin(templatePath, 'hooks'));

      // If we don't create an empty www directory, cordova-lib will get
      // confused
      files.mkdir_p(files.pathJoin(templatePath, 'www'));

      const builder = new CordovaBuilder(this.projectContext, templatePath,
        { mobileServerUrl, settingsFile } = this.options);

      builder.processControlFile();

      if (buildmessage.jobHasMessages()) return;

      // Don't copy resources (they will be copied as part of the prepare)
      builder.writeConfigXmlAndCopyResources(false);

      // Create the Cordova project root directory
      files.mkdir_p(files.pathDirname(this.projectRoot));

      const config = { lib:
        { www: { url: files.convertToOSPath(templatePath) } } };

      // Don't set cwd to project root in runCommands because it doesn't
      // exist yet
      this.runCommands('creating Cordova project', async () => {
        // No need to pass in appName and appId because these are set from
        // the generated config.xml
        await cordova_lib.raw.create(files.convertToOSPath(this.projectRoot),
          undefined, undefined, config);
      }, undefined, null);
    }
  }

  // Preparing

  prepareFromAppBundle(bundlePath, pluginVersions) {
    assert(bundlePath);
    assert(pluginVersions);

    buildmessage.assertInJob();

    Console.debug('Preparing Cordova project from app bundle');

    const builder = new CordovaBuilder(this.projectContext, this.projectRoot,
      { mobileServerUrl, settingsFile } = this.options);

    builder.processControlFile();

    if (buildmessage.jobHasMessages()) return;

    builder.writeConfigXmlAndCopyResources();
    builder.copyWWW(bundlePath);
    builder.copyBuildOverride();

    this.ensurePlatformsAreSynchronized();
    this.ensurePluginsAreSynchronized(pluginVersions,
      builder.pluginsConfiguration);
  }

  prepareForPlatform(platform) {
    assert(platform);

    const commandOptions = _.extend(this.defaultOptions,
      { platforms: [platform] });

    this.runCommands(`preparing Cordova project for platform \
${displayNameForPlatform(platform)}`, async () => {
      await cordova_lib.raw.prepare(commandOptions);
    });
  }

  // Building (includes prepare)

  buildForPlatform(platform, options = [], extraPaths) {
    assert(platform);

    const commandOptions = _.extend(this.defaultOptions,
      { platforms: [platform], options: options });

    this.runCommands(`building Cordova app for platform \
${displayNameForPlatform(platform)}`, async () => {
      await cordova_lib.raw.build(commandOptions);
    });
  }

  // Running

  async run(platform, isDevice, options = [], extraPaths) {
    options.push(isDevice ? '--device' : '--emulator');

    const env = this.defaultEnvWithPathsAdded(...extraPaths);

    const command = files.convertToOSPath(files.pathJoin(
      this.projectRoot, 'platforms', platform, 'cordova', 'run'));

    this.runCommands(`running Cordova app for platform \
${displayNameForPlatform(platform)} with options ${options}`,
    execFileAsync(command, options, {
      env: env,
      cwd: this.projectRoot,
      stdio: Console.verbose ? 'inherit' : 'pipe',
      waitForClose: false })
    ), null, null;
  }

  // Platforms

  // Checks to see if the requirements for building and running on the
  // specified Cordova platform are satisfied, printing
  // installation instructions when needed.
  checkPlatformRequirements(platform) {
    if (platform === 'ios' && process.platform !== 'darwin') {
      Console.warn("Currently, it is only possible to build iOS apps \
on an OS X system.");
      return false;
    }

    const installedPlatforms = this.listInstalledPlatforms();

    const inProject = _.contains(installedPlatforms, platform);
    if (!inProject) {
      Console.warn(`Please add the ${displayNameForPlatform(platform)} \
platform to your project first.`);
      Console.info(`Run: ${Console.command(`meteor add-platform ${platform}`)}`);
      return false;
    }

    const allRequirements = this.runCommands(`checking Cordova \
requirements for platform ${displayNameForPlatform(platform)}`,
      async () => {
        return await cordova_lib.raw.requirements([platform],
          this.defaultOptions);
      });
    let requirements = allRequirements && allRequirements[platform];
    if (!requirements) {
      Console.error(`Failed to check requirements for platform \
${displayNameForPlatform(platform)}`);
      return false;
    } else if (requirements instanceof CordovaError) {
      Console.error(`Cordova error: ${requirements.message}`);
      return false;
    }

    // We don't use ios-deploy, but open Xcode to run on a device instead
    requirements = _.reject(requirements,
      requirement => requirement.id === 'ios-deploy');

    const satisfied = _.every(requirements,
      requirement => requirement.installed);

    if (!satisfied) {
      Console.info();
      Console.info(`Your system does not yet seem to fulfill all requirements \
to build apps for ${displayNameForPlatform(platform)}.`);

      const url = installationInstructionsUrlForPlatform(platform);
      if (url) {
        Console.info();
        Console.info("Please follow the installation instructions here:");
        Console.info(Console.url(url));
      }

      Console.info();

      if (!Console.verbose) {
        Console.info("Specify the --verbose option to see more details about \
the status of individual requirements.");
        return false;
      }

      Console.info("Status of the requirements:");
      for (requirement of requirements) {
        const name = requirement.name;
        if (requirement.installed) {
          Console.success(name);
        } else {
          const reason = requirement.metadata && requirement.metadata.reason;
          if (reason) {
            Console.failInfo(`${name}: ${reason}`);
          } else {
            Console.failInfo(name);
          }
        }
      }
    }
    return satisfied;
  }

  listInstalledPlatforms() {
    return cordova_util.listPlatforms(files.convertToOSPath(this.projectRoot));
  }

  installedVersionForPlatform(platform) {
    const command = files.convertToOSPath(files.pathJoin(
      this.projectRoot, 'platforms', platform, 'cordova', 'version'));
    // Make sure the command exists before trying to execute it
    if (files.exists(command)) {
      return this.runCommands(
        `getting installed version for platform ${platform} in Cordova project`,
        execFileSync(command, {
          env: this.defaultEnvWithPathsAdded(),
          cwd: this.projectRoot}), null, null);
    } else {
      return null;
    }
  }

  updatePlatforms(platforms = this.listInstalledPlatforms()) {
    this.runCommands(`updating Cordova project for platforms \
${displayNamesForPlatforms(platforms)}`, async () => {
      await cordova_lib.raw.platform('update', platforms, this.defaultOptions);
    });
  }

  addPlatform(platform) {
    this.runCommands(`adding platform ${displayNameForPlatform(platform)} \
to Cordova project`, async () => {
      await cordova_lib.raw.platform('add', platform, this.defaultOptions);
    });
  }

  removePlatform(platform) {
    this.runCommands(`removing platform ${displayNameForPlatform(platform)} \
from Cordova project`, async () => {
      await cordova_lib.raw.platform('rm', platform, this.defaultOptions);
    });
  }

  get cordovaPlatformsInApp() {
    return this.projectContext.platformList.getCordovaPlatforms();
  }

  // Ensures that the Cordova platforms are synchronized with the app-level
  // platforms.
  ensurePlatformsAreSynchronized(platforms = this.cordovaPlatformsInApp) {
    buildmessage.assertInCapture();

    const installedPlatforms = this.listInstalledPlatforms();

    for (platform of platforms) {
      if (_.contains(installedPlatforms, platform)) continue;

      this.addPlatform(platform);
    }

    for (platform of installedPlatforms) {
      if (!_.contains(platforms, platform) &&
        _.contains(AVAILABLE_PLATFORMS, platform)) {
        this.removePlatform(platform);
      }
    }
  }

  // Plugins

  // Because PluginInfoProvider reads in the plugin versions from
  // their plugin.xml, that only gives us the declared version and doesn't
  // tell us if plugins have been fetched from a Git SHA URL or a local path.
  // So we overwrite the declared versions with versions from
  // listFetchedPluginVersions that do contain this information.
  listInstalledPluginVersions() {
    const pluginInfoProvider = new PluginInfoProvider();
    const installedPluginVersions = pluginInfoProvider.getAllWithinSearchPath(
      files.convertToOSPath(this.pluginsDir));
    const fetchedPluginVersions = this.listFetchedPluginVersions();
    return _.object(installedPluginVersions.map(pluginInfo => {
      const id = pluginInfo.id;
      const version = fetchedPluginVersions[id] || pluginInfo.version;
      return [id, version];
    }));
  }

  // There is no Cordova function to get the fetched plugin versions, so we
  // have to read in fetch.json (a file managed by plugman, a semi-independent
  // part of cordova-lib) and parse the format ourselves into a version
  // string suitable to be passed to targetForPlugin.
  // Note that a plugin can be fetched but not installed, so that's why we
  // still need a separate listInstalledPluginVersions.
  listFetchedPluginVersions() {
    const fetchJsonPath = files.pathJoin(this.pluginsDir, 'fetch.json');

    if (!files.exists(fetchJsonPath)) {
      return {};
    }

    const fetchedPluginsMetadata = JSON.parse(files.readFile(
      fetchJsonPath, 'utf8'));
    return _.object(_.map(fetchedPluginsMetadata, (metadata, id) => {
      const source = metadata.source;
      let version;
      if (source.type === 'registry') {
        version = source.id.split('@')[1];
      } else if (source.type === 'git') {
        version = `${source.url}#${source.ref}`;
      } else if (source.type === 'local') {
        version = `file://${source.path}`;
      }
      return [id, version];
    }));
  }

  // Construct a target suitable for 'cordova plugin add' from an id and
  // version, converting or resolving a URL or path where needed.
  targetForPlugin(id, version) {
    assert(id);
    assert(version);

    buildmessage.assertInJob();

    if (utils.isUrlWithSha(version)) {
      return convertToGitUrl(version);
    } else if (utils.isUrlWithFileScheme(version)) {
      // Strip file:// and resolve the path relative to the cordova-build
      // directory
      const pluginPath = this.resolveLocalPluginPath(version);
      // We need to check if the directory exists ourselves because Cordova
      // will try to install from npm (and fail with an unhelpful error message)
      // if the directory is not found
      if (!cordova_util.isDirectory(pluginPath)) {
        buildmessage.error(`Couldn't find local directory \
'${files.convertToOSPath(pluginPath)}' \
(while attempting to install plugin ${id}).`);
        return null;
      }
      return files.convertToOSPath(pluginPath);
    } else {
      return `${id}@${version}`;
    }
  }

  // Strips file:// and resolves the path relative to the cordova-build
  // directory
  resolveLocalPluginPath(pluginPath) {
    pluginPath = pluginPath.substr("file://".length);
    if (utils.isPathRelative(pluginPath)) {
      return path.resolve(this.projectContext.projectDir, pluginPath);
    } else {
      return pluginPath;
    }
  }

  addPlugin(id, version, config = {}) {
    const target = this.targetForPlugin(id, version);
    if (target) {
      const commandOptions = _.extend(this.defaultOptions,
        { cli_variables: config });

      this.runCommands(`adding plugin ${target} \
to Cordova project`, async () => {
        await cordova_lib.raw.plugin('add', [target], commandOptions);
      });
    }
  }

  // plugins is an array of plugin IDs.
  removePlugins(plugins) {
    if (_.isEmpty(plugins)) return;

    this.runCommands(`removing plugins ${plugins} \
from Cordova project`, async () => {
      await cordova_lib.raw.plugin('rm', plugins, this.defaultOptions);
    });
  }

  // Ensures that the Cordova plugins are synchronized with the app-level
  // plugins.
  ensurePluginsAreSynchronized(pluginVersions, pluginsConfiguration = {}) {
    assert(pluginVersions);

    buildmessage.assertInCapture();

    buildmessage.enterJob({ title: "installing Cordova plugins"}, () => {
      // Cordova plugin IDs have changed as part of moving to npm.
      // We convert old plugin IDs to new IDs in the 1.2.0-cordova-changes
      // upgrader and when adding plugins, but packages may still depend on
      // the old IDs.
      // To avoid attempts at duplicate installation, we check for old IDs here
      // and convert them to new IDs when needed. We also convert old-style GitHub
      // tarball URLs to new Git URLs, and check if other Git URLs contain a
      // SHA reference.
      pluginVersions = convertPluginVersions(pluginVersions);

      if (buildmessage.jobHasMessages()) return;

      // Also, we warn if any App.configurePlugin calls in mobile-config.js
      // need to be updated (and in the meantime we take care of the
      // conversion of the plugin configuration to the new ID).
      pluginsConfiguration = _.object(_.map(pluginsConfiguration, (config, id) => {
        const newId = newPluginId(id);
        if (newId) {
          Console.warn();
          Console.labelWarn(`Cordova plugin ${id} has been renamed to ${newId} \
  as part of moving to npm. Please change the App.configurePlugin call in \
  mobile-config.js accordingly.`);
          return [newId, config];
        } else {
          return [id, config];
        }
      }));

      const installedPluginVersions =
        convertPluginVersions(this.listInstalledPluginVersions());

      // Due to the dependency structure of Cordova plugins, it is impossible to
      // upgrade the version on an individual Cordova plugin. Instead, whenever
      // a new Cordova plugin is added or removed, or its version is changed,
      // we just reinstall all of the plugins.
      let shouldReinstallAllPlugins = false;

      // Iterate through all of the plugins and find if any of them have a new
      // version. Additionally, check if we have plugins installed from a local
      // path.
      const pluginsFromLocalPath = {};
      _.each(pluginVersions, (version, id) => {
        // Check if plugin is installed from a local path.
        const isPluginFromLocalPath = utils.isUrlWithFileScheme(version);

        if (isPluginFromLocalPath) {
          pluginsFromLocalPath[id] = version;
        } else {
          if (!_.has(installedPluginVersions, id) ||
            installedPluginVersions[id] !== version) {
            // We do not have the plugin installed or the version has changed.
            shouldReinstallAllPlugins = true;
          }
        }
      });

      if (!_.isEmpty(pluginsFromLocalPath)) {
        Console.debug('Reinstalling Cordova plugins added from the local path');
      }

      // Check to see if we have any installed plugins that are not in the
      // current set of plugins.
      _.each(installedPluginVersions, (version, id) => {
        if (!_.has(pluginVersions, id)) {
          shouldReinstallAllPlugins = true;
        }
      });

      // We either reinstall all plugins or only those fetched from a local
      // path.
      if (shouldReinstallAllPlugins || !_.isEmpty(pluginsFromLocalPath)) {
        let pluginsToRemove;
        if (shouldReinstallAllPlugins) {
          pluginsToRemove = Object.keys(installedPluginVersions);
        } else {
          // Only try to remove plugins that are currently installed.
          pluginsToRemove = _.intersection(
            Object.keys(pluginsFromLocalPath),
            Object.keys(installedPluginVersions));
        }

        this.removePlugins(pluginsToRemove);

        // Now install the necessary plugins.
        if (shouldReinstallAllPlugins) {
          pluginVersionsToInstall = pluginVersions;
        } else {
          pluginVersionsToInstall = pluginsFromLocalPath;
        }

        const pluginsToInstallCount = _.size(pluginVersionsToInstall);
        let installedPluginsCount = 0;

        buildmessage.reportProgress({ current: 0, end: pluginsToInstallCount });
        _.each(pluginVersionsToInstall, (version, id) => {
          this.addPlugin(id, version, pluginsConfiguration[id]);

          buildmessage.reportProgress({
            current: ++installedPluginsCount,
            end: pluginsToInstallCount
          });
        });
      }
    });
  }

  // Cordova commands support

  get defaultOptions() {
    return { silent: !Console.verbose, verbose: Console.verbose };
  }

  defaultEnvWithPathsAdded(...extraPaths) {
    let paths = (this.defaultPaths || []);
    paths.unshift(...extraPaths);
    const env = files.currentEnvWithPathsAdded(...paths);
    return env;
  }

  get defaultPaths() {
    const nodeBinDir = files.getCurrentNodeBinDir();

    // Add the ios-sim bin path so Cordova can find it
    const iosSimBinPath =
      files.pathJoin(files.getDevBundle(),
      'lib/node_modules/ios-sim/bin');

    return [nodeBinDir, iosSimBinPath];
  }

  runCommands(title, promiseOrAsyncFunction, env = this.defaultEnvWithPathsAdded(),
    cwd = this.projectRoot) {
    // Capitalize title for debug output
    Console.debug(title[0].toUpperCase() + title.slice(1));

    const oldCwd = process.cwd();
    if (cwd) {
      process.chdir(files.convertToOSPath(cwd));
    }

    const oldEnv = process.env;
    if (env) {
      process.env = env;
    }

    try {
      const promise = (typeof promiseOrAsyncFunction === 'function') ?
        promiseOrAsyncFunction() : promiseOrAsyncFunction;
      return Promise.await(promise);
    } catch (error) {
      Console.arrowError('Errors executing Cordova commands:');
      Console.error();
      const consoleOptions = Console.options({ indent: 3 });
      Console.error(`While ${title}:`, consoleOptions);

      if (error instanceof CordovaError) {
        // Only print the message for errors thrown by cordova-lib, because
        // these are meant for end-user consumption.
        // But warn that they may not completely apply to our situation.
        // (We do print the stack trace if we are in verbose mode.)
        const errorMessage = Console.verbose ? (error.stack || error.message) :
          error.message;
        Console.error(`Cordova error: ${errorMessage}`, consoleOptions);
        Console.error(chalk.green(`(If the error message contains suggestions \
for a fix, note that this may not apply to the Meteor integration. You can try \
running again with the --verbose option to help diagnose the issue.)`),
          consoleOptions);
      } else {
        // Print stack trace for other errors by default, because the message
        // usually does not give us enough information to know what is going on
        const errorMessage = error && error.stack || error;
        Console.error(errorMessage, consoleOptions);
      };
      throw new main.ExitWithCode(1);
    } finally {
      if (cwd && oldCwd) {
        process.chdir(oldCwd);
      }
      if (env && oldEnv) {
        process.env = oldEnv;
      }
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- SlidingDrawer specific attributes. These attributes are used to configure
         a SlidingDrawer from XML. -->
    <declare-styleable name="SlidingDrawer">
        <!-- Identifier for the child that represents the drawer's handle. -->
        <attr name="handle" format="reference" />
        <!-- Identifier for the child that represents the drawer's content. -->
        <attr name="content" format="reference" />
        <!-- Orientation of the SlidingDrawer. -->
        <attr name="orientation" format="integer"/>
        <!-- Extra offset for the handle at the bottom of the SlidingDrawer. -->
        <attr name="bottomOffset" format="dimension"  />
        <!-- Extra offset for the handle at the top of the SlidingDrawer. -->
        <attr name="topOffset" format="dimension"  />
        <!-- Indicates whether the drawer can be opened/closed by a single tap
             on the handle.  (If false, the user must drag or fling, or click
             using the trackball, to open/close the drawer.)  Default is true. -->
        <attr name="allowSingleTap" format="boolean" />
        <!-- Indicates whether the drawer should be opened/closed with an animation
             when the user clicks the handle. Default is true. -->
        <attr name="animateOnClick" format="boolean" />
    </declare-styleable>
</resources>