text:
<?php

require_once dirname(__FILE__).'/../lib/sfGuardMessageTypeGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/sfGuardMessageTypeGeneratorHelper.class.php';

/**
 * sfGuardMessageType actions.
 *
 * @package    przedszkole
 * @subpackage sfGuardMessageType
 * @author     Tomasz Jakub Rup
 * @version    SVN: $Id: actions.class.php 12474 2008-10-31 10:41:27Z fabien $
 */
class sfGuardMessageTypeActions extends autoSfGuardMessageTypeActions
{
}


text:
layout: page
title: 个人技术博客<修整中...>
tags: [about, owner]
date: 2016-03-21
---

Synemin is my blog, one fork from moon with jekyll theme.

## Features
* Minimal, you can focus on your content
* Responsive
* Disqus integration
* Syntax highlighting
* Optional post image
* Social icons
* Page for sharing projects
* Optional background image
* Simple navigation menu
* MathJax support

## Preview

{% capture images %}
    https://cloud.githubusercontent.com/assets/754514/14509720/61c61058-01d6-11e6-93ab-0918515ecd56.png
    https://cloud.githubusercontent.com/assets/754514/14509716/61ac6c8e-01d6-11e6-879f-8308883de790.png
{% endcapture %}
{% include gallery images=images caption="Screenshots of Moon Theme" cols=2 %}

See a [live version of Moon](http://taylantatli.github.io/Moon) hosted on GitHub.

## Getting Started

To learn how to install and use this theme check out the [Setup Guide](http://taylantatli.me/Moon/moon-theme/) for more information.

[Install Moon](https://github.com/TaylanTatli/Moon){: .btn}

redpajama_set_name: RedPajamaGithub


text:
package com.xhaleera.whiteshark.exceptions;

/**
 * Exception thrown when an expected object property element cannot be found.
 *
 * @author Christophe SAUVEUR (christophe@xhaleera.com)
 * @since 1.0
 * @version 1.0
 */
public class WhiteSharkNotAPropertyException extends WhiteSharkException {

	/** Serialization version UID */
	static final long serialVersionUID = 1;

	/**
	 * Constructor with custom message
	 * @param arg0 Custom message
	 */
	public WhiteSharkNotAPropertyException(String arg0) {
		super(arg0);
	}

}


text:
exports.attach = function(Handlebars) {

// BEGIN(BROWSER)

Handlebars.Visitor = function() {};

Handlebars.Visitor.prototype = {
  accept: function(object) {
    return this[object.type](object);
  }
};

// END(BROWSER)

return Handlebars;
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VidyoIntegration.CommonLib.CicTypes
{
    public enum GenericInteractionInitialState
    {
        None,
        Alerting,
        Connected,
        Held,
        Messaging,
        Offering,
        Parked,
        Proceeding,
        System,
        InternalDisconnect,
        ExternalDisconnect,
        Suspended
    }
}


text:
package com.wiley.autotest.selenium.elements.upgrade.v3.expectedconditions;

import com.wiley.autotest.selenium.elements.upgrade.TeasyElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;

import javax.annotation.Nullable;

/**
 * Created by vefimov on 21/08/2017.
 */
public class ElementDisplayed implements ExpectedCondition<Boolean> {

    private TeasyElement element;

    public ElementDisplayed(TeasyElement element) {
        this.element = element;
    }

    @Nullable
    @Override
    public Boolean apply(@Nullable WebDriver driver) {
        return element.isDisplayed();
    }

    @Override
    public String toString() {
        return String.format("Element '%s' is not displayed!", element.toString());
    }
}


text:
from django.test.simple import DjangoTestSuiteRunner

class DatabaselessTestRunner(DjangoTestSuiteRunner):
    """
    A test suite runner that does not set up and tear down a database.
    """

    def setup_databases(self):
        """Overrides DjangoTestSuiteRunner"""
        pass

    def teardown_databases(self, *args):
        """Overrides DjangoTestSuiteRunner"""
        pass


text:
Calculate-in-plain-english
==========================

This is a simple project that takes an english language and tries to solve the math problems in it.


text:
exports.dbc = [
  {
    name: 'default',
    host: process.env.MYSQL_HOST || "localhost",
    user: process.env.MYSQL_USER || "blew",
    password: process.env.MYSQL_PASSWORD || "Invalid password",
    database: process.env.MYSQL_DATABASE || "IR_properties",
    table: "IR_properties",
    multipleStatements: false,
  },
  {
    name: 'err',
    host: 'localhost',
    user: "bflew",
    password: 'pass',
    database: 'IR',
    table: 'IR_properties',
    multipleStatements: false,
  }
];

module.exports = exports.dbc;

// var assert = require('assert');
// var app_utils = require('../lib/users/utils.js');

// exports.DatabaseConfig = function(config) {
//   // This is expected to be either an 'Array' or 'Object' type, or that is --
//   // two or more configuration objects, or a single configuration 'Object'.
//   var configs = null;

//   var num_databases = config.length;
//   console.log('num_databases:', num_databases);

//   for(var idx = 0; idx != num_databases; ++idx) {

//     if(app_utils.array(config) === true) {
//       var cfg = config[idx];

//       var cfg_obj = {
//         name: cfg.name || 'database',
//         host: cfg.host || 'invalid host',
//         user: cfg.user || 'invalid user',
//         password: cfg.password || 'invalid password',
//         database: cfg.database || 'invalid database',
//         table: cfg.table || 'invalid table',

//         // Additional options that are specific to the node-mysql library
//         // interface
//         multipleStatements: cfg.multipleStatements || false,
//       };

//       configs = [];
//       configs.push(cfg_obj);

//     // if(app_utils.enumerate(configs, 0) === true) {
//       this.config_ = configs;
//     // }

//     } else if(app_utils.object(config) === true) {

//       var cfg_obj = {
//         name: cfg.name || 'database',
//         host: cfg.host || 'invalid host',
//         user: cfg.user || 'invalid user',
//         password: cfg.password || 'invalid password',
//         database: cfg.database || 'invalid database',
//         table: cfg.table || 'invalid table',

//         // Additional options that are specific to the node-mysql library
//         // interface
//         multipleStatements: cfg.multipleStatements || false,
//       };

//       configs = {};
//       configs = cfg_obj;

//       // if(app_utils.enumerate(configs, 'cfg_obj') === true) {
//         this.config_ = configs;
//       // }
//     }
//   } // end for loop
// };

// exports.DatabaseConfig.prototype.config = function(index) {
//   var cfg = this.config_;
//   var obj_value = null;

//   // if(app_utils.enumerate(configs, 'cfg_obj') === true) {
//     // obj_value = 'cfg_obj';
//   // } else if(app_utils.enumerate(configs, 0) === true) {
//     // enum_value = 0;
//   // }

//   if(app_utils.enumerate(cfg, 0) === true && index != cfg.length) {
//     return cfg[index];
//   }
// };


text:
import Environment from '../../environment';
import Bounds, { clear } from '../../bounds';
import { Opaque, Simple, Option } from "@glimmer/interfaces";
import { NewElementBuilder } from '../element-builder';

export interface DynamicContent {
  bounds: Bounds;
  update(env: Environment, value: Opaque): DynamicContent;
}

abstract class DynamicContentBase implements DynamicContent {
  constructor(protected trusting: boolean) {}

  abstract update(env: Environment, value: Opaque): DynamicContent;

  public abstract bounds: Bounds;

  protected retry(env: Environment, value: Opaque): DynamicContent {
    let { bounds } = this;
    let parentElement = bounds.parentElement();
    let nextSibling = clear(bounds);

    let stack = NewElementBuilder.forInitialRender(env, { element: parentElement, nextSibling });

    if (this.trusting) {
      return stack.__appendTrustingDynamicContent(value);
    } else {
      return stack.__appendCautiousDynamicContent(value);
    }
  }
}

export default DynamicContentBase;

export class DynamicContentWrapper implements DynamicContent, Bounds {
  parentElement(): Simple.Element {
    return this.bounds.parentElement();
  }

  firstNode(): Option<Simple.Node> {
    return this.bounds.firstNode();
  }

  lastNode(): Option<Simple.Node> {
    return this.bounds.lastNode();
  }

  public bounds: Bounds;

  constructor(private inner: DynamicContent) {
    this.bounds = inner.bounds;
  }

  update(env: Environment, value: Opaque): DynamicContentWrapper {
    let inner = this.inner = this.inner.update(env, value);
    this.bounds = inner.bounds;
    return this;
  }
}


text:
.. _page-soup:

Soup
===================================

Making a Soup
-----------------------------------

To parse a :math:`\LaTeX` document, pass an open filehandle or a string into the
:code:`TexSoup` constructor::

    >>> from TexSoup import TexSoup
    >>> with open("main.tex") as f:
    ...     soup = TexSoup(f)
    >>> soup2 = TexSoup(r'\begin{document}Hello world!\end{document}')

Alternatively, compute the data structure only::

    >>> from TexSoup import read
    >>> soup3, _ = read(r'\begin{document}Hello world!\end{document}')
    >>> soup3
    [TexNamedEnv('document', ['Hello world!'], [])]

You can also ask TexSoup to tolerate :math:`\LaTeX` errors. In which case,
TexSoup will make a best-effort guess::

    >>> soup4 = TexSoup(r'\begin{itemize}\item hullo\end{enumerate}', tolerance=1)
    >>> soup4
    \begin{itemize}\item hullo\end{itemize}\end{enumerate}

To output the soup, you can call :code:`str()` on a :class:`TexSoup.data.TexNode` object, or any nested
data structure.

    >>> soup4
    \begin{itemize}\item hullo\end{itemize}\end{enumerate}
    >>> str(soup4)
    '\\begin{itemize}\\item hullo\\end{itemize}\\end{enumerate}'
    >>> soup4.item
    \item hullo
    >>> str(soup4.item)
    '\\item hullo'

Kinds of Objects
------------------------------------

TexSoup translates a :math:`\LaTeX` document into a tree of Python objects.
There are only three *kinds* of objects: commands, environments, and
text.

Command
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

A :code:`TexCmd` corresponds to a command in the original document::

    >>> soup = TexSoup(r'I am \textbf{\large Large and bold}')
    >>> cmd = soup.textbf
    >>> cmd
    \textbf{\large Large and bold}

You can access the underlying data structures using :code:`.expr`.

    >>> cmd.expr
    TexCmd('textbf', [BraceGroup(TexCmd('large'), ' Large and bold')])

Every command has a name::

    >>> cmd.name
    'textbf'

You can change the command's name too. This change will be reflected when you
convert the TexSoup back to :math:`\LaTeX`::

    >>> cmd.name = 'textit'
    >>> cmd
    \textit{\large Large and bold}
    >>> soup
    I am \textit{\large Large and bold}

Commands may have any number of arguments, stored in :code:`.args` as a list.
Our command has just one argument::

    >>> len(cmd.args)
    1
    >>> str(cmd.args[0])
    '{\\large Large and bold}'

You can add, remove, and modify arguments, treating :code:`.args` as a list::

    >>> cmd.args.append('{moar}')  # add arguments
    >>> str(cmd.args)
    '{\\large Large and bold}{moar}'
    >>> cmd.args.remove('{\large Large and bold}')  # remove arguments
    >>> str(cmd.args)
    '{moar}'
    >>> cmd.args[0].string = 'floating'  # modify arguments
    >>> str(cmd.args)
    '{floating}'

All arguments are represented using TexSoup's underlying data structures::

    >>> cmd.args
    [BraceGroup('floating')]

The above commands all apply to optional arguments as well. Note
that all changes are reflected when we convert the soup back to :math:`\LaTeX`::

    >>> cmd.args.append('[optional]')  # add optional arg
    >>> str(cmd.args)
    '{floating}[optional]'
    >>> cmd.args.remove('[optional]')  # remove optional arg
    >>> str(cmd.args)
    '{floating}'
    >>> soup
    I am \textit{floating}

Text
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. note: If you've just started reading from this portion of the guide, start
         by defining :code:`soup = TexSoup(r'I am \textit{floating}')`.

A :code:`TexText` represents floating bits of text::

    >>> soup
    I am \textit{floating}
    >>> text = next(soup.contents)
    >>> text
    'I am '
    >>> type(text)
    <class 'TexSoup.data.TexText'>

You can set the :code:`.text` attribute. As before, this will be reflected
when you convert the data structure back into :math:`\LaTeX`.

    >>> text.text = 'I am not '
    >>> soup
    I am not \textit{floating}

Environment
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Environments, or :code:`TexEnv`, are split into three types:

1. :code:`TexNamedEnv`: The typical environments you think of, with a begin
   and an end, such as :code:`\begin{itemize}...\end{itemize}`.
2. :code:`TexUnNamedEnv`: Special environments such as math :code:`\(...\)`.
   All math environments fall in this category.
3. :code:`TexGroup`: Unnamed environments with single-character delimiters,
   like :code:`{...}`.

You can access environments by name::

    >>> soup = TexSoup(r'Haha \begin{itemize}[label=\alph]\item Huehue\end{itemize}')
    >>> env = soup.itemize
    >>> env
    \begin{itemize}[label=\alph]\item Huehue\end{itemize}

Every environment's name can be accessed and modified using :code:`.name`::

    >>> env.name
    'itemize'
    >>> env.name = 'enumerate'
    >>> env
    \begin{enumerate}[label=\alph]\item Huehue\end{enumerate}
    >>> soup
    Haha \begin{enumerate}[label=\alph]\item Huehue\end{enumerate}

As with commands, environments store arguments in a list :code:`.args`::

    >>> str(env.args)
    '[label=\\alph]'

Each environment will contain variable amounts of content, accessible via
:code:`.contents`::

    >>> list(env.contents)
    [\item Huehue]


text:
Originally published: 2010-11-27 03:00:26
Last updated: 2010-11-27 03:00:28
Author: thom neale

Set-like operations for dictionaries


text:
package com.sanath.movies.adapters;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sanath.movies.common.Util;
import com.sanath.movies.models.Api;
import com.sanath.movies.R;
import com.sanath.movies.common.OnMovieSelectListener;
import com.sanath.movies.models.Movie;
import com.squareup.picasso.Picasso;

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

/**
 * Created by sanathnandasiri on 7/15/16.
 */

public class MoviesRecyclerAdapter extends RecyclerView.Adapter<MovieRecyclerViewHolder> {

    private static final String TAG = MoviesRecyclerAdapter.class.getSimpleName();
    private List<Movie> mMovieList = new ArrayList<>();
    private final Context mContext;
    private final OnMovieSelectListener mOnMovieSelectListener;

    public MoviesRecyclerAdapter(Context context, List<Movie> movies, OnMovieSelectListener onMovieSelectListener) {
        this.mMovieList = movies;
        this.mContext = context;
        this.mOnMovieSelectListener = onMovieSelectListener;
    }

    @Override
    public MovieRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View root = LayoutInflater.from(mContext).inflate(R.layout.movie_list_item, parent, false);
        return new MovieRecyclerViewHolder(root);
    }

    @Override
    public void onBindViewHolder(final MovieRecyclerViewHolder holder, int position) {
        Movie movie = mMovieList.get(position);
        Log.d(TAG,"Movie " + movie);
        Uri imageUri = Uri.parse(Api.BASE_URL_IMAGE).buildUpon()
                .appendPath("w185")
                .appendEncodedPath(movie.posterPath)
                .build();
        Log.d(TAG, imageUri.toString());
        Drawable drawableFilmReal;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
            drawableFilmReal = mContext.getResources().getDrawable(R.drawable.ic_film_real, mContext.getApplicationContext().getTheme());
        } else {
            drawableFilmReal = mContext.getResources().getDrawable(R.drawable.ic_film_real);
        }
        Picasso.with(mContext)
                .load(imageUri.toString())
                .placeholder(drawableFilmReal)
                .into(holder.mImageViewMovie);
        holder.mImageViewMovie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOnMovieSelectListener.onSelectMovie(mMovieList.get(holder.getAdapterPosition()));
            }
        });

        holder.mTextView.setText(Util.getRating(movie.voteAverage));
    }

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

    public void add(List<Movie> movies) {
        mMovieList.clear();
        mMovieList.addAll(movies);
        notifyDataSetChanged();
    }

    public List<Movie> get() {
        return mMovieList;
    }
}


text:
"""Google Cloud Bigtable HappyBase batch module."""

import datetime
import six

from gcloud_bigtable._helpers import _microseconds_to_timestamp
from gcloud_bigtable.row import TimestampRange

_WAL_SENTINEL = object()
# Assumed granularity of timestamps in Cloud Bigtable.
_ONE_MILLISECOND = datetime.timedelta(microseconds=1000)

def _get_column_pairs(columns, require_qualifier=False):
    """Turns a list of column or column families in parsed pairs.

    Turns a column family (``fam`` or ``fam:``) into a pair such
    as ``['fam', None]`` and turns a column (``fam:col``) into
    ``['fam', 'col']``.

    :type columns: list
    :param columns: Iterable containing column names (as
                    strings). Each column name can be either

                      * an entire column family: ``fam`` or ``fam:``
                      * an single column: ``fam:col``

    :type require_qualifier: bool
    :param require_qualifier: Boolean indicating if the columns should
                              all have a qualifier or not.

    :rtype: list
    :returns: List of pairs, where the first element in each pair is the
              column family and the second is the column qualifier
              (or :data:`None`).
    :raises: :class:`ValueError <exceptions.ValueError>` if any of the columns
             are not of the expected format.
             :class:`ValueError <exceptions.ValueError>` if
             ``require_qualifier`` is :data:`True` and one of the values is
             for an entire column family
    """
    column_pairs = []
    for column in columns:
        # Remove trailing colons (i.e. for standalone column family).
        column = column.rstrip(':')
        num_colons = column.count(':')
        if num_colons == 0:
            # column is a column family.
            if require_qualifier:
                raise ValueError('column does not contain a qualifier',
                                 column)
            else:
                column_pairs.append([column, None])
        elif num_colons == 1:
            column_pairs.append(column.split(':'))
        else:
            raise ValueError('Column contains the : separator more than once')

    return column_pairs

class Batch(object):
    """Batch class for accumulating mutations.

    :type table: :class:`Table <gcloud_bigtable.happybase.table.Table>`
    :param table: The table where mutations will be applied.

    :type timestamp: int
    :param timestamp: (Optional) Timestamp (in milliseconds since the epoch)
                      that all mutations will be applied at.

    :type batch_size: int
    :param batch_size: (Optional) The maximum number of mutations to allow
                       to accumulate before committing them.

    :type transaction: bool
    :param transaction: Flag indicating if the mutations should be sent
                        transactionally or not. If ``transaction=True`` and
                        an error occurs while a :class:`Batch` is active,
                        then none of the accumulated mutations will be
                        committed. If ``batch_size`` is set, the mutation
                        can't be transactional.

    :type wal: object
    :param wal: Unused parameter (Boolean for using the HBase Write Ahead Log).
                Provided for compatibility with HappyBase, but irrelevant for
                Cloud Bigtable since it does not have a Write Ahead Log.

    :raises: :class:`TypeError <exceptions.TypeError>` if ``batch_size``
             is set and ``transaction=True``.
             :class:`ValueError <exceptions.ValueError>` if ``batch_size``
             is not positive.
             :class:`ValueError <exceptions.ValueError>` if ``wal``
             is used.
    """

    def __init__(self, table, timestamp=None, batch_size=None,
                 transaction=False, wal=_WAL_SENTINEL):
        if wal is not _WAL_SENTINEL:
            raise ValueError('The wal argument cannot be used with '
                             'Cloud Bigtable.')

        if batch_size is not None:
            if transaction:
                raise TypeError('When batch_size is set, a Batch cannot be '
                                'transactional')
            if batch_size <= 0:
                raise ValueError('batch_size must be positive')

        self._table = table
        self._batch_size = batch_size
        # Timestamp is in milliseconds, convert to microseconds.
        self._timestamp = self._delete_range = None
        if timestamp is not None:
            self._timestamp = _microseconds_to_timestamp(1000 * timestamp)
            # For deletes, we get the very next timestamp (assuming timestamp
            # granularity is milliseconds). This is because HappyBase users
            # expect HBase deletes to go **up to** and **including** the
            # timestamp while Cloud Bigtable Time Ranges **exclude** the
            # final timestamp.
            next_timestamp = self._timestamp + _ONE_MILLISECOND
            self._delete_range = TimestampRange(end=next_timestamp)
        self._transaction = transaction

        # Internal state for tracking mutations.
        self._row_map = {}
        self._mutation_count = 0

    def send(self):
        """Send / commit the batch of mutations to the server."""
        for row in self._row_map.values():
            # commit() does nothing if row hasn't accumulated any mutations.
            row.commit()

        self._row_map.clear()
        self._mutation_count = 0

    def _try_send(self):
        """Send / commit the batch if mutations have exceeded batch size."""
        if self._batch_size and self._mutation_count >= self._batch_size:
            self.send()

    def _get_row(self, row_key):
        """Gets a row that will hold mutations.

        If the row is not already cached on the current batch, a new row will
        be created.

        :type row_key: str
        :param row_key: The row key for a row stored in the map.

        :rtype: :class:`Row <gcloud_bigtable.row.Row>`
        :returns: The newly created or stored row that will hold mutations.
        """
        if row_key not in self._row_map:
            table = self._table._low_level_table
            self._row_map[row_key] = table.row(row_key)

        return self._row_map[row_key]

    def put(self, row, data, wal=_WAL_SENTINEL):
        """Insert data into a row in the table owned by this batch.

        :type row: str
        :param row: The row key where the mutation will be "put".

        :type data: dict
        :param data: Dictionary containing the data to be inserted. The keys
                     are columns names (of the form ``fam:col``) and the values
                     are strings (bytes) to be stored in those columns.

        :type wal: object
        :param wal: Unused parameter (to over-ride the default on the
                    instance). Provided for compatibility with HappyBase, but
                    irrelevant for Cloud Bigtable since it does not have a
                    Write Ahead Log.

        :raises: :class:`ValueError <exceptions.ValueError>` if ``wal``
                 is used.
        """
        if wal is not _WAL_SENTINEL:
            raise ValueError('The wal argument cannot be used with '
                             'Cloud Bigtable.')

        row_object = self._get_row(row)
        # Make sure all the keys are valid before beginning
        # to add mutations.
        column_pairs = _get_column_pairs(six.iterkeys(data),
                                         require_qualifier=True)
        for column_family_id, column_qualifier in column_pairs:
            value = data[column_family_id + ':' + column_qualifier]
            row_object.set_cell(column_family_id, column_qualifier,
                                value, timestamp=self._timestamp)

        self._mutation_count += len(data)
        self._try_send()

    def _delete_columns(self, columns, row_object):
        """Adds delete mutations for a list of columns and column families.

        :type columns: list
        :param columns: Iterable containing column names (as
                        strings). Each column name can be either

                          * an entire column family: ``fam`` or ``fam:``
                          * an single column: ``fam:col``

        :type row_object: :class:`Row <gcloud_bigtable.row.Row>`
        :param row_object: The row which will hold the delete mutations.

        :raises: :class:`ValueError <exceptions.ValueError>` if the delete
                 timestamp range is set on the current batch, but a
                 column family delete is attempted.
        """
        column_pairs = _get_column_pairs(columns)
        for column_family_id, column_qualifier in column_pairs:
            if column_qualifier is None:
                if self._delete_range is not None:
                    raise ValueError('The Cloud Bigtable API does not support '
                                     'adding a timestamp to '
                                     '"DeleteFromFamily" ')
                row_object.delete_cells(column_family_id,
                                        columns=row_object.ALL_COLUMNS)
            else:
                row_object.delete_cell(column_family_id,
                                       column_qualifier,
                                       time_range=self._delete_range)

    def delete(self, row, columns=None, wal=_WAL_SENTINEL):
        """Delete data from a row in the table owned by this batch.

        :type row: str
        :param row: The row key where the delete will occur.

        :type columns: list
        :param columns: (Optional) Iterable containing column names (as
                        strings). Each column name can be either

                          * an entire column family: ``fam`` or ``fam:``
                          * an single column: ``fam:col``

                        If not used, will delete the entire row.

        :type wal: object
        :param wal: Unused parameter (to over-ride the default on the
                    instance). Provided for compatibility with HappyBase, but
                    irrelevant for Cloud Bigtable since it does not have a
                    Write Ahead Log.

        :raises: :class:`ValueError <exceptions.ValueError>` if ``wal``
                 is used, or if if the delete timestamp range is set on the
                 current batch, but a full row delete is attempted.
        """
        if wal is not _WAL_SENTINEL:
            raise ValueError('The wal argument cannot be used with '
                             'Cloud Bigtable.')

        row_object = self._get_row(row)

        if columns is None:
            # Delete entire row.
            if self._delete_range is not None:
                raise ValueError('The Cloud Bigtable API does not support '
                                 'adding a timestamp to "DeleteFromRow" '
                                 'mutations')
            row_object.delete()
            self._mutation_count += 1
        else:
            self._delete_columns(columns, row_object)
            self._mutation_count += len(columns)

        self._try_send()

    def __enter__(self):
        """Enter context manager, no set-up required."""
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        """Exit context manager, no set-up required.

        :type exc_type: type
        :param exc_type: The type of the exception if one occurred while the
                         context manager was active. Otherwise, :data:`None`.

        :type exc_value: :class:`Exception <exceptions.Exception>`
        :param exc_value: An instance of ``exc_type`` if an exception occurred
                          while the context was active.
                          Otherwise, :data:`None`.

        :type traceback: ``traceback`` type
        :param traceback: The traceback where the exception occurred (if one
                          did occur). Otherwise, :data:`None`.
        """
        # If the context manager encountered an exception and the batch is
        # transactional, we don't commit the mutations.
        if self._transaction and exc_type is not None:
            return

        # NOTE: For non-transactional batches, this will even commit mutations
        #       if an error occurred during the context manager.
        self.send()


text:
<?php

namespace Ekino\Bundle\NewRelicBundle\Silex;

use Silex\Application;
use Silex\ServiceProviderInterface;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Console\ConsoleEvents;

use Ekino\Bundle\NewRelicBundle\NewRelic\NewRelic;
use Ekino\Bundle\NewRelicBundle\NewRelic\NewRelicInteractor;
use Ekino\Bundle\NewRelicBundle\NewRelic\LoggingInteractorDecorator;
use Ekino\Bundle\NewRelicBundle\Listener\RequestListener;
use Ekino\Bundle\NewRelicBundle\Listener\ResponseListener;
use Ekino\Bundle\NewRelicBundle\Listener\ExceptionListener;
use Ekino\Bundle\NewRelicBundle\Listener\CommandListener;
use Ekino\Bundle\NewRelicBundle\TransactionNamingStrategy\RouteNamingStrategy;
use Ekino\Bundle\NewRelicBundle\Command\NotifyDeploymentCommand;

/**
 * Service Provider for Silex
 *
 * @author Jérôme TAMARELLE <jerome@tamarelle.net>
 */
class EkinoNewRelicServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['new_relic.enabled'] = extension_loaded('newrelic');
        $app['new_relic.application_name'] = 'Silex Application';
        $app['new_relic.api_key'] = null;
        $app['new_relic.logging'] = false;
        $app['new_relic.log_exceptions'] = false;
        $app['new_relic.log_commands'] = class_exists('Symfony\\Component\\Console\\ConsoleEvents');

        $app['new_relic'] = $app->share(function ($app) {
            return new NewRelic($app['new_relic.application_name'], $app['new_relic.api_key']);
        });

        $app['new_relic.transaction_naming_strategy'] = $app->share(function ($app) {
            // The route strategy is used by default because closures controllers
            // cannot be represented by a string
            return new RouteNamingStrategy();
        });

        // Interactor
        $app['new_relic.interactor'] = $app->share(function ($app) {
            if ($app['new_relic.logging']) {
                return $app['new_relic.interactor.logger'];
            }

            return $app['new_relic.interactor.real'];
        });
        $app['new_relic.interactor.real'] = $app->share(function ($app) {
            return new NewRelicInteractor();
        });
        $app['new_relic.interactor.logger'] = $app->share(function ($app) {
            return new LoggingInteractorDecorator($app['new_relic.interactor.real'], isset($app['logger']) ? $app['logger'] : null);
        });

        // Listeners
        $app['new_relic.request_listener'] = $app->share(function ($app) {
            return new RequestListener($app['new_relic'], $app['new_relic.interactor'], array(), array(), $app['new_relic.transaction_naming_strategy']);
        });
        $app['new_relic.exception_listener'] = $app->share(function ($app) {
            return new ExceptionListener($app['new_relic.interactor']);
        });
        $app['new_relic.response_listener'] = $app->share(function ($app) {
            return new ResponseListener($app['new_relic'], $app['new_relic.interactor'], false);
        });
        $app['new_relic.console_listener'] = $app->share(function ($app) {
            return new CommandListener($app['new_relic'], $app['new_relic.interactor'], array());
        });

        // Optional command
        $app['new_relic.command.notify'] = $app->share(function ($app) {
            return new NotifyDeploymentCommand($app['new_relic']);
        });
    }

    public function boot(Application $app)
    {
        if (!$app['new_relic.enabled']) {
            return;
        }

        $app['dispatcher']->addListener(KernelEvents::REQUEST, array($app['new_relic.request_listener'], 'setApplicationName'), -1);
        $app['dispatcher']->addListener(KernelEvents::REQUEST, array($app['new_relic.request_listener'], 'setIgnoreTransaction'), -1);
        $app['dispatcher']->addListener(KernelEvents::REQUEST, array($app['new_relic.request_listener'], 'setTransactionName'), -1);

        $app['dispatcher']->addListener(KernelEvents::RESPONSE, array($app['new_relic.response_listener'], 'onCoreResponse'), -1);

        if ($app['new_relic.log_exceptions']) {
            $app['dispatcher']->addListener(KernelEvents::EXCEPTION, array($app['new_relic.exception_listener'], 'onKernelException'), 0);
        }

        if ($app['new_relic.log_commands']) {
            $app['dispatcher']->addListener(ConsoleEvents::COMMAND, array($app['new_relic.console_listener'], 'onConsoleCommand'), 0);
        }

        if ($app['new_relic.log_exceptions'] && $app['new_relic.log_commands']) {
            $app['dispatcher']->addListener(ConsoleEvents::EXCEPTION, array($app['new_relic.console_listener'], 'onConsoleException'), 0);
        }
    }
}


text:
var PopSearch = {
	hotkey : {},
	PSFrame : function () {
		var f = document.createElement('iframe');
		f.id = 'cksse_iframe';
		f.name = 'cksse_iwin';
		f.src = safari.extension.baseURI + 'popsearch.html';
		f.style.cssText = '\
			position: fixed !important; \
			z-index: 2147483647 !important; \
			left: 0 !important; top: 0 !important; \
			width: 100% !important; height: 100% !important; \
			border-width: 0 !important; \
			background: transparent !important; \
			opacity: 0; \
		';
		return f;
	},
	handleKeyDown : function (e) {
		if (!PopSearch.psFrame) {
			var k = e.which;
			var m = e.shiftKey * 1 + e.altKey * 2 + e.ctrlKey * 4 + e.metaKey * 8;
			if (k === PopSearch.hotkey.k && m === PopSearch.hotkey.m) {
				var forbiddenTargets = ['INPUT','BUTTON','SELECT','TEXTAREA'];
				var elementIsForbidden = (forbiddenTargets.indexOf(e.target.nodeName) > -1);
				var elementIsEditable = e.target.isContentEditable;
				if (m >= 4 || (!elementIsForbidden && !elementIsEditable)) {
					e.preventDefault();
					var selectedText = window.getSelection().toString();
					safari.self.tab.dispatchMessage('tellMyTopToPop', selectedText);
				}
			}
		}
	},
	handleContextMenu : function (e) {
		if (e.target.nodeName === 'INPUT') {
			var inputField = e.target;
			var searchTerms = '';
			var urlTemplate = '';
			if ((inputField.type == 'text' || inputField.type == 'search') && inputField.value) {
				var plusEncodedTerms = inputField.value;
				while (plusEncodedTerms.indexOf(' ') > -1)
					plusEncodedTerms = plusEncodedTerms.replace(' ', '+');
				var percentEncodedTerms = inputField.value;
				while (percentEncodedTerms.indexOf(' ') > -1)
					percentEncodedTerms = percentEncodedTerms.replace(' ', '%20');
				if (window.location.href.indexOf(inputField.value) > -1) {
					searchTerms = inputField.value;
					urlTemplate = window.location.href.replace(inputField.value, '%s');
				}
				else if (window.location.href.indexOf(plusEncodedTerms) > -1) {
					searchTerms = inputField.value;
					urlTemplate = window.location.href.replace(plusEncodedTerms, '%s');
				}
				else if (window.location.href.indexOf(percentEncodedTerms) > -1) {
					searchTerms = inputField.value;
					urlTemplate = window.location.href.replace(percentEncodedTerms, '%s');
				}
			}
			if (searchTerms) {
				var userInfo = {
					searchTerms: searchTerms,
					urlTemplate: urlTemplate,
					hostname: window.location.hostname
				};
				safari.self.tab.setContextMenuEventUserInfo(e, userInfo);
			}
		}
	},
	handleMessage : function (e) {
		switch (e.name) {
			case 'receiveSettings': {
				if (e.message.hotkey)
					PopSearch.hotkey = e.message.hotkey;
				break;
			}
			case 'SendTextSelection': {
				safari.self.tab.dispatchMessage('TextSelectionIs', window.getSelection().toString());
				break;
			}
		}
	},
	handleMessageForTop : function (e) {
		switch (e.name) {
			case 'insertPSFrame': {
				PopSearch.insertPSFrame();
				break;
			}
			case 'removePSFrame': {		// event.message == andFocusParent
				if (PopSearch.psFrame) {
					PopSearch.removePSFrame();
					if (e.message) window.focus();
				} break;
			}
			case 'togglePSFrame': {
				if (PopSearch.psFrame) {
					PopSearch.removePSFrame();
					window.focus();
				} else {
					safari.self.tab.dispatchMessage('saveSelection', window.getSelection().toString());
					PopSearch.insertPSFrame();
				}
				break;
			}
			case 'focusYourself': {
				window.focus();
				break;
			}
			case 'loadUrl': {
				window.location.href = e.message;
				break;
			}
		}
	},
	insertPSFrame : function () {
		this.psFrame = document.body.appendChild(new this.PSFrame);
		setTimeout(function () {
			PopSearch.psFrame.style.opacity = '1';
		}, 50); /*
		PopSearch.fadeInTimer = setInterval(function () {
			var currop = PopSearch.psFrame.style.opacity * 1;
			currop = currop + 0.25;
			PopSearch.psFrame.style.opacity = currop + '';
			if (currop >= 1) clearInterval(PopSearch.fadeInTimer);
		}, 10);*/
	},
	removePSFrame : function () {
		document.body.removeChild(this.psFrame);
		this.psFrame = null;
	},
};

if ((/^http/.test(location.protocol) || location.href == 'about:blank') && window.name != 'cksse_iwin') {
	document.addEventListener('keydown', PopSearch.handleKeyDown, false);
	document.addEventListener('contextmenu', PopSearch.handleContextMenu, false);
	safari.self.addEventListener('message', PopSearch.handleMessage, false);
	if (window == window.top)
		safari.self.addEventListener('message', PopSearch.handleMessageForTop, false);
	safari.self.tab.dispatchMessage('passSettings', ['hotkey']);
	if (document.title == 'AutoPopSearch') {
		PopSearch.autoPop = true;
		PopSearch.insertPSFrame();
	}
}


text:
static const void *kWYAddSubViewsFinishCallBackKey = &kWYAddSubViewsFinishCallBackKey;

@implementation UIView (WYCustomNavigationBar)

+ (void)load {

    // runtime加载类时hook 原有的adddSubViews,在结束时回调block
    Method oldViewDidLoadMethod = class_getInstanceMethod([self class], @selector(addSubview:));
    Method newViewDidLoadMethod = class_getInstanceMethod([self class], @selector(wy_WYCustomNavigationBar_addSubview:));
    method_exchangeImplementations(oldViewDidLoadMethod, newViewDidLoadMethod);

}

#pragma mark - 关联回调block,setter/getter方法

- (void)setWy_addSubViewsFinishCallBack:(void (^)())wy_addSubViewsFinishCallBack {
    objc_setAssociatedObject(self, kWYAddSubViewsFinishCallBackKey, wy_addSubViewsFinishCallBack, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void (^)())wy_addSubViewsFinishCallBack {
    return objc_getAssociatedObject(self, kWYAddSubViewsFinishCallBackKey);
}

#pragma mark - hook方法中处理回调

- (void)wy_WYCustomNavigationBar_addSubview:(UIView *)subView {

    // 1.添加子控件
    [self wy_WYCustomNavigationBar_addSubview:subView];

    // 2.回调
    if (self.wy_addSubViewsFinishCallBack) {
        self.wy_addSubViewsFinishCallBack();
    }
}

@end


text:
import { TestBed } from '@angular/core/testing';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

import { FavoritesApiService } from './favorites-api.service';
import { FavoritesStateService } from './favorites/state/favorites-state.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';

describe('FavoritesApiService', () => {
  let service: FavoritesApiService;
  let getSubject: any;
  let getSpy: any;

  beforeEach(() => {
    const favoritesStateService: any = jasmine.createSpyObj('favoritesStateService', [
      'fetchLoader'
    ]);
    getSubject = new BehaviorSubject<any>([]);
    const injector = TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        FavoritesApiService,
        {provide: FavoritesStateService, useValue: favoritesStateService}
      ]
    });
    service = injector.get(FavoritesApiService);
    spyOn(service, 'toggleLoader');
    spyOn(service, 'complete');
    spyOn(service, 'failed');
    getSpy = spyOn(service, 'get');
    getSpy.and.callFake(() => getSubject);
  });

  it('should call toggleLoader() when load() is called', () => {
    service.load([]);
    expect(service.toggleLoader).toHaveBeenCalledTimes(1);
    expect(service.toggleLoader).toHaveBeenCalledWith(true);
  });

  it('should call get() when load() is called', () => {
    service.load(['a']);
    expect(service.get).toHaveBeenCalledTimes(1);
    expect(service.get).toHaveBeenCalledWith('./assets/json/stocks.json');
  });

  it('should call complete() with a successful completion of get() call', () => {
    service.load([]);
    expect(service.complete).toHaveBeenCalledTimes(1);
    expect(service.complete).toHaveBeenCalledWith([]);
  });

  it('should call failed() when get() call errors out', () => {
    getSpy.and.callFake(() => Observable.throw('error'));
    service.load([]);
    expect(service.failed).toHaveBeenCalledTimes(1);
  });

  it('should call complete() with transformed data with a completion of get() call', () => {
    getSubject.next({
      query: {
        results: {
          quote: [{
            symbol: 'a',
            Name: 'a',
            Change: '0.3056',
            LastTradePriceOnly: '132.126464'
          }]
        }
      }
    });
    service.load([]);
    expect(service.complete).toHaveBeenCalledTimes(1);
    expect(service.complete).toHaveBeenCalledWith([{
      symbol: 'a',
      name: 'a',
      price: 132.126464,
      priceDisplay: '132.13',
      change: '+0.31',
      percentage: '+0.23%'
    }]);

    getSubject.next({
      query: {
        results: {
          quote: {
            symbol: 'a',
            Name: 'a',
            Change: '-0.3056',
            LastTradePriceOnly: '132.126464'
          }
        }
      }
    });
    expect(service.complete).toHaveBeenCalledTimes(2);
    expect(service.complete).toHaveBeenCalledWith([{
      symbol: 'a',
      name: 'a',
      price: 132.126464,
      priceDisplay: '132.13',
      change: '-0.31',
      percentage: '-0.23%'
    }]);

    getSubject.next({
      query: {
        results: {
          quote: {
            symbol: 'a',
            Name: 'a',
            LastTradePriceOnly: '132.126464'
          }
        }
      }
    });
    expect(service.complete).toHaveBeenCalledTimes(3);
    expect(service.complete).toHaveBeenCalledWith([{
      symbol: 'a',
      name: 'a',
      price: 132.126464,
      priceDisplay: '132.13',
      change: '0.00',
      percentage: '0.00%'
    }]);
  });

  it('should call load() when reload() is called', () => {
    spyOn(service, 'load');
    service.reload();
    expect(service.load).toHaveBeenCalledTimes(1);
    expect(service.load).toHaveBeenCalledWith([]);
  });
});


text:
'use strict';

import query from '../src/es6-query';
import $ from 'jquery';
import 'jasmine-jquery';

jasmine.getFixtures().fixturesPath = 'base/spec/fixtures';

describe('Toggle class on DOM element', () => {
	beforeEach(() => {
		loadFixtures('add.class.html');
	});

	it('should be able to add and remove a class on single element', () => {
		const spec = query('#spec-add-container').toggleClass('toggle-spec-class');

		expect($('#spec-add-container')).toHaveClass('toggle-spec-class');

		spec.toggleClass('toggle-spec-class');

		expect($('#spec-add-container')).not.toHaveClass('toggle-spec-class');
	});

	it('should be able to add and remove a class on multiple elements', () => {
		const spec = query('.spec-text').toggleClass('toggle-spec-class');

		expect(spec.length).toEqual(2);
		expect($('.toggle-spec-class').length).toEqual(2);

		spec.toggleClass('toggle-spec-class');

		expect($('.spec-text')).not.toHaveClass('toggle-spec-class');
		expect(query('.toggle-spec-class')[0]).toBeUndefined();
		expect(query('.toggle-spec-class').length).toEqual(0);
	});
});


text:
    #include "wx/fontutil.h"    // for wxNativeEncodingInfo
#endif // wxUSE_GUI

#if wxUSE_CONFIG && wxUSE_FILECONFIG
    class WXDLLIMPEXP_FWD_BASE wxConfigBase;
#endif // wxUSE_CONFIG

class WXDLLIMPEXP_FWD_CORE wxFontMapper;

#if wxUSE_GUI
    class WXDLLIMPEXP_FWD_CORE wxWindow;
#endif // wxUSE_GUI

// ============================================================================
// wxFontMapper manages user-definable correspondence between wxWidgets font
// encodings and the fonts present on the machine.
//
// This is a singleton class, font mapper objects can only be accessed using
// wxFontMapper::Get().
// ============================================================================

// ----------------------------------------------------------------------------
// wxFontMapperBase: this is a non-interactive class which just uses its built
//                   in knowledge of the encodings equivalence
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_BASE wxFontMapperBase
{
public:
    // constructor and such
    // ---------------------

    // default ctor
    wxFontMapperBase();

    // virtual dtor for any base class
    virtual ~wxFontMapperBase();

    // return instance of the wxFontMapper singleton
    // wxBase code only cares that it's a wxFontMapperBase
    // In wxBase, wxFontMapper is only forward declared
    // so one cannot implicitly cast from it to wxFontMapperBase.
    static wxFontMapperBase *Get();

    // set the singleton to 'mapper' instance and return previous one
    static wxFontMapper *Set(wxFontMapper *mapper);

    // delete the existing font mapper if any
    static void Reset();

    // translates charset strings to encoding
    // --------------------------------------

    // returns the encoding for the given charset (in the form of RFC 2046) or
    // wxFONTENCODING_SYSTEM if couldn't decode it
    //
    // interactive parameter is ignored in the base class, we behave as if it
    // were always false
    virtual wxFontEncoding CharsetToEncoding(const wxString& charset,
                                             bool interactive = true);

    // information about supported encodings
    // -------------------------------------

    // get the number of font encodings we know about
    static size_t GetSupportedEncodingsCount();

    // get the n-th supported encoding
    static wxFontEncoding GetEncoding(size_t n);

    // return canonical name of this encoding (this is a short string,
    // GetEncodingDescription() returns a longer one)
    static wxString GetEncodingName(wxFontEncoding encoding);

    // return a list of all names of this encoding (see GetEncodingName)
    static const wxChar** GetAllEncodingNames(wxFontEncoding encoding);

    // return user-readable string describing the given encoding
    //
    // NB: hard-coded now, but might change later (read it from config?)
    static wxString GetEncodingDescription(wxFontEncoding encoding);

    // find the encoding corresponding to the given name, inverse of
    // GetEncodingName() and less general than CharsetToEncoding()
    //
    // returns wxFONTENCODING_MAX if the name is not a supported encoding
    static wxFontEncoding GetEncodingFromName(const wxString& name);

    // functions which allow to configure the config object used: by default,
    // the global one (from wxConfigBase::Get() will be used) and the default
    // root path for the config settings is the string returned by
    // GetDefaultConfigPath()
    // ----------------------------------------------------------------------

#if wxUSE_CONFIG && wxUSE_FILECONFIG
    // set the root config path to use (should be an absolute path)
    void SetConfigPath(const wxString& prefix);

    // return default config path
    static const wxString& GetDefaultConfigPath();
#endif // wxUSE_CONFIG

    // returns true for the base class and false for a "real" font mapper object
    // (implementation-only)
    virtual bool IsDummy() { return true; }

protected:
#if wxUSE_CONFIG && wxUSE_FILECONFIG
    // get the config object we're using -- either the global config object
    // or a wxMemoryConfig object created by this class otherwise
    wxConfigBase *GetConfig();

    // gets the root path for our settings -- if it wasn't set explicitly, use
    // GetDefaultConfigPath()
    const wxString& GetConfigPath();

    // change to the given (relative) path in the config, return true if ok
    // (then GetConfig() will return something !NULL), false if no config
    // object
    //
    // caller should provide a pointer to the string variable which should be
    // later passed to RestorePath()
    bool ChangePath(const wxString& pathNew, wxString *pathOld);

    // restore the config path after use
    void RestorePath(const wxString& pathOld);

    // config object and path (in it) to use
    wxConfigBase *m_configDummy;

    wxString m_configRootPath;
#endif // wxUSE_CONFIG

    // the real implementation of the base class version of CharsetToEncoding()
    //
    // returns wxFONTENCODING_UNKNOWN if encoding is unknown and we shouldn't
    // ask the user about it, wxFONTENCODING_SYSTEM if it is unknown but we
    // should/could ask the user
    int NonInteractiveCharsetToEncoding(const wxString& charset);

private:
    // the global fontmapper object or NULL
    static wxFontMapper *sm_instance;

    friend class wxFontMapperPathChanger;

    wxDECLARE_NO_COPY_CLASS(wxFontMapperBase);
};

// ----------------------------------------------------------------------------
// wxFontMapper: interactive extension of wxFontMapperBase
//
// The default implementations of all functions will ask the user if they are
// not capable of finding the answer themselves and store the answer in a
// config file (configurable via SetConfigXXX functions). This behaviour may
// be disabled by giving the value of false to "interactive" parameter.
// However, the functions will always consult the config file to allow the
// user-defined values override the default logic and there is no way to
// disable this -- which shouldn't be ever needed because if "interactive" was
// never true, the config file is never created anyhow.
// ----------------------------------------------------------------------------

#if wxUSE_GUI

class WXDLLIMPEXP_CORE wxFontMapper : public wxFontMapperBase
{
public:
    // default ctor
    wxFontMapper();

    // virtual dtor for a base class
    virtual ~wxFontMapper();

    // working with the encodings
    // --------------------------

    // returns the encoding for the given charset (in the form of RFC 2046) or
    // wxFONTENCODING_SYSTEM if couldn't decode it
    virtual wxFontEncoding CharsetToEncoding(const wxString& charset,
                                             bool interactive = true);

    // find an alternative for the given encoding (which is supposed to not be
    // available on this system). If successful, return true and fill info
    // structure with the parameters required to create the font, otherwise
    // return false
    virtual bool GetAltForEncoding(wxFontEncoding encoding,
                                   wxNativeEncodingInfo *info,
                                   const wxString& facename = wxEmptyString,
                                   bool interactive = true);

    // version better suitable for 'public' use. Returns wxFontEcoding
    // that can be used it wxFont ctor
    bool GetAltForEncoding(wxFontEncoding encoding,
                           wxFontEncoding *alt_encoding,
                           const wxString& facename = wxEmptyString,
                           bool interactive = true);

    // checks whether given encoding is available in given face or not.
    //
    // if no facename is given (default), return true if it's available in any
    // facename at alll.
    virtual bool IsEncodingAvailable(wxFontEncoding encoding,
                                     const wxString& facename = wxEmptyString);

    // configure the appearance of the dialogs we may popup
    // ----------------------------------------------------

    // the parent window for modal dialogs
    void SetDialogParent(wxWindow *parent) { m_windowParent = parent; }

    // the title for the dialogs (note that default is quite reasonable)
    void SetDialogTitle(const wxString& title) { m_titleDialog = title; }

    // GUI code needs to know it's a wxFontMapper because there
    // are additional methods in the subclass.
    static wxFontMapper *Get();

    // pseudo-RTTI since we aren't a wxObject.
    virtual bool IsDummy() { return false; }

protected:
    // GetAltForEncoding() helper: tests for the existence of the given
    // encoding and saves the result in config if ok - this results in the
    // following (desired) behaviour: when an unknown/unavailable encoding is
    // requested for the first time, the user is asked about a replacement,
    // but if he doesn't choose any and the default logic finds one, it will
    // be saved in the config so that the user won't be asked about it any
    // more
    bool TestAltEncoding(const wxString& configEntry,
                         wxFontEncoding encReplacement,
                         wxNativeEncodingInfo *info);

    // the title for our dialogs
    wxString m_titleDialog;

    // the parent window for our dialogs
    wxWindow *m_windowParent;

private:
    wxDECLARE_NO_COPY_CLASS(wxFontMapper);
};

#endif // wxUSE_GUI

// ----------------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------------

// the default font mapper for wxWidgets programs do NOT use! This is for
// backward compatibility, use wxFontMapper::Get() instead
#define wxTheFontMapper (wxFontMapper::Get())

#else // !wxUSE_FONTMAP

#if wxUSE_GUI
    // wxEncodingToCodepage (utils.cpp) needs wxGetNativeFontEncoding
    #include "wx/fontutil.h"
#endif

#endif // wxUSE_FONTMAP/!wxUSE_FONTMAP

#endif // _WX_FONTMAPPER_H_


text:
package seedu.flexitrack.logic;

import javafx.collections.ObservableList;
import seedu.flexitrack.logic.commands.CommandResult;
import seedu.flexitrack.model.task.ReadOnlyTask;

/**
 * API of the Logic component
 */
public interface Logic {
    /**
     * Executes the command and returns the result.
     *
     * @param commandText
     *            The command as entered by the user.
     * @return the result of the command execution.
     */
    CommandResult execute(String commandText);

    /** Returns the filtered list of persons */
    ObservableList<ReadOnlyTask> getFilteredTaskList();

}


text:
#ifndef TENSORFLOW_C_EAGER_PARALLEL_DEVICE_PARALLEL_DEVICE_TESTLIB_H_
#define TENSORFLOW_C_EAGER_PARALLEL_DEVICE_PARALLEL_DEVICE_TESTLIB_H_

#include <array>

#include "tensorflow/c/c_api.h"
#include "tensorflow/c/c_api_experimental.h"
#include "tensorflow/c/eager/c_api.h"
#include "tensorflow/c/eager/c_api_experimental.h"
#include "tensorflow/c/eager/parallel_device/parallel_device.h"
#include "tensorflow/c/eager/parallel_device/parallel_device_lib.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace parallel_device {

// A helper for performing common operations on variables. A much more
// restricted stand-in for tf.Variable in Python.
class Variable {
 public:
  // Construct a Variable from a resource-dtype TFE_TensorHandle and an
  // indication of the dtype of the variable's value.
  //
  // Note that creating this resource-dtype handle can fail, so `Create` is a
  // separate static method which returns a status.
  Variable(TFE_TensorHandle* handle, TF_DataType type)
      : handle_(handle), type_(type) {}

  // Helper for constructing a resource handle and wrapping it in a `Variable`
  // object.
  static Variable* Create(TFE_Context* context, TF_DataType type,
                          const int64_t* dims, const int num_dims,
                          const char* device, TF_Status* status);
  // Dereferences the backing buffer for the variable. Note that since this can
  // fail (it runs operations), it must be called explicitly and the resulting
  // `status` checked.
  void Destroy(TFE_Context* context, TF_Status* status);

  // Reads from the variable.
  TensorHandlePtr Read(TFE_Context* context, TF_Status* status);
  // Assigns a new value to the variable.
  void Assign(TFE_Context* context, TFE_TensorHandle* value, TF_Status* status);
  // Adds `value` to the existing value of the variable.
  void AssignAdd(TFE_Context* context, TFE_TensorHandle* value,
                 TF_Status* status);

 private:
  // Helper for running any single-argument assignment ops (Assign, AssignAdd,
  // AssignSub, ...).
  void GeneralAssignment(const char* op_name, TFE_Context* context,
                         TFE_TensorHandle* value, TF_Status* status);

  // The a handle for the resource-dtype tensor pointing to the variable's
  // buffer.
  TFE_TensorHandle* handle_;
  // The dtype of the variable's buffer (input dtype for assignments, output
  // dtype of read operations).
  TF_DataType type_;
};

// Creates a TFE_TensorHandle with value `v`.
TensorHandlePtr FloatTensorHandle(float v, TF_Status* status);

// Creates a rank-one TFE_TensorHandle with value `v`.
TensorHandlePtr VectorFloatTensorHandle(const std::vector<float>& v,
                                        TF_Status* status);

// Helper to un-pack `num_replicas` TFE_TensorHandles from one parallel handle.
template <std::size_t num_replicas>
void ExtractPerDeviceValues(
    TFE_Context* context, TFE_TensorHandle* input,
    std::array<TensorHandlePtr, num_replicas>* components, TF_Status* status);

// Helper to pack `num_replicas` TFE_TensorHandles into one parallel handle.
template <std::size_t num_replicas>
TensorHandlePtr CreatePerDeviceValues(
    TFE_Context* context,
    const std::array<TFE_TensorHandle*, num_replicas>& components,
    const char* device, TF_Status* status);

TensorHandlePtr Multiply(TFE_Context* context, TFE_TensorHandle* first,
                         TFE_TensorHandle* second, TF_Status* status);

// Assert that `handle` is equal to `expected_value`.
template <typename value_type>
void ExpectScalarEq(TFE_TensorHandle* handle, value_type expected_value);

template <std::size_t num_devices>
void RegisterParallelDevice(
    TFE_Context* context, const char* device_name,
    const std::array<const char*, num_devices>& underlying_devices,
    TF_Status* status);

// Create and modify a variable placed on a parallel device which composes
// `first_device` and `second_device`.
void BasicTestsForTwoDevices(TFE_Context* context, const char* first_device,
                             const char* second_device);

// Implementations of templated functions ******************************

template <std::size_t num_replicas>
TensorHandlePtr CreatePerDeviceValues(
    TFE_Context* context,
    const std::array<TFE_TensorHandle*, num_replicas>& components,
    const char* device, TF_Status* status) {
  std::unique_ptr<TFE_Op, decltype(&TFE_DeleteOp)> op(
      TFE_NewOp(context, "TPUReplicatedInput", status), TFE_DeleteOp);
  if (TF_GetCode(status) != TF_OK) return nullptr;
  TFE_OpSetAttrInt(op.get(), "N", num_replicas);
  for (int i = 0; i < num_replicas; ++i) {
    TFE_OpAddInput(op.get(), components[i], status);
    if (TF_GetCode(status) != TF_OK) return nullptr;
  }
  TFE_OpSetDevice(op.get(), device, status);
  if (TF_GetCode(status) != TF_OK) return nullptr;

  TFE_TensorHandle* result_handle;
  int num_retvals = 1;
  TFE_Execute(op.get(), &result_handle, &num_retvals, status);
  if (TF_GetCode(status) != TF_OK) return nullptr;
  return TensorHandlePtr(result_handle);
}

template <typename value_type>
void ExpectScalarEq(TFE_TensorHandle* handle, value_type expected_value) {
  std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
      TF_NewStatus(), TF_DeleteStatus);
  std::unique_ptr<TF_Tensor, decltype(&TF_DeleteTensor)> actual_value(
      TFE_TensorHandleResolve(handle, status.get()), TF_DeleteTensor);
  ASSERT_EQ(TF_GetCode(status.get()), TF_OK) << TF_Message(status.get());
  ASSERT_EQ(TF_TensorType(actual_value.get()),
            static_cast<TF_DataType>(DataTypeToEnum<value_type>().value));
  EXPECT_EQ(expected_value,
            *static_cast<value_type*>(TF_TensorData(actual_value.get())));
}

template <std::size_t num_devices>
void RegisterParallelDevice(
    TFE_Context* context, const char* device_name,
    const std::array<const char*, num_devices>& underlying_devices,
    TF_Status* status) {
  TFE_CustomDevice device;
  void* device_info;
  tensorflow::parallel_device::AllocateParallelDevice(
      device_name, underlying_devices.data(), underlying_devices.size(),
      &device, &device_info);
  TFE_RegisterCustomDevice(context, device, device_name, device_info, status);
}

}  // namespace parallel_device
}  // namespace tensorflow

#endif  // TENSORFLOW_C_EAGER_PARALLEL_DEVICE_PARALLEL_DEVICE_TESTLIB_H_


text:
#ifndef SWITCH_D_H
#define SWITCH_D_H

#include <iostream>

#include "mem/ruby/network/garnet/NetworkHeader.hh"
#include "mem/ruby/common/Consumer.hh"
#include "mem/ruby/network/garnet/fixed-pipeline/flitBuffer_d.hh"

class Router_d;
class OutputUnit_d;

class Switch_d : public Consumer {
public:
        Switch_d(Router_d *router);
        ~Switch_d();
        void wakeup();
        void init();
        void check_for_wakeup();
        void print(std::ostream& out) const {};
        inline void update_sw_winner(int inport, flit_d *t_flit)
        {
                m_switch_buffer[inport]->insert(t_flit);
        }
        inline double get_crossbar_count()
        {
                return m_crossbar_activity;
        }

private:
        int m_num_vcs;
        int m_num_inports;
        double m_crossbar_activity;
        Router_d *m_router;
        Vector<flitBuffer_d *> m_switch_buffer;
        Vector<OutputUnit_d *> m_output_unit;
};

#endif


text:
Record some niubility code.

## Equality(==)

```js
if([]) console.log(123)
//123
if(![]) console.log(123)
//undefined
console.log([] == ![])
//true
```
In [developer.mozilla.org](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
>The equality operator converts the operands if they are **not of the same type**, then applies strict comparison. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

No more info we could get from it.
### First ([] == false)
In [Ecma International, 11.9.3 The Abstract Equality Comparison Algorithm](http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3) :
>If Type(y) is Boolean, return the result of the comparison x == ToNumber(y)

Obviously, The above-mentioned `([]==![])` is the same as point 7, cause `![]` is type of boolean. But what is `ToNumber` mean ? In [Ecma International, 9.3 ToNumber](http://www.ecma-international.org/ecma-262/5.1/#sec-9.3) , when the argument type is boolean:
> The result is 1 if the argument is true. The result is +0 if the argument is false.

So, in other words, that mean `([]==![])`(also is `([] == false)`) will be converted to `([] == +0)`.

### Second ([] == +0)
Review the [Ecma International, 11.9.3 The Abstract Equality Comparison Algorithm](http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3) :

>If Type(x) is Object and Type(y) is either String or Number,return the result of the comparison ToPrimitive(x) == y.

Absolutely, `([] == +0)` fit it. Here is the description of `ToPrimitive`

>Return a default value for the Object. The default value of an object is retrieved by calling the `[[DefaultValue]]` internal method of the object, passing the optional hint PreferredType. The behaviour of the `[[DefaultValue]]` internal method is defined by this specification for all native ECMAScript objects in 8.12.8.

Then we go and see what is the `[[DefaultValue]]` :
> When the [[DefaultValue]] internal method of O is called with hint String, the following steps are taken:
> 1. Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".
> 2. If IsCallable(toString) is true then,
>    1. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.
>    2. If str is a primitive value, return str.

So, in other words, that mean `([] == +0)` will be converted as below
```js
//1.
if([].toString)
    //2.1
    let str = [].toString()
    //2.2
    if(['undefined','null','boolean','number','string'].indexOf(typeof str) > -1)
        return str
```
As you see, the `([]==+0)` is converted to `(''==+0)`.
### Finally ('' == +0)
Review the [Ecma International, 11.9.3 The Abstract Equality Comparison Algorithm](http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3) point 5:
>If Type(x) is String and Type(y) is Number,return the result of the comparison ToNumber(x) == y.

In [Ecma International, 9.3 ToNumber](http://www.ecma-international.org/ecma-262/5.1/#sec-9.3) , when the argument type is string:
> The result is 1 if the argument is true. The result is +0 if the argument is false.

So long... In one word, `''` will return `0`(as below)
```js
Number('')
//0
```
That's all the reason why the comparison of `(0==0)` will return true.
## Array initialization

Init an array with { number : 1 },{ number : 2}.....{ number : 10}
```js
    // in normal way
    var arr = [{ number : 1 },
               { number : 2 },
               { number : 3 },
               { number : 4 },
               { number : 5 },
               { number : 6 },
               { number : 7 },
               { number : 8 },
               { number : 9 },
               { number : 10}]

    // in smart way

    var brr = [];
    for(var i=0;i < 10;i++){
        brr.push({number:i+1})
    }
```
Well, if you want to zhuangbility, you may like this one.
```js
    var arr = [...Array(10)].map((v,i)=>({number:i+1}))
```

## Object copying

```js
    var obj = {
        number : 1,
        type : 'text',
        subs : [1,2,3,4,5]
        //so on...
    }

    // width jq
    var newObj = $.extend({},obj);

    // widthout jq
    //We need to go through all the node of obj (use for..in.. )

```

In zhuangbility way

```js
    var newObj = JSON.parse(JSON.stringify(obj))
```

## Asynchronous requests

```js
	// write in js without jq make me sick
	var xmlhttp;
	if (window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else {
		// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
		}
	}
	xmlhttp.open("GET","/ajax/demo_get.asp",true);
	xmlhttp.send();

	// width jq
	// in much better way by using defered
	var deferred = jQuery.Deferred();
	deferred.then(function() {
	  console.log("first callback");
	  throw new Error("error in callback");
	})
	.then(function() {
	  console.log("second callback");
	}, function(err) {
	  console.log("rejection callback", err instanceof Error);
	});
	deferred.resolve();

```

In zhuangbility way

```js
	// fetch is still an experimental technology, so you should use babel first
	fetch("/submit", {
		method: "POST",
		headers: {
			"Content-Type": "application/x-www-form-urlencoded"
		},
		body: "firstName=Nikhil&favColor=blue&password=easytoguess"
	})
	.then(function(res) {
		// on response
	}, function(err) {
		// on error
	});

```

In more zhuangbility way. Use `then(fn).catch(fn)` is equal to `then(fn).then(null, fn)`, but `catch` make your code more clear than before.

```js
	// fetch is still an experimental technology, so you should use babel first
	fetch("/submit", {
		method: "POST",
		headers: {
			"Content-Type": "application/x-www-form-urlencoded"
		},
		body: "firstName=Nikhil&favColor=blue&password=easytoguess"
	})
	.then(function(res) {
		// on response
	})
	.catch(function(err) {
		// on error
	})
```
### Type checking

```js
	var someFn = function(){}
	//type checking
	if(typeof someFn === 'function'){
		//do something here
	}

```

In zhuangbility way

```js
	var someFn = function(){}
	var isFunction = {
		'function': true
	}
	if(isFunction[typeof someFn]){
		//do something here
	}
```


text:
.. include:: ../README.rst

User's Guide
~~~~~~~~~~~~

.. toctree::
  :maxdepth: 2

  basics
  database
  subgraph
  asyncio
  graphql
  protobuf
  reference/index
  changelog/index


text:
package internal

import (
	"errors"
	"fmt"
	"github.com/jdextraze/go-gesclient/client"
	"github.com/jdextraze/go-gesclient/log"
	"github.com/jdextraze/go-gesclient/subscriptions"
	"github.com/jdextraze/go-gesclient/tasks"
	"github.com/satori/go.uuid"
	"net"
	"reflect"
	"sync/atomic"
	"time"
)

type ConnectionLogicHandler interface {
	TotalOperationCount() int
	EnqueueMessage(msg message) error
	Connected() client.EventHandlers
	Disconnected() client.EventHandlers
	Reconnecting() client.EventHandlers
	Closed() client.EventHandlers
	ErrorOccurred() client.EventHandlers
	AuthenticationFailed() client.EventHandlers
}

type heartbeatInfo struct {
	LastPackageNumber int
	IsIntervalStage   bool
	Timestamp         time.Duration
}

type reconnectionInfo struct {
	ReconnectionAttempt int
	Timestamp           time.Duration
}

type authInfo struct {
	CorrelationId uuid.UUID
	Timestamp     time.Duration
}

type connectionState int

const (
	connectionState_Init connectionState = iota
	connectionState_Connecting
	connectionState_Connected
	connectionState_Closed
)

var connectionState_values = []string{
	"Init",
	"Connecting",
	"Connected",
	"Closed",
}

func (s connectionState) String() string {
	return connectionState_values[s]
}

type connectingPhase int

const (
	connectingPhase_Invalid connectingPhase = iota
	connectingPhase_Reconnecting
	connectingPhase_EndpointDiscovery
	connectingPhase_ConnectionEstablishing
	connectingPhase_Authentication
	connectingPhase_Connected
)

type connectionLogicHandler struct {
	connected             *eventHandlers
	disconnected          *eventHandlers
	reconnecting          *eventHandlers
	closed                *eventHandlers
	errorOccurred         *eventHandlers
	authenticationFailed  *eventHandlers
	esConnection          client.Connection
	settings              *client.ConnectionSettings
	queue                 *simpleQueuedHandler
	timer                 *time.Ticker
	endpointDiscoverer    EndpointDiscoverer
	startTime             time.Time
	reconInfo             reconnectionInfo
	heartbeatInfo         heartbeatInfo
	authInfo              authInfo
	lastTimeoutsTimestamp time.Duration
	operations            *OperationsManager
	subscriptions         *SubscriptionsManager
	state                 connectionState
	connectingPhase       connectingPhase
	wasConnected          int32
	packageNumber         int
	connection            *client.PackageConnection
}

func NewConnectionLogicHandler(
	connection client.Connection,
	settings *client.ConnectionSettings,
) *connectionLogicHandler {
	if connection == nil {
		panic("connection is nil")
	}
	if settings == nil {
		panic("settings is nil")
	}

	queue := newSimpleQueuedHandler()

	obj := &connectionLogicHandler{
		connected:            newEventHandlers(),
		disconnected:         newEventHandlers(),
		reconnecting:         newEventHandlers(),
		closed:               newEventHandlers(),
		errorOccurred:        newEventHandlers(),
		authenticationFailed: newEventHandlers(),
		esConnection:         connection,
		settings:             settings,
		queue:                queue,
		startTime:            time.Now(),
		operations:           NewOperationsManager(connection.Name(), settings),
		subscriptions:        NewSubscriptionManager(connection.Name(), settings),
		connectingPhase:      connectingPhase_Invalid,
	}

	queue.RegisterHandler(&startConnectionMessage{}, obj.startConnection)
	queue.RegisterHandler(&closeConnectionMessage{}, obj.closeConnection)

	queue.RegisterHandler(&startOperationMessage{}, obj.startOperation)
	queue.RegisterHandler(&startSubscriptionMessage{}, obj.startSubscription)
	queue.RegisterHandler(&startPersistentSubscriptionMessage{}, obj.startPersistentSubscription)

	queue.RegisterHandler(&establishTcpConnectionMessage{}, obj.establishTcpConnection)
	queue.RegisterHandler(&tcpConnectionEstablishedMessage{}, obj.tcpConnectionEstablished)
	queue.RegisterHandler(&tcpConnectionErrorMessage{}, obj.tcpConnectionError)
	queue.RegisterHandler(&tcpConnectionClosedMessage{}, obj.tcpConnectionClosed)
	queue.RegisterHandler(&handleTcpPackageMessage{}, obj.handleTcpPackage)

	queue.RegisterHandler(&timerTickMessage{}, obj.timerTick)

	obj.timer = time.NewTicker(client.TimerPeriod)
	go func() {
		for range obj.timer.C {
			obj.EnqueueMessage(&timerTickMessage{})
		}
	}()

	return obj
}

func (h *connectionLogicHandler) TotalOperationCount() int {
	return h.operations.TotalOperationCount()
}

func (h *connectionLogicHandler) EnqueueMessage(msg message) error {
	_, isTimerTickMessage := msg.(*timerTickMessage)
	if h.settings.VerboseLogging() && !isTimerTickMessage {
		log.Debugf("enqueuing message %s", reflect.TypeOf(msg))
	}
	return h.queue.EnqueueMessage(msg)
}

func (h *connectionLogicHandler) startConnection(msg message) error {
	startConnectionMessage := msg.(*startConnectionMessage)
	if startConnectionMessage.task == nil {
		panic("startConnectionMessage.resultChannel is nil")
	}
	if startConnectionMessage.endpointDiscoverer == nil {
		panic("startConnectionMessage.endpointDiscoverer is nil")
	}
	log.Debug("Start connection")
	switch h.state {
	case connectionState_Init:
		h.endpointDiscoverer = startConnectionMessage.endpointDiscoverer
		h.state = connectionState_Connecting
		h.connectingPhase = connectingPhase_Reconnecting
		h.discoverEndpoint(startConnectionMessage.task)
		return nil
	case connectionState_Connecting, connectionState_Connected:
		return startConnectionMessage.task.SetError(fmt.Errorf(
			"EventStoreConnection '%s' is already active", h.esConnection.Name()))
	case connectionState_Closed:
		return startConnectionMessage.task.SetError(fmt.Errorf(
			"EventStoreConnection '%s' is closed", h.esConnection.Name()))
	default:
		return fmt.Errorf("Unknown state '%v'", h.state)
	}
}

func (h *connectionLogicHandler) discoverEndpoint(task *tasks.CompletionSource) {
	log.Debug("Discover endpoint")

	if h.state != connectionState_Connecting {
		return
	}
	if h.connectingPhase != connectingPhase_Reconnecting {
		return
	}

	h.connectingPhase = connectingPhase_EndpointDiscovery

	var remoteEndpoint net.Addr
	if h.connection != nil {
		remoteEndpoint = h.connection.RemoteEndpoint()
	}
	h.endpointDiscoverer.DiscoverAsync(remoteEndpoint).ContinueWith(func(t *tasks.Task) (interface{}, error) {
		if t.IsFaulted() {
			h.EnqueueMessage(newCloseConnectionMessage(
				"Failed to resolve TCP end point to which to connect.",
				t.Error(),
			))
			if task != nil {
				task.SetError(fmt.Errorf("Cannot resolve target endpoint"))
			}
		} else {
			nodeEndpoints := t.Result().(*NodeEndpoints)
			h.EnqueueMessage(newEstablishTcpConnectionMessage(nodeEndpoints))
			if task != nil {
				task.SetResult(nil)
			}
		}
		return nil, nil
	})
}

func (h *connectionLogicHandler) closeConnection(msg message) error {
	m := msg.(*closeConnectionMessage)

	if h.state == connectionState_Closed {
		log.Debugf("CloseConnection IGNORED because is ESConnection is CLOSED, reason %s, exception %v.",
			m.reason, m.error)
		return nil
	}

	log.Debugf("CloseConnection, reason %s, exception %v.", m.reason, m.error)

	h.state = connectionState_Closed

	h.timer.Stop()
	h.timer = nil
	if err := h.operations.CleanUp(); err != nil {
		return err
	}
	if err := h.subscriptions.CleanUp(); err != nil {
		return err
	}
	h.closeTcpConnection(m.reason)

	log.Infof("Closed. Reason: %s", m.reason)

	if m.error != nil {
		h.raiseErrorOccurred(m.error)
	}

	h.raiseClosed(m.reason)

	return nil
}

func (h *connectionLogicHandler) closeTcpConnection(reason string) {
	if h.connection == nil {
		log.Debug("CloseTcpConnection IGNORED because _connection == null")
		return
	}

	log.Debug("CloseTcpConnection")
	h.connection.Close(reason)
	h.tcpConnectionClosed(newTcpConnectionClosedMessage(h.connection, nil))
	h.connection = nil
}

func (h *connectionLogicHandler) startOperation(msg message) error {
	m := msg.(*startOperationMessage)

	switch h.state {
	case connectionState_Init:
		return m.operation.Fail(fmt.Errorf("EventStoreConnection '%s' is not active", h.esConnection.Name()))
	case connectionState_Connecting:
		log.Debugf("StartOperation enqueue %s, %d, %s", m.operation, m.maxRetries, m.timeout)
		return h.operations.EnqueueOperation(newOperationItem(m.operation, m.maxRetries, m.timeout))
	case connectionState_Connected:
		log.Debugf("StartOperation schedule %s, %d, %s", m.operation, m.maxRetries, m.timeout)
		return h.operations.ScheduleOperation(newOperationItem(m.operation, m.maxRetries, m.timeout), h.connection)
	case connectionState_Closed:
		return m.operation.Fail(fmt.Errorf("Connection %s is closed", h.esConnection.Name()))
	default:
		return fmt.Errorf("Unknown state: %s", h.state)
	}
}

func (h *connectionLogicHandler) startSubscription(msg message) error {
	m := msg.(*startSubscriptionMessage)

	switch h.state {
	case connectionState_Init:
		return m.source.SetError(fmt.Errorf("EventStoreConnection '%s' is not active.", h.esConnection.Name()))
	case connectionState_Connecting, connectionState_Connected:
		operation := subscriptions.NewVolatileSubscription(m.source, m.streamId, m.resolveLinkTos,
			m.userCredentials, m.eventAppeared, m.subscriptionDropped, h.settings.VerboseLogging(),
			func() (*client.PackageConnection, error) { return h.connection, nil })
		var state string
		if h.state == connectionState_Connected {
			state = "fire"
		} else {
			state = "enqueue"
		}
		log.Debugf("StartSubscription %s %s, %d, %s", state, operation, m.maxRetries, m.timeout)
		subscription := NewSubscriptionItem(operation, m.maxRetries, m.timeout)
		if h.state == connectionState_Connecting {
			h.subscriptions.EnqueueSubscription(subscription)
		} else {
			h.subscriptions.StartSubscription(subscription, h.connection)
		}
		return nil
	case connectionState_Closed:
		return m.source.SetError(fmt.Errorf("Object disposed: %s", h.esConnection.Name()))
	default:
		return fmt.Errorf("Unknown state: %s", h.state)
	}
}

func (h *connectionLogicHandler) startPersistentSubscription(msg message) error {
	m := msg.(*startPersistentSubscriptionMessage)
	switch h.state {
	case connectionState_Init:
		return m.source.SetError(fmt.Errorf("EventStoreConnection '%s' is not active.", h.esConnection.Name()))
	case connectionState_Connecting, connectionState_Connected:
		operation := subscriptions.NewConnectToPersistentSubscription(m.source, m.subscriptionId,
			m.bufferSize, m.streamId, m.userCredentials, m.eventAppeared, m.subscriptionDropped,
			h.settings.VerboseLogging(), func() (*client.PackageConnection, error) { return h.connection, nil })
		log.Debugf("StartSubscription %s %s, %d, %s", h.state, operation, m.maxRetries, m.timeout)
		subscription := NewSubscriptionItem(operation, m.maxRetries, m.timeout)
		if h.state == connectionState_Connecting {
			h.subscriptions.EnqueueSubscription(subscription)
		} else {
			h.subscriptions.StartSubscription(subscription, h.connection)
		}
		return nil
	case connectionState_Closed:
		return m.source.SetError(fmt.Errorf("Object disposed: %s", h.esConnection.Name()))
	default:
		return fmt.Errorf("Unknown state: %s", h.state)
	}
}

func (h *connectionLogicHandler) establishTcpConnection(msg message) error {
	establishTcpConnection := msg.(*establishTcpConnectionMessage)
	var tcpEndpoint net.Addr
	if h.settings.UseSslConnection() {
		if establishTcpConnection.endpoints.secureTcpEndpoint == nil {
			tcpEndpoint = establishTcpConnection.endpoints.tcpEndpoint
		} else {
			tcpEndpoint = establishTcpConnection.endpoints.secureTcpEndpoint
		}
	} else {
		tcpEndpoint = establishTcpConnection.endpoints.tcpEndpoint
	}
	if tcpEndpoint == nil {
		h.closeConnection(newCloseConnectionMessage("No endpoint to node specified.", nil))
	}
	if h.state != connectionState_Connecting {
		return nil
	}
	if h.connectingPhase != connectingPhase_EndpointDiscovery {
		return nil
	}
	h.connectingPhase = connectingPhase_ConnectionEstablishing
	h.connection = client.NewPackageConnection(tcpEndpoint, uuid.Must(uuid.NewV4()), h.settings.UseSslConnection(),
		h.settings.TargetHost(), h.settings.ValidateService(), h.settings.ClientConnectionTimeout(),
		func(c *client.PackageConnection, p *client.Package) {
			h.EnqueueMessage(newHandleTcpPackageMessage(c, p))
		},
		func(c *client.PackageConnection, err error) {
			h.EnqueueMessage(newTcpConnectionErrorMessage(c, err))
		},
		func(c *client.PackageConnection) {
			h.EnqueueMessage(newTcpConnectionEstablishedMessage(c))
		},
		func(c *client.PackageConnection, err error) {
			h.EnqueueMessage(newTcpConnectionClosedMessage(c, err))
		},
	)
	return h.connection.StartReceiving()
}

func (h *connectionLogicHandler) elapsedTime() time.Duration {
	return time.Now().Sub(h.startTime)
}

func (h *connectionLogicHandler) tcpConnectionEstablished(msg message) error {
	m := msg.(*tcpConnectionEstablishedMessage)
	if h.state != connectionState_Connecting || h.connection != m.connection || m.connection.IsClosed() {
		log.Debugf("")
		return nil
	}

	h.heartbeatInfo = heartbeatInfo{h.packageNumber, true, h.elapsedTime()}

	if h.settings.DefaultUserCredentials != nil {
		h.connectingPhase = connectingPhase_Authentication
		h.authInfo = authInfo{uuid.Must(uuid.NewV4()), h.elapsedTime()}
		return h.connection.EnqueueSend(client.NewTcpPackage(
			client.Command_Authenticate,
			client.FlagsAuthenticated,
			h.authInfo.CorrelationId,
			nil,
			h.settings.DefaultUserCredentials,
		))
	}
	return h.goToConnectedState()
}

func (h *connectionLogicHandler) goToConnectedState() error {
	h.state = connectionState_Connected
	h.connectingPhase = connectingPhase_Connected

	atomic.CompareAndSwapInt32(&h.wasConnected, 0, 1)

	h.raiseConnected(h.connection.RemoteEndpoint())

	if h.elapsedTime()-h.lastTimeoutsTimestamp >= h.settings.OperationTimeoutCheckPeriod() {
		if err := h.operations.CheckTimeoutsAndRetry(h.connection); err != nil {
			return err
		}
		if err := h.subscriptions.CheckTimeoutsAndRetry(h.connection); err != nil {
			return err
		}
		h.lastTimeoutsTimestamp = h.elapsedTime()
	}
	return nil
}

func (h *connectionLogicHandler) tcpConnectionError(msg message) error {
	m := msg.(*tcpConnectionErrorMessage)
	if h.connection != m.connection {
		return nil
	}
	if h.state == connectionState_Closed {
		return nil
	}
	log.Debugf("TcpConnectionError connId %s, exc %v", m.connection.ConnectionId(), m.error)
	return h.closeConnection(newCloseConnectionMessage("TCP connection error occurred.", m.error))
}

func (h *connectionLogicHandler) tcpConnectionClosed(msg message) error {
	m := msg.(*tcpConnectionClosedMessage)
	if h.state == connectionState_Init {
		return errors.New(":|")
	}
	if h.state == connectionState_Closed || h.connection != m.connection {
		var cid uuid.UUID
		if h.connection != nil {
			cid = h.connection.ConnectionId()
		}
		log.Debugf("IGNORED (_state: %s, _conn.ID: %s, conn.ID: %s: TCP connection to [%s, L%s] closed.",
			h.state, cid, m.connection.ConnectionId(), m.connection.RemoteEndpoint(), m.connection.LocalEndpoint())
		return nil
	}

	h.state = connectionState_Connecting
	h.connectingPhase = connectingPhase_Reconnecting

	log.Debugf("TCP connection to [%s, L%s, %s closed.", m.connection.RemoteEndpoint(),
		m.connection.LocalEndpoint(), m.connection.ConnectionId())

	h.subscriptions.PurgeSubscribedAndDroppedSubscriptions(h.connection.ConnectionId())
	h.reconInfo = reconnectionInfo{h.reconInfo.ReconnectionAttempt, h.elapsedTime()}

	if !atomic.CompareAndSwapInt32(&h.wasConnected, 1, 0) {
		h.raiseDisconnected(m.connection.RemoteEndpoint())
	}

	return nil
}

func (h *connectionLogicHandler) handleTcpPackage(msg message) error {
	m := msg.(*handleTcpPackageMessage)
	command := m.pkg.Command()
	correlationId := m.pkg.CorrelationId()

	if h.connection != m.connection || h.state == connectionState_Closed || h.state == connectionState_Init {
		log.Debugf("IGNORED: HandleTcpPackage connId %s, package %s, %s.", m.connection.ConnectionId(),
			command, correlationId)
		return nil
	}

	log.Debugf("HandleTcpPackage connId %s, package %s, %s.", m.connection.ConnectionId(), command,
		correlationId)
	h.packageNumber += 1

	if command == client.Command_HeartbeatResponseCommand {
		return nil
	}
	if command == client.Command_HeartbeatRequestCommand {
		return h.connection.EnqueueSend(client.NewTcpPackage(client.Command_HeartbeatResponseCommand, client.FlagsNone,
			correlationId, nil, nil))
	}

	if command == client.Command_Authenticated || command == client.Command_NotAuthenticated {
		if h.state == connectionState_Connecting &&
			h.connectingPhase == connectingPhase_Authentication &&
			h.authInfo.CorrelationId == correlationId {
			if command == client.Command_NotAuthenticated {
				h.raiseAuthFailed("Not authenticated")
			}
			h.goToConnectedState()
			return nil
		}
	}

	if command == client.Command_BadRequest && correlationId == uuid.Nil {
		message := string(m.pkg.Data())
		if message == "" {
			message = "<no message>"
		}
		return h.closeConnection(newCloseConnectionMessage(
			"Connection-wide bad request received. Too dangerous to continue.",
			fmt.Errorf("Bad request received from server. Error: %s", message),
		))
	}

	if found, operation := h.operations.TryGetActiveOperation(correlationId); found {
		result, err := operation.operation.InspectPackage(m.pkg)
		if err != nil {
			return err
		}
		log.Debugf("HandleTcpPackage OPERATION DECISION %s (%s), %s", result.Decision(), result.Description(),
			operation)
		switch result.Decision() {
		case client.InspectionDecision_DoNothing:
			break
		case client.InspectionDecision_EndOperation:
			h.operations.RemoveOperation(operation)
		case client.InspectionDecision_Retry:
			if err := h.operations.ScheduleOperationRetry(operation); err != nil {
				return err
			}
		case client.InspectionDecision_Reconnect:
			h.reconnectTo(NewNodeEndpoints(result.TcpEndpoint(), result.SecureTcpEndpoint()))
			if err := h.operations.ScheduleOperationRetry(operation); err != nil {
				return err
			}
		default:
			return fmt.Errorf("Unknown InspectionDecision: %s", result.Decision())
		}
		if h.state == connectionState_Connected {
			return h.operations.TryScheduleWaitingOperations(m.connection)
		}
	} else if found, subscription := h.subscriptions.TryGetActiveSubscription(correlationId); found {
		result, err := subscription.Operation().InspectPackage(m.pkg)
		if err != nil {
			return err
		}
		log.Debugf("HandleTcpPackage SUBSCRIPTION DECISION %s (%s), %s", result.Decision(), result.Description(),
			subscription)
		switch result.Decision() {
		case client.InspectionDecision_DoNothing:
			break
		case client.InspectionDecision_EndOperation:
			h.subscriptions.RemoveSubscription(subscription)
		case client.InspectionDecision_Retry:
			h.subscriptions.ScheduleSubscriptionRetry(subscription)
		case client.InspectionDecision_Reconnect:
			h.reconnectTo(NewNodeEndpoints(result.TcpEndpoint(), result.SecureTcpEndpoint()))
			h.subscriptions.ScheduleSubscriptionRetry(subscription)
		case client.InspectionDecision_Subscribed:
			subscription.IsSubscribed = true
		default:
			return fmt.Errorf("Unknown InspectionDecision: %s", result.Decision())
		}
	}
	return nil
}

func (h *connectionLogicHandler) reconnectTo(endpoints *NodeEndpoints) {
	var endPoint net.Addr
	if h.settings.UseSslConnection() {
		if endpoints.SecureTcpEndpoint() == nil {
			endPoint = endpoints.TcpEndpoint()
		} else {
			endPoint = endpoints.SecureTcpEndpoint()
		}
	} else {
		endPoint = endpoints.TcpEndpoint()
	}
	if endPoint == nil {
		h.closeConnection(newCloseConnectionMessage("No end point is specified while trying to reconnect.", nil))
		return
	}
	if h.state != connectionState_Connected || h.connection.RemoteEndpoint().String() == endPoint.String() {
		return
	}
	msg := fmt.Sprintf("EventStoreConnection '%s': going to reconnect to [%s]. Current endpoint: [%s, L%s].",
		h.esConnection.Name(), endPoint, h.connection.RemoteEndpoint(), h.connection.LocalEndpoint())
	if h.settings.VerboseLogging() {
		log.Debug(msg)
	}
	h.closeTcpConnection(msg)

	h.state = connectionState_Connecting
	h.connectingPhase = connectingPhase_EndpointDiscovery
	h.establishTcpConnection(newEstablishTcpConnectionMessage(endpoints))
}

func (h *connectionLogicHandler) timerTick(msg message) error {
	switch h.state {
	case connectionState_Init:
		return nil
	case connectionState_Connecting:
		if h.connectingPhase == connectingPhase_Reconnecting && h.elapsedTime()-h.reconInfo.Timestamp >= h.settings.ReconnectionDelay() {
			log.Debug("TimerTick checking reconnection")

			h.reconInfo = reconnectionInfo{h.reconInfo.ReconnectionAttempt + 1, h.elapsedTime()}
			if h.settings.MaxReconnections() >= 0 && h.reconInfo.ReconnectionAttempt > h.settings.MaxReconnections() {
				h.closeConnection(newCloseConnectionMessage("Reconnection limit reached.", nil))
			} else {
				h.raiseReconnecting()
				h.discoverEndpoint(nil)
			}
		}
		if h.connectingPhase == connectingPhase_Authentication && h.elapsedTime()-h.reconInfo.Timestamp >= h.settings.OperationTimeout() {
			h.raiseAuthFailed("Authentication timed out.")
			h.goToConnectedState()
		}
		if h.connectingPhase > connectingPhase_ConnectionEstablishing {
			return h.manageHeartbeats()
		}
		return nil
	case connectionState_Connected:
		if h.elapsedTime()-h.lastTimeoutsTimestamp >= h.settings.OperationTimeoutCheckPeriod() {
			h.reconInfo = reconnectionInfo{0, h.elapsedTime()}
			if err := h.operations.CheckTimeoutsAndRetry(h.connection); err != nil {
				return err
			}
			if err := h.subscriptions.CheckTimeoutsAndRetry(h.connection); err != nil {
				return err
			}
			h.lastTimeoutsTimestamp = h.elapsedTime()
		}
		return h.manageHeartbeats()
	case connectionState_Closed:
		return nil
	default:
		return fmt.Errorf("Unknown state: %v", h.state)
	}
}

func (h *connectionLogicHandler) manageHeartbeats() error {
	if h.connection == nil {
		return errors.New("")
	}

	var timeout time.Duration
	if h.heartbeatInfo.IsIntervalStage {
		timeout = h.settings.HeartbeatInterval()
	} else {
		timeout = h.settings.HeartbeatTimeout()
	}
	if h.elapsedTime()-h.heartbeatInfo.Timestamp < timeout {
		return nil
	}

	pkgNumber := h.packageNumber
	if h.heartbeatInfo.LastPackageNumber != pkgNumber {
		h.heartbeatInfo = heartbeatInfo{pkgNumber, true, h.elapsedTime()}
		return nil
	}

	if h.heartbeatInfo.IsIntervalStage {
		h.connection.EnqueueSend(client.NewTcpPackage(client.Command_HeartbeatRequestCommand, client.FlagsNone,
			uuid.Must(uuid.NewV4()), nil, nil))
		h.heartbeatInfo = heartbeatInfo{h.heartbeatInfo.LastPackageNumber, false, h.elapsedTime()}
	} else {
		msg := fmt.Sprintf(
			"EventStoreConnection '%s': closing TCP connection [%s, %s, %s] due to HEARTBEAT TIMEOUT at pkgNum %d.",
			h.esConnection.Name(), h.connection.RemoteEndpoint(), h.connection.LocalEndpoint(),
			h.connection.ConnectionId(), pkgNumber)
		log.Info(msg)
		h.closeTcpConnection(msg)
	}
	return nil
}

func (h *connectionLogicHandler) Connected() client.EventHandlers { return h.connected }

func (h *connectionLogicHandler) raiseConnected(addr net.Addr) {
	h.connected.Raise(client.NewClientConnectionEventArgs(addr, h.esConnection))
}

func (h *connectionLogicHandler) Disconnected() client.EventHandlers { return h.disconnected }

func (h *connectionLogicHandler) raiseDisconnected(addr net.Addr) {
	h.disconnected.Raise(client.NewClientConnectionEventArgs(addr, h.esConnection))
}

func (h *connectionLogicHandler) Reconnecting() client.EventHandlers { return h.reconnecting }

func (h *connectionLogicHandler) raiseReconnecting() {
	h.reconnecting.Raise(client.NewClientReconnectingEventArgs(h.esConnection))
}

func (h *connectionLogicHandler) Closed() client.EventHandlers { return h.closed }

func (h *connectionLogicHandler) raiseClosed(reason string) {
	h.closed.Raise(client.NewClientClosedEventArgs(reason, h.esConnection))
}

func (h *connectionLogicHandler) ErrorOccurred() client.EventHandlers { return h.errorOccurred }

func (h *connectionLogicHandler) raiseErrorOccurred(err error) {
	h.errorOccurred.Raise(client.NewClientErrorEventArgs(err, h.esConnection))
}

func (h *connectionLogicHandler) AuthenticationFailed() client.EventHandlers {
	return h.authenticationFailed
}

func (h *connectionLogicHandler) raiseAuthFailed(reason string) {
	h.authenticationFailed.Raise(client.NewClientAuthenticationFailedEventArgs(reason, h.esConnection))
}