text:
package net.katsuster.strview.gui.view;

import java.util.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

import net.katsuster.strview.gui.*;
import net.katsuster.strview.util.*;
import net.katsuster.strview.media.*;

/**
 *

 * ストリームの構造を表示するパネルです。
 *

 *
 *

 * 下記の情報を表示します。
 *

 *
 *

 *
ストリームを構成するパケットの一覧

 *
各パケットを構成するデータの一覧

 *

 */
public class PacketTreeViewerPanel extends ViewerPanel {
    private static final long serialVersionUID = 1L;

    private FlatTextField packetToolText;
    private PacketTreeViewer packetTreeViewer;
    private PacketListViewer packetListViewer;
    private MemberTreeViewer memberTreeViewer;
    private JTextArea memberTextViewer;

    public PacketTreeViewerPanel(LargePacketList<?> l) {
        JScrollPane scrPacketViewer;

        //表示するファイルを保持する
        setList(l);

        setName(getList().getTypeName());
        setLayout(new BorderLayout());
        setTransferHandler(new FileTransferHandler());

        //ビューアを上下に表示する
        JSplitPane splitPacketMember = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPacketMember.setDividerSize(5);
        splitPacketMember.setDividerLocation(200);

        //上側、パケットツリーまたはパケットリスト
        JPanel packetTool = new JPanel();
        packetTool.setLayout(new FlowLayout(FlowLayout.LEFT));

        packetToolText = new FlatTextField();
        packetToolText.setPreferredSize(new Dimension(150, 22));
        packetToolText.getTextField().addKeyListener(new ActionGoto(""));
        packetTool.add(packetToolText);

        JButton btnGo = new JButton(new ActionGoto("Go"));
        packetTool.add(btnGo);
        JButton btnCount = new JButton(new ActionCount("Count"));
        packetTool.add(btnCount);

        if (getList().hasTreeStructure()) {
            packetTreeViewer = new PacketTreeViewer(getList());
            PacketTreeSelListener packetTreeListener = new PacketTreeSelListener();

            JTree lview = packetTreeViewer.getViewer();
            lview.addTreeSelectionListener(packetTreeListener);
            lview.addMouseListener(packetTreeListener);
            lview.addKeyListener(packetTreeListener);

            scrPacketViewer = new JScrollPane(packetTreeViewer);
            scrPacketViewer.getVerticalScrollBar().setUnitIncrement(10);
        } else {
            packetListViewer = new PacketListViewer(getList());
            PacketListSelListener packetListListener = new PacketListSelListener();

            JList lview = packetListViewer.getViewer();
            lview.addListSelectionListener(packetListListener);
            lview.addMouseListener(packetListListener);
            lview.addKeyListener(packetListListener);

            scrPacketViewer = new JScrollPane(packetListViewer);
            scrPacketViewer.getVerticalScrollBar().setUnitIncrement(10);
        }

        JPanel packetPanel = new JPanel();
        packetPanel.setLayout(new BorderLayout());
        packetPanel.add(packetTool, BorderLayout.NORTH);
        packetPanel.add(scrPacketViewer, BorderLayout.CENTER);

        splitPacketMember.setLeftComponent(packetPanel);

        //下側、メンバービューア(ツリー、テキストをタブで切り替え)
        JTabbedPane tabMembers = new JTabbedPane();
        splitPacketMember.setRightComponent(tabMembers);

        //メンバービューア(ツリー)
        memberTreeViewer = new MemberTreeViewer();
        MemberTreeSelListener memberTreeListener = new MemberTreeSelListener();
        JTree m_jt = memberTreeViewer.getViewer();
        m_jt.addTreeSelectionListener(memberTreeListener);
        m_jt.addMouseListener(memberTreeListener);
        m_jt.addKeyListener(memberTreeListener);
        m_jt.setFont(new Font(Font.MONOSPACED, 0, 12));

        JScrollPane scrMemberViewer = new JScrollPane(memberTreeViewer);
        scrMemberViewer.getVerticalScrollBar().setUnitIncrement(10);
        tabMembers.addTab("Tree", scrMemberViewer);

        //メンバービューア(テキスト)
        memberTextViewer = new JTextArea();
        memberTextViewer.setFont(new Font(Font.MONOSPACED, 0, 12));

        JScrollPane scrText = new JScrollPane(memberTextViewer);
        tabMembers.addTab("Text", scrText);

        add(splitPacketMember, BorderLayout.CENTER);
    }

    @Override
    public void setFont(Font f) {
        super.setFont(f);

        if (packetTreeViewer != null) {
            packetTreeViewer.setFont(f);
        }
        if (packetListViewer != null) {
            packetListViewer.setFont(f);
        }
        if (memberTreeViewer != null) {
            memberTreeViewer.setFont(f);
        }
    }

    @Override
    public LargePacketList<?> getList() {
        return (LargePacketList<?>)super.getList();
    }

    public class ActionGoto extends AbstractAction
            implements KeyListener {
        private static final long serialVersionUID = 1L;

        public ActionGoto(String name) {
            super(name);
        }

        public ActionGoto(String name, Icon icon) {
            super(name, icon);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            go();
        }

        @Override
        public void keyTyped(KeyEvent e) {
            //Do nothing
        }

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                go();
                e.consume();
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
            //Do nothing
        }

        public void go() {
            packetToolText.setForeground(Color.BLACK);

            try {
                long num = Long.parseLong(
                        packetToolText.getTextField().getText(), 10);

                if (getList().hasTreeStructure()) {
                    JTree tview = packetTreeViewer.getViewer();
                    DefaultTreeModel model = (DefaultTreeModel)tview.getModel();
                    DefaultMutableTreeNode n = (DefaultMutableTreeNode)model.getRoot();
                    DefaultMutableTreeNode f = findNodeFromIndex(n, num);
                    if (f == null) {
                        throw new IllegalArgumentException("Not found node:" + num);
                    }

                    TreePath tp = new TreePath(model.getPathToRoot(f));
                    tview.setSelectionPath(tp);
                    tview.scrollPathToVisible(tp);
                } else {
                    JList lview = packetListViewer.getViewer();

                    lview.setSelectedIndex((int)num);
                    lview.ensureIndexIsVisible((int)num);
                    if (lview.getSelectedIndex() != num) {
                        throw new IllegalArgumentException("Not found item:" + num);
                    }
                }
            } catch (NumberFormatException ex) {
                packetToolText.setForeground(Color.RED);
            } catch (IllegalArgumentException ex) {
                packetToolText.setForeground(Color.RED);
            }
        }

        private DefaultMutableTreeNode findNodeFromIndex(DefaultMutableTreeNode n, long num) {
            Enumeration e = n.depthFirstEnumeration();

            while (e.hasMoreElements()) {
                DefaultMutableTreeNode cn = (DefaultMutableTreeNode)e.nextElement();
                if (!(cn.getUserObject() instanceof PacketTreeNode)) {
                    continue;
                }

                PacketTreeNode pn = (PacketTreeNode)cn.getUserObject();
                if (pn.getRange().getNumber() == num) {
                    return cn;
                }
            }

            return null;
        }
    }

    public class ActionCount extends AbstractAction {
        private static final long serialVersionUID = 1L;

        public ActionCount(String name) {
            super(name);
        }

        public ActionCount(String name, Icon icon) {
            super(name, icon);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    getList().count();

                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            if (packetTreeViewer != null) {
                                packetTreeViewer.setMax(1);
                            }
                            if (packetListViewer != null) {
                                packetListViewer.setMax(1);
                            }
                        }
                    });
                }
            });
            t.start();
        }
    }

    public class PacketTreeSelListener extends SelListener
            implements TreeSelectionListener {
        @Override
        public void valueChanged(TreeSelectionEvent e) {
            TreePath selPath = e.getPath();
            long selRow = getIndexFromEvent(selPath);

            if (selRow != -1) {
                onLeftSingleClick(selRow);
            }
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            TreePath selPath = packetTreeViewer.getViewer().getPathForLocation(
                    e.getX(), e.getY());
            long selRow = getIndexFromEvent(selPath);

            if (selRow != -1) {
                if (e.getClickCount() == 1
                        && e.getButton() == MouseEvent.BUTTON1) {
                    //左シングルのとき
                    //onLeftSingleClick(selRow);
                } else if (e.getClickCount() == 1
                        && e.getButton() == MouseEvent.BUTTON3) {
                    //右シングルのとき
                    //onRightSingleClick(selRow);
                } else if (e.getClickCount() == 2
                        && e.getButton() == MouseEvent.BUTTON1) {
                    //左ダブルのとき
                    onLeftDoubleClick(selRow);
                }
            }
        }

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                JTree tree = (JTree)e.getSource();
                TreePath selPath = tree.getLeadSelectionPath();
                long selRow = getIndexFromEvent(selPath);

                if (selRow != -1) {
                    onLeftDoubleClick(selRow);
                }
                e.consume();
            }
        }

        protected long getIndexFromEvent(TreePath selPath) {
            if (selPath == null || !(selPath.getLastPathComponent()
                    instanceof DefaultMutableTreeNode)) {
                return -1;
            }

            DefaultMutableTreeNode n = (DefaultMutableTreeNode)
                    selPath.getLastPathComponent();
            if (!(n.getUserObject() instanceof PacketTreeNode)) {
                return -1;
            }

            PacketTreeNode pn = (PacketTreeNode)n.getUserObject();
            PacketRange pr = pn.getRange();
            if (pr == null) {
                return -1;
            }

            return pr.getNumber();
        }
    }

    public class PacketListSelListener extends SelListener
            implements ListSelectionListener {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                return;
            }

            JList l = (JList)e.getSource();
            onLeftSingleClick(l.getLeadSelectionIndex());
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            long selRow = packetListViewer.getRowForLocation(
                    e.getX(), e.getY());

            if (selRow != -1) {
                if (e.getClickCount() == 1
                        && e.getButton() == MouseEvent.BUTTON1) {
                    //左シングルのとき
                    //onLeftSingleClick(selRow);
                } else if (e.getClickCount() == 1
                        && e.getButton() == MouseEvent.BUTTON3) {
                    //右シングルのとき
                    //onRightSingleClick(selRow);
                } else if (e.getClickCount() == 2
                        && e.getButton() == MouseEvent.BUTTON1) {
                    //左ダブルのとき
                    onLeftDoubleClick(selRow);
                }
            }
        }

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                JList l = (JList)e.getSource();
                long selRow = l.getLeadSelectionIndex();

                if (selRow != -1) {
                    onLeftDoubleClick(selRow);
                }
                e.consume();
            }
        }
    }

    public class SelListener
            implements MouseListener, KeyListener {
        @Override
        public void mouseClicked(MouseEvent e) {
            //Do nothing
        }

        @Override
        public void mousePressed(MouseEvent e) {
            //Do nothing
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            //Do nothing
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            //Do nothing
        }

        @Override
        public void mouseExited(MouseEvent e) {
            //Do nothing
        }

        @Override
        public void keyTyped(KeyEvent e) {
            //Do nothing
        }

        @Override
        public void keyPressed(KeyEvent e) {
            //Do nothing
        }

        @Override
        public void keyReleased(KeyEvent e) {
            //Do nothing
        }

        public void onLeftSingleClick(long selRow) {
            Packet p = getPacketFromEvent(selRow);
            if (p == null) {
                return;
            }

            //ノードの文字列表現を表示する
            memberTextViewer.setText(p.toString());
            memberTextViewer.repaint();

            //ノードのツリー表現を表示する
            ToMemberTreeNodeConverter c = new ToMemberTreeNodeConverter();
            p.write(c);
            MemberTreeNode root = c.getResult();
            root.setName(getList().getTypeName());
            memberTreeViewer.setRootTreeNode(root);
            JTree v = memberTreeViewer.getViewer();
            while (true) {
                int before = v.getRowCount();
                for (int row = Integer.min(100, before) - 1; row >= 0; row--) {
                    v.expandRow(row);
                }
                if (before == v.getRowCount())
                    break;
            }
            memberTreeViewer.repaint();

            //ノードが指すデータ範囲をハイライトする
            if (p.getRawPacket() != null) {
                PacketRange pr = p.getRange();

                LinkEvent e = new LinkEvent(getList(), LinkEvent.Type.NODE,
                        new SimpleRange(null, pr.getStart(), pr.getLength()));
                fireLinkChange(e);
            }
        }

        public void onLeftDoubleClick(long selRow) {
            Packet p = getPacketFromEvent(selRow);
            if (p == null) {
                return;
            }

            //ノードが指すデータの先頭にジャンプする
            LinkEvent e = new LinkEvent(getList(), LinkEvent.Type.JUMP,
                    new SimpleRange(null, p.getRange().getStart(), 0));
            fireLinkChange(e);
        }

        protected Packet getPacketFromEvent(long selRow) {
            return getList().get(selRow);
        }
    }

    public class MemberTreeSelListener extends MouseAdapter
            implements TreeSelectionListener, KeyListener {
        @Override
        public void valueChanged(TreeSelectionEvent e) {
            onLeftSingleClick(0, e.getPath());
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            int selRow = memberTreeViewer.getViewer().getRowForLocation(
                    e.getX(), e.getY());
            TreePath selPath = memberTreeViewer.getViewer().getPathForLocation(
                    e.getX(), e.getY());

            if (selRow != -1) {
                if (e.getClickCount() == 1
                        && e.getButton() == MouseEvent.BUTTON1) {
                    //左シングルのとき
                    //onLeftSingleClick(selRow, selPath);
                } else if (e.getClickCount() == 1
                        && e.getButton() == MouseEvent.BUTTON3) {
                    //右シングルのとき
                    //onRightSingleClick(selRow, selPath);
                } else if (e.getClickCount() == 2
                        && e.getButton() == MouseEvent.BUTTON1) {
                    //左ダブルのとき
                    onLeftDoubleClick(selRow, selPath);
                }
            }
        }

        @Override
        public void keyTyped(KeyEvent e) {
            //Do nothing
        }

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                JTree tree = (JTree)e.getSource();
                TreePath selPath = tree.getLeadSelectionPath();

                if (selPath != null) {
                    onLeftDoubleClick(0, selPath);
                }
                e.consume();
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
            //Do nothing
        }

        public void onLeftSingleClick(int selRow, TreePath selPath) {
            MemberTreeNode ptn = getPacketTreeNodeFromEvent(selPath);
            LinkEvent e;

            if (ptn == null) {
                return;
            }

            //メンバが指すデータ範囲をハイライトする
            if (ptn.hasNumData() || ptn.hasArrayData()) {
                long len = ptn.getDataLength();
                if ((len != 0) && (len % 8 != 0)) {
                    //bit | bit+7 | byte
                    //----+-------+-----
                    //0   | 除外  | 0
                    //1   | 8     | 1
                    //2   | 9     | 1
                    //7   | 14    | 1
                    //8   | 15    | 1
                    //9   | 16    | 2
                    len += 7;
                }

                e = new LinkEvent(getList(), LinkEvent.Type.MEMBER,
                        new SimpleRange(null, ptn.getDataStart(), len));
            } else {
                e = new LinkEvent(getList(), LinkEvent.Type.MEMBER,
                        new SimpleRange(null, 0, 0));
            }

            fireLinkChange(e);
        }

        public void onLeftDoubleClick(int selRow, TreePath selPath) {
            MemberTreeNode ptn = getPacketTreeNodeFromEvent(selPath);
            if (ptn == null) {
                return;
            }

            //ノードが指すデータの先頭にジャンプする
            if (ptn.hasNumData() || ptn.hasArrayData()) {
                LinkEvent e = new LinkEvent(getList(), LinkEvent.Type.JUMP,
                        new SimpleRange(null, ptn.getDataStart(), 0));
                fireLinkChange(e);
            }
        }

        protected MemberTreeNode getPacketTreeNodeFromEvent(TreePath selPath) {
            if (!(selPath.getLastPathComponent() instanceof MemberTreeNode)) {
                return null;
            }

            return (MemberTreeNode)selPath.getLastPathComponent();
        }
    }
}


text:
using System.Threading.Tasks;
using RemoteClient.Roslyn.Attributes;

namespace RemoteClient.Roslyn.Test
{
    [RemoteClient(true, true)]
    public interface IFoo
    {
        /// <summary>
        /// Getting string value async
        /// </summary>
        /// <param name="value">Value parameter</param>
        /// <param name="bar">Bar parameter</param>
        /// <returns>Result of method</returns>
        [WebInvoke(Method = "GET", UriTemplate = "foo/{value}", RequestFormat = OperationWebMessageFormat.Json, ResponseFormat = OperationWebMessageFormat.Xml)]
        Task<string> GetStringAsync(string value, string bar);

        [WebInvoke(Method = "GET", UriTemplate = "foo/{value}", RequestFormat = OperationWebMessageFormat.Json, ResponseFormat = OperationWebMessageFormat.Xml)]
        Task ExecuteStringAsync(string value, string bar);
    }
}

redpajama_set_name: RedPajamaGithub


text:
Quickstart
==========

Hi, welcome to the twelve-minute quick-start tutorial.

Connecting to a database
------------------------

At first you need to import the dataset package :) ::

   import dataset

To connect to a database you need to identify it by its `URL <http://docs.sqlalchemy.org/en/latest/core/engines.html#engine-creation-api>`_, which basically is a string of the form ``"dialect://user:password@host/dbname"``. Here are a few examples for different database backends::

   # connecting to a SQLite database
   db = dataset.connect('sqlite:///mydatabase.db')

   # connecting to a MySQL database with user and password
   db = dataset.connect('mysql://user:password@localhost/mydatabase')

   # connecting to a PostgreSQL database
   db = dataset.connect('postgresql://scott:tiger@localhost:5432/mydatabase')

It is also possible to define the `URL` as an environment variable called `DATABASE_URL`
so you can initialize database connection without explicitly passing an `URL`::

   db = dataset.connect()

Depending on which database you're using, you may also have to install
the database bindings to support that database. SQLite is included in
the Python core, but PostgreSQL requires ``psycopg2`` to be installed.
MySQL can be enabled by installing the ``mysql-db`` drivers.

Storing data
------------

To store some data you need to get a reference to a table. You don't need
to worry about whether the table already exists or not, since dataset
will create it automatically::

   # get a reference to the table 'user'
   table = db['user']

Now storing data in a table is a matter of a single function call. Just
pass a `dict`_ to *insert*. Note that you don't need to create the columns
*name* and *age* – dataset will do this automatically::

   # Insert a new record.
   table.insert(dict(name='John Doe', age=46, country='China'))

   # dataset will create "missing" columns any time you insert a dict with an unknown key
   table.insert(dict(name='Jane Doe', age=37, country='France', gender='female'))

.. _dict: http://docs.python.org/2/library/stdtypes.html#dict

Updating existing entries is easy, too::

   table.update(dict(name='John Doe', age=47), ['name'])

The list of filter columns given as the second argument filter using the
values in the first column. If you don't want to update over a
particular value, just use the auto-generated ``id`` column.

Using Transactions
------------------

You can group a set of database updates in a transaction. In that case, all updates
are committed at once or, in case of exception, all of them are reverted. Transactions
are supported through a context manager, so they can be used through a ``with``
statement::

    with dataset.connect() as tx:
        tx['user'].insert(dict(name='John Doe', age=46, country='China'))

You can get same functionality by invoking the methods :py:meth:`begin() <dataset.Table.begin>`,
:py:meth:`commit() <dataset.Table.commit>` and :py:meth:`rollback() <dataset.Table.rollback>`
explicitly::

    db = dataset.connect()
    db.begin()
    try:
        db['user'].insert(dict(name='John Doe', age=46, country='China'))
        db.commit()
    except:
        db.rollback()

Nested transactions are supported too::

    db = dataset.connect()
    with db as tx1:
        tx1['user'].insert(dict(name='John Doe', age=46, country='China'))
        with db as tx2:
            tx2['user'].insert(dict(name='Jane Doe', age=37, country='France', gender='female'))

Inspecting databases and tables
-------------------------------

When dealing with unknown databases we might want to check their structure
first. To start exploring, let's find out what tables are stored in the
database:

   >>> print(db.tables)
   [u'user']

Now, let's list all columns available in the table ``user``:

   >>> print(db['user'].columns)
   [u'id', u'country', u'age', u'name', u'gender']

Using ``len()`` we can get the total number of rows in a table:

   >>> print(len(db['user']))
   2

Reading data from tables
------------------------

Now let's get some real data out of the table::

   users = db['user'].all()

If we simply want to iterate over all rows in a table, we can omit :py:meth:`all() <dataset.Table.all>`::

   for user in db['user']:
      print(user['age'])

We can search for specific entries using :py:meth:`find() <dataset.Table.find>` and
:py:meth:`find_one() <dataset.Table.find_one>`::

   # All users from China
   chinese_users = table.find(country='China')

   # Get a specific user
   john = table.find_one(name='John Doe')

   # Find by comparison
   elderly_users = table.find(table.table.columns.age >= 70)

Using  :py:meth:`distinct() <dataset.Table.distinct>` we can grab a set of rows
with unique values in one or more columns::

   # Get one user per country
   db['user'].distinct('country')

Finally, you can use the ``row_type`` parameter to choose the data type in which
results will be returned::

    import dataset
    from stuf import stuf

    db = dataset.connect('sqlite:///mydatabase.db', row_type=stuf)

Now contents will be returned in ``stuf`` objects (basically, ``dict``
objects whose elements can be acessed as attributes (``item.name``) as well as
by index (``item['name']``).

Running custom SQL queries
--------------------------

Of course the main reason you're using a database is that you want to
use the full power of SQL queries. Here's how you run them with ``dataset``::

   result = db.query('SELECT country, COUNT(*) c FROM user GROUP BY country')
   for row in result:
      print(row['country'], row['c'])

The :py:meth:`query() <dataset.Table.query>` method can also be used to
access the underlying `SQLAlchemy core API <http://docs.sqlalchemy.org/en/latest/orm/query.html#the-query-object>`_, which allows for the
programmatic construction of more complex queries::

   table = db['user'].table
   statement = table.select(table.c.name.like('%John%'))
   result = db.query(statement)

Exporting data
--------------

While playing around with our database in Python is a nice thing, they are
sometimes just a processing stage until we go on to use it in another
place, say in an interactive web application. To make this seamless,
``dataset`` supports serializing rows of data into static JSON and CSV files
such using the :py:meth:`freeze() <dataset.freeze>` function::

   # export all users into a single JSON
   result = db['users'].all()
   dataset.freeze(result, format='json', filename='users.json')

You can create one file per row by setting ``mode`` to "item"::

   # export one JSON file per user
   dataset.freeze(result, format='json', filename='users/{{ id }}.json', mode='item')

Since this is a common operation we made it available via command line
utility ``datafreeze``. Read more about the :doc:`freezefile markup <freezefile>`.

.. code-block:: bash

   $ datafreeze freezefile.yaml


text:
package net.pinemz.hm.api;

import java.text.ParseException;

import net.pinemz.hm.R;

import org.apache.commons.lang3.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;

public class HmApi {
	public static final String TAG = "HmApi";

	private static final String API_BASE = "http://node-hm.herokuapp.com/";
	private static final String API_INDEX = "prefectures";
	private static final String API_SHOW = "prefecture/:id";
	private static final String API_MENU = "prefecture/:prefecture_id/:menu_id";

	private Context context;
	private RequestQueue requestQueue;

	public HmApi(
			Context context,
			RequestQueue requestQueue
			)
	{
		Log.d(TAG, "HmApi");

		Validate.notNull(context);
		Validate.notNull(requestQueue);

		this.context = context;
		this.requestQueue = requestQueue;
	}

	/**
	 * ƒŠƒNƒGƒXƒg'ðƒLƒ…['ɒljÁ'·'é
	 * @param request 'ljÁ'·'郊ƒNƒGƒXƒg
	 */
	protected <T> void addRequest(Request<T> request) {
		Log.d(TAG, "addRequest");

		Validate.notNull(request);

		request.setRetryPolicy(new DefaultRetryPolicy(
				context.getResources().getInteger(R.integer.network_timeout),
				context.getResources().getInteger(R.integer.network_max_retries),
				DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
				));

		this.requestQueue.add(request);
		this.requestQueue.start();
	}

	public void getPrefectures(final HmApi.Listener<PrefectureCollection> listener){
		this.addRequest(new JsonArrayRequest(this.getIndexUrl(),
				new Response.Listener<JSONArray>() {
			        @Override
			        public void onResponse(JSONArray response){
			        	try {
			        		PrefectureCollection prefectures =
			        				new PrefectureCollection(response);

			        		if(prefectures.isEmpty()){
			        			Log.d(TAG, "Response.Listener#onResponse onFailure");
			        			listener.onFailure();
			        		}

			        		else {
			        			Log.d(TAG, "Response.Listener#onResponse onSuccess");
			        			listener.onSuccess(HmApi.this, prefectures);
			        		}
			        	}

			        	catch(JSONException e){
			        		Log.e(TAG, "Response.Listener#onResponse", e);
			        		listener.onException(e);
			        	}

			        	catch(ParseException e){
			        		Log.e(TAG, "Response.Listener#onResponse", e);
			        		listener.onException(e);
			        	}
			        }
				},
				new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Log.e(TAG, "Response.ErrorListener#onErrorResponse", error);
						listener.onException(error);
					}
				}));
	}

	/**
	 * ƒƒjƒ…[ˆê——'ðŽæ"¾'·'é
	 * @param prefectureId "s"¹•{Œ§ ID
	 * @param listener ƒCƒxƒ"ƒgƒŠƒXƒi
	 */
	public void getMenus(
			int prefectureId,
			final HmApi.Listener<MenuCollection> listener)
	{
		Log.d(TAG, "getMenus");

		if (prefectureId < 0) {
			throw new IllegalArgumentException("prefectureId cannot be negative number");
		}

		this.addRequest(new JsonObjectRequest(
				Method.GET,
				this.getShowUrl(prefectureId),
				null,
				new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject response){
						Log.d(TAG, "getMenus>#onResponse");

						try {
							MenuCollection menus =
									new MenuCollection(response);

							if (menus.isEmpty()) {
								listener.onFailure();
							}

							else {
								listener.onSuccess(HmApi.this, menus);
							}
						}

						catch(JSONException e) {
							Log.d(TAG, "getMenus>#onResponse", e);
							listener.onException(e);
						}

						catch(ParseException e) {
							Log.d(TAG, "getMenus>#onResponse", e);
							listener.onException(e);
						}
					}
				},
				new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						listener.onException(error);
					}
				}));
	}

	protected String getIndexUrl(){
		return API_BASE + API_INDEX;
	}

	protected String getShowUrl(int id){
		String url = API_BASE + API_SHOW;
		url = url.replace(":id", Integer.toString(id));

		return url;
	}

	protected String getMenuUrl(int prefecture_id, int menu_id){
		String url = API_BASE + API_MENU;
		url = url.replace(":prefecture_id", Integer.toString(prefecture_id));
		url = url.replace(":menu_id", Integer.toString(menu_id));

		return url;
	}

	/**
	 * API ŽÀsŽž'̃Cƒxƒ"ƒgƒŠƒXƒi
	 * @author MIZUNE Pine
	 * @param <T> API 'Ì–ß'è'l
	 */
	public interface Listener<T> {
		void onSuccess(HmApi api, T data);
		void onFailure();
		void onException(Exception exception);
	}
}


text:
package com.linbo.algs.searchings;

import com.linbo.algs.datatypes.LinkedQueue;

import java.util.NoSuchElementException;

/**
 * Created by @linbojin on 2/2/17.
 *  This class represents an ordered symbol table of generic
 *  key-value pairs.
 *  This implementation uses an (unbalanced) binary search tree. It requires that
 *  the key type implements the Comparable interface and calls the
 *  compareTo() and method to compare two keys.
 *  Operations each take linear time in the worst case, if the tree becomes unbalanced.
 *  The size and is-empty operations take constant time.
 */
public class BST<Key extends Comparable<Key>, Value> {
  private Node root;

  private class Node {
    private Key key;
    private Value val;
    private Node left, right;
    private int size;

    public Node(Key key, Value val, int size) {
      this.key = key;
      this.val = val;
      this.size = size;
    }
  }

  public BST() { }

  public boolean isEmpty() {
    return size() == 0;
  }

  public int size() { return size(root); }

  private int size(Node x) {
    if (x == null) return 0;
    else return x.size;
  }

  public boolean contains(Key key) {
    if (key == null) throw new java.lang.IllegalArgumentException("argument to contains() is null");
    return get(key) != null;
  }

  public Value get(Key key) {
    return get(root, key);
  }

  private Value get(Node x, Key key) {
    if (x == null) return null;
    int cmp = key.compareTo(x.key);
    if (cmp < 0) return get(x.left, key);
    else if (cmp > 0) return get(x.right, key);
    else return x.val;
  }

  public void put(Key key, Value val) {
    if (key == null) throw new java.lang.IllegalArgumentException("first argument to put() is null");
    if (val == null) {
      delete(key);
      return;
    }
    root = put(root, key, val);
  }

  private Node put(Node x, Key key, Value val) {
    if (x == null) return new Node(key, val, 1);
    int cmp = key.compareTo(x.key);
    if (cmp < 0) x.left = put(x.left, key, val);
    else if (cmp > 0) x.right = put(x.right, key, val);
    else x.val = val;
    x.size = 1 + size(x.left) + size(x.right);
    return x;
  }

  public void deleteMin() {
    if (isEmpty()) throw new java.util.NoSuchElementException("Symbol table underflow");
    root = deleteMin(root);
  }

  private Node deleteMin(Node x) {
    if (x.left == null) return x.right;
    x.left = deleteMin(x.left);
    x.size = size(x.left) + size(x.right) + 1;
    return x;
  }

  public void deleteMax() {
    if (isEmpty()) throw new java.util.NoSuchElementException("Symbol table underflow");
    root = deleteMax(root);
  }

  private Node deleteMax(Node x) {
    if (x.right == null) return x.left;
    x.right = deleteMax(x.right);
    x.size = size(x.left) + size(x.right) + 1;
    return x;
  }

  public void delete(Key key) {
    if (key == null) throw new IllegalArgumentException("argument of delete() is null");
    root = delete(root, key);
  }

  private Node delete(Node x, Key key) {
    if (x == null) return null;

    int cmp = key.compareTo(x.key);
    if (cmp < 0) x.left = delete(x.left, key);
    else if (cmp > 0) x.right = delete(x.right, key);
    else {
      if (x.left == null) return x.right;
      if (x.right == null) return x.left;
      Node t = x;
      x = min(t.right);
      x.right = deleteMin(t.right);
      x.left = t.left;
    }
    x.size = size(x.left) + size(x.right) + 1;
    return x;
  }

  public Key min() {
    if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table");
    return min(root).key;
  }

  private Node min(Node x) {
    if (x.left == null) return x;
    else return min(x.left);
  }

  public Key max() {
    if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table");
    return max(root).key;
  }

  private Node max(Node x) {
    if (x.right == null) return x;
    else return max(x.right);
  }

  public Key floor(Key key) {
    if (key == null) throw new IllegalArgumentException("argument to floor() is null");
    if (isEmpty()) throw new NoSuchElementException("called floor() with empty symbol table");
    Node x = floor(root, key);
    if (x == null) return null;
    else return x.key;
  }

  private Node floor(Node x, Key key) {
    if (x == null) return null;
    int cmp = key.compareTo(x.key);
    if (cmp == 0) return x;
    if (cmp <  0) return floor(x.left, key);
    Node t = floor(x.right, key);
    if (t != null) return t;
    else return x;
  }

  public Key ceiling(Key key) {
    if (key == null) throw new IllegalArgumentException("argument to ceiling() is null");
    if (isEmpty()) throw new NoSuchElementException("called ceiling() with empty symbol table");
    Node x = ceiling(root, key);
    if (x == null) return null;
    else return x.key;
  }

  private Node ceiling(Node x, Key key) {
    if (x == null) return null;
    int cmp = key.compareTo(x.key);
    if (cmp == 0) return x;
    if (cmp < 0) {
      Node t = ceiling(x.left, key);
      if (t != null) return t;
      else return x;
    }
    return ceiling(x.right, key);
  }

  public Key select(int k) {
    if (k < 0 || k >= size()) throw new IllegalArgumentException();
    Node x = select(root, k);
    return x.key;
  }

  // Return key of rank k.
  private Node select(Node x, int k) {
    if (x == null) return null;
    int t = size(x.left);
    if      (t > k) return select(x.left,  k);
    else if (t < k) return select(x.right, k-t-1);
    else            return x;
  }

  public int rank(Key key) {
    if (key == null) throw new IllegalArgumentException("argument to rank() is null");
    return rank(key, root);
  }

  // Number of keys in the subtree less than key.
  private int rank(Key key, Node x) {
    if (x == null) return 0;
    int cmp = key.compareTo(x.key);
    if      (cmp < 0) return rank(key, x.left);
    else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right);
    else              return size(x.left);
  }

  public Iterable<Key> keysIterable() {
    return keysIterable(min(), max());
  }

  // Returns all keys in the symbol table in the given range.
  public Iterable<Key> keysIterable(Key lo, Key hi) {
    if (lo == null) throw new IllegalArgumentException("first argument to keys() is null");
    if (hi == null) throw new IllegalArgumentException("second argument to keys() is null");

    LinkedQueue<Key> queue = new LinkedQueue<Key>();
    keys(root, queue, lo, hi);
    return queue;
  }

  private void keys(Node x, LinkedQueue<Key> queue, Key lo, Key hi) {
    if (x == null) return;
    int cmplo = lo.compareTo(x.key);
    int cmphi = hi.compareTo(x.key);
    if (cmplo < 0) keys(x.left, queue, lo, hi);
    if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key);
    if (cmphi > 0) keys(x.right, queue, lo, hi);
  }

  public int size(Key lo, Key hi) {
    if (lo == null) throw new IllegalArgumentException("first argument to size() is null");
    if (hi == null) throw new IllegalArgumentException("second argument to size() is null");

    if (lo.compareTo(hi) > 0) return 0;
    if (contains(hi)) return rank(hi) - rank(lo) + 1;
    else              return rank(hi) - rank(lo);
  }

  // return the height of the BST (a 1-node tree has height 0)
  public int height() {
    return height(root);
  }
  private int height(Node x) {
    if (x == null) return -1;
    return 1 + Math.max(height(x.left), height(x.right));
  }

  // return the keys in the BST in level order traversal
  public Iterable<Key> levelOrder() {
    LinkedQueue<Key> keys = new LinkedQueue<Key>();
    LinkedQueue<Node> queue = new LinkedQueue<Node>();
    queue.enqueue(root);
    while (!queue.isEmpty()) {
      Node x = queue.dequeue();
      if (x == null) continue;
      keys.enqueue(x.key);
      queue.enqueue(x.left);
      queue.enqueue(x.right);
    }
    return keys;
  }

  public static void main(String[] args) {

    BST st = new BST();

    st.put("A", 0);
    st.put("C", 2);
    st.put("I", 8);
    st.put("F", 5);
    st.put("D", 3);
    st.put("K", 10);
    st.put("J", 9);
    st.put("E", 4);
    st.put("H", 7);
    st.put("B", 1);
    st.put("G", 6);

    System.out.println(st.size());     // 11
    System.out.println(st.isEmpty());  // false
    System.out.println(st.get("J"));   // 9
    System.out.println(st.get("M"));   // null
    System.out.println(st.min());      // A
    System.out.println(st.max());      // K
    System.out.println(st.rank("F"));  // 5
    System.out.println(st.floor("O"));  // K
    System.out.println(st.ceiling("O"));  // null

    st.delete("A");
    st.delete("J");
    for (Object a: st.keysIterable()) {
      System.out.print(a + " ");
    }
  }

}


text:
console.log(__dirname);
console.log(__filename);


text:
<?php
/**
 * @package PayPal
 */

/**
 * Make sure our parent class is defined.
 */
require_once 'PayPal/Type/XSDSimpleType.php';

/**
 * SellerType
 *
 * Information about user used by selling applications there are number of required
 * elements - they will always show up for seller node there is not such a call to
 * do revise seller info. only added minoccur=0 to elements that will not show up
 * in every type of request/responce
 *
 * @package PayPal
 */
class SellerType extends XSDSimpleType
{
    var $AllowPaymentEdit;

    var $BillingCurrency;

    var $CheckoutEnabled;

    var $CIPBankAccountStored;

    var $GoodStanding;

    var $LiveAuctionAuthorized;

    /**
     * Indicates whether the user has elected to participate as a seller in the
     * Merchandising Manager feature.
     */
    var $MerchandizingPref;

    var $QualifiesForB2BVAT;

    var $SellerLevel;

    var $SellerPaymentAddress;

    var $SchedulingInfo;

    var $StoreOwner;

    var $StoreURL;

    function SellerType()
    {
        parent::XSDSimpleType();
        $this->_namespace = 'urn:ebay:apis:eBLBaseComponents';
        $this->_elements = array_merge($this->_elements,
            array (
              'AllowPaymentEdit' =>
              array (
                'required' => true,
                'type' => 'boolean',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'BillingCurrency' =>
              array (
                'required' => false,
                'type' => 'CurrencyCodeType',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'CheckoutEnabled' =>
              array (
                'required' => true,
                'type' => NULL,
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'CIPBankAccountStored' =>
              array (
                'required' => true,
                'type' => 'boolean',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'GoodStanding' =>
              array (
                'required' => true,
                'type' => 'boolean',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'LiveAuctionAuthorized' =>
              array (
                'required' => true,
                'type' => 'boolean',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'MerchandizingPref' =>
              array (
                'required' => true,
                'type' => 'MerchandizingPrefCodeType',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'QualifiesForB2BVAT' =>
              array (
                'required' => true,
                'type' => 'boolean',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'SellerLevel' =>
              array (
                'required' => true,
                'type' => NULL,
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'SellerPaymentAddress' =>
              array (
                'required' => false,
                'type' => NULL,
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'SchedulingInfo' =>
              array (
                'required' => false,
                'type' => 'SchedulingInfoType',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'StoreOwner' =>
              array (
                'required' => true,
                'type' => NULL,
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
              'StoreURL' =>
              array (
                'required' => false,
                'type' => 'anyURI',
                'namespace' => 'urn:ebay:apis:eBLBaseComponents',
              ),
            ));
    }

    function getAllowPaymentEdit()
    {
        return $this->AllowPaymentEdit;
    }
    function setAllowPaymentEdit($AllowPaymentEdit, $charset = 'iso-8859-1')
    {
        $this->AllowPaymentEdit = $AllowPaymentEdit;
        $this->_elements['AllowPaymentEdit']['charset'] = $charset;
    }
    function getBillingCurrency()
    {
        return $this->BillingCurrency;
    }
    function setBillingCurrency($BillingCurrency, $charset = 'iso-8859-1')
    {
        $this->BillingCurrency = $BillingCurrency;
        $this->_elements['BillingCurrency']['charset'] = $charset;
    }
    function getCheckoutEnabled()
    {
        return $this->CheckoutEnabled;
    }
    function setCheckoutEnabled($CheckoutEnabled, $charset = 'iso-8859-1')
    {
        $this->CheckoutEnabled = $CheckoutEnabled;
        $this->_elements['CheckoutEnabled']['charset'] = $charset;
    }
    function getCIPBankAccountStored()
    {
        return $this->CIPBankAccountStored;
    }
    function setCIPBankAccountStored($CIPBankAccountStored, $charset = 'iso-8859-1')
    {
        $this->CIPBankAccountStored = $CIPBankAccountStored;
        $this->_elements['CIPBankAccountStored']['charset'] = $charset;
    }
    function getGoodStanding()
    {
        return $this->GoodStanding;
    }
    function setGoodStanding($GoodStanding, $charset = 'iso-8859-1')
    {
        $this->GoodStanding = $GoodStanding;
        $this->_elements['GoodStanding']['charset'] = $charset;
    }
    function getLiveAuctionAuthorized()
    {
        return $this->LiveAuctionAuthorized;
    }
    function setLiveAuctionAuthorized($LiveAuctionAuthorized, $charset = 'iso-8859-1')
    {
        $this->LiveAuctionAuthorized = $LiveAuctionAuthorized;
        $this->_elements['LiveAuctionAuthorized']['charset'] = $charset;
    }
    function getMerchandizingPref()
    {
        return $this->MerchandizingPref;
    }
    function setMerchandizingPref($MerchandizingPref, $charset = 'iso-8859-1')
    {
        $this->MerchandizingPref = $MerchandizingPref;
        $this->_elements['MerchandizingPref']['charset'] = $charset;
    }
    function getQualifiesForB2BVAT()
    {
        return $this->QualifiesForB2BVAT;
    }
    function setQualifiesForB2BVAT($QualifiesForB2BVAT, $charset = 'iso-8859-1')
    {
        $this->QualifiesForB2BVAT = $QualifiesForB2BVAT;
        $this->_elements['QualifiesForB2BVAT']['charset'] = $charset;
    }
    function getSellerLevel()
    {
        return $this->SellerLevel;
    }
    function setSellerLevel($SellerLevel, $charset = 'iso-8859-1')
    {
        $this->SellerLevel = $SellerLevel;
        $this->_elements['SellerLevel']['charset'] = $charset;
    }
    function getSellerPaymentAddress()
    {
        return $this->SellerPaymentAddress;
    }
    function setSellerPaymentAddress($SellerPaymentAddress, $charset = 'iso-8859-1')
    {
        $this->SellerPaymentAddress = $SellerPaymentAddress;
        $this->_elements['SellerPaymentAddress']['charset'] = $charset;
    }
    function getSchedulingInfo()
    {
        return $this->SchedulingInfo;
    }
    function setSchedulingInfo($SchedulingInfo, $charset = 'iso-8859-1')
    {
        $this->SchedulingInfo = $SchedulingInfo;
        $this->_elements['SchedulingInfo']['charset'] = $charset;
    }
    function getStoreOwner()
    {
        return $this->StoreOwner;
    }
    function setStoreOwner($StoreOwner, $charset = 'iso-8859-1')
    {
        $this->StoreOwner = $StoreOwner;
        $this->_elements['StoreOwner']['charset'] = $charset;
    }
    function getStoreURL()
    {
        return $this->StoreURL;
    }
    function setStoreURL($StoreURL, $charset = 'iso-8859-1')
    {
        $this->StoreURL = $StoreURL;
        $this->_elements['StoreURL']['charset'] = $charset;
    }
}


text:
<?php

namespace Dizda\BitdepotClientBundle\Request;

use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class AbstractRequest
 *
 * @author Jonathan Dizdarevic <dizda@dizda.fr>
 */
abstract class AbstractRequest
{
    private $attributes;

    /**
     * @param array $options
     */
    public function __construct(array $options = array())
    {
        $resolver = new OptionsResolver();
        $this->setDefaultOptions($resolver);

        $this->attributes = $resolver->resolve($options);
    }

    /**
     * @param OptionsResolver $resolver
     */
    protected function setDefaultOptions(OptionsResolver $resolver)
    {

    }

    public function getAttributes()
    {
        return $this->attributes;
    }
}


text:
#ifndef TALK_P2P_BASE_FAKESESSION_H_
#define TALK_P2P_BASE_FAKESESSION_H_

#include <map>
#include <string>
#include <vector>

#include "talk/base/buffer.h"
#include "talk/base/sigslot.h"
#include "talk/base/sslfingerprint.h"
#include "talk/base/messagequeue.h"
#include "talk/p2p/base/session.h"
#include "talk/p2p/base/transport.h"
#include "talk/p2p/base/transportchannel.h"
#include "talk/p2p/base/transportchannelimpl.h"

namespace cricket {

class FakeTransport;

struct PacketMessageData : public talk_base::MessageData {
  PacketMessageData(const char* data, size_t len) : packet(data, len) {
  }
  talk_base::Buffer packet;
};

// Fake transport channel class, which can be passed to anything that needs a
// transport channel. Can be informed of another FakeTransportChannel via
// SetDestination.
class FakeTransportChannel : public TransportChannelImpl,
                             public talk_base::MessageHandler {
 public:
  explicit FakeTransportChannel(Transport* transport,
                                const std::string& content_name,
                                int component)
      : TransportChannelImpl(content_name, component),
        transport_(transport),
        dest_(NULL),
        state_(STATE_INIT),
        async_(false),
        identity_(NULL),
        do_dtls_(false),
        role_(ROLE_UNKNOWN),
        tiebreaker_(0),
        ice_proto_(ICEPROTO_HYBRID),
        dtls_fingerprint_("", NULL, 0) {
  }
  ~FakeTransportChannel() {
    Reset();
  }

  TransportRole role() const { return role_; }
  uint64 tiebreaker() const { return tiebreaker_; }
  TransportProtocol protocol() const { return ice_proto_; }
  const std::string& ice_ufrag() const { return ice_ufrag_; }
  const std::string& ice_pwd() const { return ice_pwd_; }
  const talk_base::SSLFingerprint& dtls_fingerprint() const {
    return dtls_fingerprint_;
  }

  void SetAsync(bool async) {
    async_ = async;
  }

  virtual Transport* GetTransport() {
    return transport_;
  }

  virtual void SetRole(TransportRole role) { role_ = role; }
  virtual void SetTiebreaker(uint64 tiebreaker) { tiebreaker_ = tiebreaker; }
  virtual void SetIceProtocolType(IceProtocolType type) { ice_proto_ = type; }
  virtual void SetIceUfrag(const std::string& ufrag) { ice_ufrag_ = ufrag; }
  virtual void SetIcePwd(const std::string& pwd) { ice_pwd_ = pwd; }
  virtual bool SetRemoteFingerprint(const std::string& alg, const uint8* digest,
                                    size_t digest_len) {
    dtls_fingerprint_ = talk_base::SSLFingerprint(alg, digest, digest_len);
    return true;
  }

  virtual void Connect() {
    if (state_ == STATE_INIT) {
      state_ = STATE_CONNECTING;
    }
  }
  virtual void Reset() {
    if (state_ != STATE_INIT) {
      state_ = STATE_INIT;
      if (dest_) {
        dest_->state_ = STATE_INIT;
        dest_->dest_ = NULL;
        dest_ = NULL;
      }
    }
  }

  void SetWritable(bool writable) {
    set_writable(writable);
  }

  void SetDestination(FakeTransportChannel* dest) {
    if (state_ == STATE_CONNECTING && dest) {
      // This simulates the delivery of candidates.
      dest_ = dest;
      dest_->dest_ = this;
      if (identity_ && dest_->identity_) {
        do_dtls_ = true;
        dest_->do_dtls_ = true;
        NegotiateSrtpCiphers();
      }
      state_ = STATE_CONNECTED;
      dest_->state_ = STATE_CONNECTED;
      set_writable(true);
      dest_->set_writable(true);
    } else if (state_ == STATE_CONNECTED && !dest) {
      // Simulates loss of connectivity, by asymmetrically forgetting dest_.
      dest_ = NULL;
      state_ = STATE_CONNECTING;
      set_writable(false);
    }
  }

  virtual int SendPacket(const char* data, size_t len, int flags) {
    if (state_ != STATE_CONNECTED) {
      return -1;
    }

    if (flags != PF_SRTP_BYPASS && flags != 0) {
      return -1;
    }

    PacketMessageData* packet = new PacketMessageData(data, len);
    if (async_) {
      talk_base::Thread::Current()->Post(this, 0, packet);
    } else {
      talk_base::Thread::Current()->Send(this, 0, packet);
    }
    return len;
  }
  virtual int SetOption(talk_base::Socket::Option opt, int value) {
    return true;
  }
  virtual int GetError() {
    return 0;
  }

  virtual void OnSignalingReady() {
  }
  virtual void OnCandidate(const Candidate& candidate) {
  }

  virtual void OnMessage(talk_base::Message* msg) {
    PacketMessageData* data = static_cast<PacketMessageData*>(
        msg->pdata);
    dest_->SignalReadPacket(dest_, data->packet.data(),
                            data->packet.length(), 0);
    delete data;
  }

  bool SetLocalIdentity(talk_base::SSLIdentity* identity) {
    identity_ = identity;

    return true;
  }

  bool IsDtlsActive() const {
    return do_dtls_;
  }

  bool SetSrtpCiphers(const std::vector<std::string>& ciphers) {
    srtp_ciphers_ = ciphers;
    return true;
  }

  virtual bool GetSrtpCipher(std::string* cipher) {
    if (!chosen_srtp_cipher_.empty()) {
      *cipher = chosen_srtp_cipher_;
      return true;
    }
    return false;
  }

  virtual bool ExportKeyingMaterial(const std::string& label,
                                    const uint8* context,
                                    size_t context_len,
                                    bool use_context,
                                    uint8* result,
                                    size_t result_len) {
    if (!chosen_srtp_cipher_.empty()) {
      memset(result, 0xff, result_len);
      return true;
    }

    return false;
  }

  virtual void NegotiateSrtpCiphers() {
    for (std::vector<std::string>::const_iterator it1 = srtp_ciphers_.begin();
        it1 != srtp_ciphers_.end(); ++it1) {
      for (std::vector<std::string>::const_iterator it2 =
              dest_->srtp_ciphers_.begin();
          it2 != dest_->srtp_ciphers_.end(); ++it2) {
        if (*it1 == *it2) {
          chosen_srtp_cipher_ = *it1;
          dest_->chosen_srtp_cipher_ = *it2;
          return;
        }
      }
    }
  }

 private:
  enum State { STATE_INIT, STATE_CONNECTING, STATE_CONNECTED };
  Transport* transport_;
  FakeTransportChannel* dest_;
  State state_;
  bool async_;
  talk_base::SSLIdentity* identity_;
  bool do_dtls_;
  std::vector<std::string> srtp_ciphers_;
  std::string chosen_srtp_cipher_;
  TransportRole role_;
  uint64 tiebreaker_;
  IceProtocolType ice_proto_;
  std::string ice_ufrag_;
  std::string ice_pwd_;
  talk_base::SSLFingerprint dtls_fingerprint_;
};

// Fake transport class, which can be passed to anything that needs a Transport.
// Can be informed of another FakeTransport via SetDestination (low-tech way
// of doing candidates)
class FakeTransport : public Transport {
 public:
  typedef std::map<int, FakeTransportChannel*> ChannelMap;
  FakeTransport(talk_base::Thread* signaling_thread,
                talk_base::Thread* worker_thread,
                const std::string& content_name,
                PortAllocator* alllocator = NULL)
      : Transport(signaling_thread, worker_thread,
                  content_name, "test_type", NULL),
      dest_(NULL),
      async_(false),
      identity_(NULL) {
  }
  ~FakeTransport() {
    DestroyAllChannels();
  }

  const ChannelMap& channels() const { return channels_; }

  void SetAsync(bool async) { async_ = async; }
  void SetDestination(FakeTransport* dest) {
    dest_ = dest;
    for (ChannelMap::iterator it = channels_.begin(); it != channels_.end();
         ++it) {
      it->second->SetLocalIdentity(identity_);
      SetChannelDestination(it->first, it->second);
    }
  }

  void SetWritable(bool writable) {
    for (ChannelMap::iterator it = channels_.begin(); it != channels_.end();
         ++it) {
      it->second->SetWritable(writable);
    }
  }

  void set_identity(talk_base::SSLIdentity* identity) {
    identity_ = identity;
  }

  using Transport::local_description;
  using Transport::remote_description;

 protected:
  virtual TransportChannelImpl* CreateTransportChannel(int component) {
    if (channels_.find(component) != channels_.end()) {
      return NULL;
    }
    FakeTransportChannel* channel =
        new FakeTransportChannel(this, content_name(), component);
    channel->SetAsync(async_);
    SetChannelDestination(component, channel);
    channels_[component] = channel;
    return channel;
  }
  virtual void DestroyTransportChannel(TransportChannelImpl* channel) {
    channels_.erase(channel->component());
    delete channel;
  }

 private:
  FakeTransportChannel* GetFakeChannel(int component) {
    ChannelMap::iterator it = channels_.find(component);
    return (it != channels_.end()) ? it->second : NULL;
  }
  void SetChannelDestination(int component,
                             FakeTransportChannel* channel) {
    FakeTransportChannel* dest_channel = NULL;
    if (dest_) {
      dest_channel = dest_->GetFakeChannel(component);
      if (dest_channel) {
        dest_channel->SetLocalIdentity(dest_->identity_);
      }
    }
    channel->SetDestination(dest_channel);
  }

  // Note, this is distinct from the Channel map owned by Transport.
  // This map just tracks the FakeTransportChannels created by this class.
  ChannelMap channels_;
  FakeTransport* dest_;
  bool async_;
  talk_base::SSLIdentity* identity_;
};

// Fake session class, which can be passed into a BaseChannel object for
// test purposes. Can be connected to other FakeSessions via Connect().
class FakeSession : public BaseSession {
 public:
  explicit FakeSession()
      : BaseSession(talk_base::Thread::Current(),
                    talk_base::Thread::Current(),
                    NULL, "", "", true),
      fail_create_channel_(false) {
  }
  explicit FakeSession(bool initiator)
      : BaseSession(talk_base::Thread::Current(),
                    talk_base::Thread::Current(),
                    NULL, "", "", initiator),
      fail_create_channel_(false) {
  }

  FakeTransport* GetTransport(const std::string& content_name) {
    return static_cast<FakeTransport*>(
        BaseSession::GetTransport(content_name));
  }

  void Connect(FakeSession* dest) {
    // Simulate the exchange of candidates.
    CompleteNegotiation();
    dest->CompleteNegotiation();
    for (TransportMap::const_iterator it = transport_proxies().begin();
        it != transport_proxies().end(); ++it) {
      static_cast<FakeTransport*>(it->second->impl())->SetDestination(
          dest->GetTransport(it->first));
    }
  }

  virtual TransportChannel* CreateChannel(
      const std::string& content_name,
      const std::string& channel_name,
      int component) {
    if (fail_create_channel_) {
      return NULL;
    }
    return BaseSession::CreateChannel(content_name, channel_name, component);
  }

  void set_fail_channel_creation(bool fail_channel_creation) {
    fail_create_channel_ = fail_channel_creation;
  }

  // TODO: Hoist this into Session when we re-work the Session code.
  void set_ssl_identity(talk_base::SSLIdentity* identity) {
    for (TransportMap::const_iterator it = transport_proxies().begin();
        it != transport_proxies().end(); ++it) {
      // We know that we have a FakeTransport*

      static_cast<FakeTransport*>(it->second->impl())->set_identity
          (identity);
    }
  }

 protected:
  virtual Transport* CreateTransport(const std::string& content_name) {
    return new FakeTransport(signaling_thread(), worker_thread(), content_name);
  }

  void CompleteNegotiation() {
    for (TransportMap::const_iterator it = transport_proxies().begin();
        it != transport_proxies().end(); ++it) {
      it->second->CompleteNegotiation();
      it->second->ConnectChannels();
    }
  }

 private:
  bool fail_create_channel_;
};

}  // namespace cricket

#endif  // TALK_P2P_BASE_FAKESESSION_H_