text:
package com.ftfl.icareapplication.activity;

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

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.ftfl.icareapplication.R;
import com.ftfl.icareapplication.database.ProfileDataSource;
import com.ftfl.icareapplication.model.Profile;

public class ProfileListActivity extends Activity {

	ProfileDataSource mProfileDS = null;
	List<Profile> mProfileList = new ArrayList<Profile>();
	List<String> mNamesList = new ArrayList<String>();
	List<String> mIdList = new ArrayList<String>();
	ListView mListView = null;
	Integer mPosition = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_profile_listview);

		 //Naseer Action bar
  		ActionBar bar = getActionBar();
  		bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00868B")));

		final String[] option = new String[] { "View Detail","Edit Data", "Delete Data" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.select_dialog_item, option);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle("Select Option");
		builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Log.e("Selected Item", String.valueOf(which));
				if (which == 0) {
					viewData(mPosition);
				}
				if (which == 1) {
					editData(mPosition);
				}

				if (which == 2) {
					deleteData(mPosition);
				}
			}

		});
		final AlertDialog dialog = builder.create();

		setListData();
		mListView = (ListView) findViewById(R.id.lv_profilelistview2);

		ArrayAdapter<String> mProfileAdapter = new ArrayAdapter<String>(this,
		        android.R.layout.simple_list_item_1, mNamesList);

		mListView.setAdapter(mProfileAdapter);

		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mPosition = position;
				dialog.show();
				//startActivity(new Intent(ProfileListHomeActivity.this, DiseViewHomeActivity.class));
			}
		});
	}

	private void setListData() {
		ProfileDataSource profiledata = new ProfileDataSource(this);
		mProfileList = profiledata.iCareProfilesList();
		for (int i = 0; i < mProfileList.size(); i++) {
			Profile mProfile = mProfileList.get(i);
			mIdList.add(mProfile.getId());
			mNamesList.add(mProfile.getName());
		}

	}
	public void viewData(Integer ePosition)
	{
		Intent mEditIntent = new Intent(getApplicationContext(),
				ProfileViewActivity.class);
		Long id = Long.parseLong(mIdList.get(ePosition));
		mEditIntent.putExtra("id", id.toString());
		startActivity(mEditIntent);
	}
	public void editData(Integer ePosition)
	{
		Intent mEditIntent = new Intent(getApplicationContext(),
				CreateProfileActivity.class);
		Long id = Long.parseLong(mIdList.get(ePosition));
		mEditIntent.putExtra("id", id.toString());
		startActivity(mEditIntent);

	}

	public void deleteData(Integer ePosition)
	{
		mProfileDS = new ProfileDataSource(this);

		Long mId = Long.parseLong(mIdList.get(ePosition));
		mProfileDS.deleteData(mId);

	 }

}


text:
.. _api:

API
===

.. currentmodule:: characteristic

``characteristic`` consists of several class decorators that add features to your classes.
There are four that add *one* feature each to your class.
And then there's the helper ``@attributes`` that combines them all into one decorator so you don't have to repeat the attribute list multiple times.

Generally the decorators take a list of attributes as their first positional argument.
This list can consists of either native strings\ [*]_ for simple cases or instances of :class:`Attribute` that allow for more customization of ``characteristic``\ 's behavior.

The easiest way to get started is to have a look at the :doc:`examples` to get a feeling for ``characteristic`` and return later for details!

.. [*] Byte strings on Python 2 and Unicode strings on Python 3.

.. note::

   Every argument except for ``attrs`` for decorators and ``name`` for :class:`Attribute` is a **keyword argument**.
   Their positions are coincidental and not guaranteed to remain stable.

.. autofunction:: attributes

.. autofunction:: with_repr

   .. doctest::

      >>> from characteristic import with_repr
      >>> @with_repr(["a", "b"])
      ... class RClass(object):
      ...     def __init__(self, a, b):
      ...         self.a = a
      ...         self.b = b
      >>> c = RClass(42, "abc")
      >>> print c
      <RClass(a=42, b='abc')>

.. autofunction:: with_cmp

   .. doctest::

      >>> from characteristic import with_cmp
      >>> @with_cmp(["a", "b"])
      ... class CClass(object):
      ...     def __init__(self, a, b):
      ...         self.a = a
      ...         self.b = b
      >>> o1 = CClass(1, "abc")
      >>> o2 = CClass(1, "abc")
      >>> o1 == o2  # o1.a == o2.a and o1.b == o2.b
      True
      >>> o1.c = 23
      >>> o2.c = 42
      >>> o1 == o2  # attributes that are not passed to with_cmp are ignored
      True
      >>> o3 = CClass(2, "abc")
      >>> o1 < o3  # because 1 < 2
      True
      >>> o4 = CClass(1, "bca")
      >>> o1 < o4  # o1.a == o4.a, but o1.b < o4.b
      True

.. autofunction:: with_init

   .. doctest::

      >>> from characteristic import with_init, Attribute
      >>> @with_init(["a",
      ...             Attribute("b", default_factory=lambda: 2),
      ...             Attribute("_c")])
      ... class IClass(object):
      ...     def __init__(self):
      ...         if self.b != 2:
      ...             raise ValueError("'b' must be 2!")
      >>> o1 = IClass(a=1, b=2, c=3)
      >>> o2 = IClass(a=1, c=3)
      >>> o1._c
      3
      >>> o1.a == o2.a
      True
      >>> o1.b == o2.b
      True
      >>> IClass()
      Traceback (most recent call last):
        ...
      ValueError: Missing keyword value for 'a'.
      >>> IClass(a=1, b=3)  # the custom __init__ is called after the attributes are initialized
      Traceback (most recent call last):
        ...
      ValueError: 'b' must be 2!

   .. note::

      The generated initializer explicitly does *not* support positional arguments.
      Those are *always* passed to the existing ``__init__`` unaltered.
      Used keyword arguments will *not* be passed to the original ``__init__`` method and have to be accessed on the class (i.e. ``self.a``).

.. autofunction:: immutable

   .. doctest::

      >>> from characteristic import immutable
      >>> @immutable([Attribute("foo")])
      ... class ImmutableClass(object):
      ...     foo = "bar"
      >>> ic = ImmutableClass()
      >>> ic.foo
      'bar'
      >>> ic.foo = "not bar"
      Traceback (most recent call last):
        ...
      AttributeError: Attribute 'foo' of class 'ImmutableClass' is immutable.

   Please note, that that doesn't mean that the attributes themselves are immutable too:

   .. doctest::

      >>> @immutable(["foo"])
      ... class C(object):
      ...     foo = []
      >>> i = C()
      >>> i.foo = [42]
      Traceback (most recent call last):
       ...
      AttributeError: Attribute 'foo' of class 'C' is immutable.
      >>> i.foo.append(42)
      >>> i.foo
      [42]

.. autoclass:: Attribute

.. autofunction:: strip_leading_underscores

   .. doctest::

      >>> from characteristic import strip_leading_underscores
      >>> strip_leading_underscores("_foo")
      'foo'
      >>> strip_leading_underscores("__bar")
      'bar'
      >>> strip_leading_underscores("___qux")
      'qux'

.. autodata:: NOTHING

redpajama_set_name: RedPajamaGithub


text:
module Pubnub
  class Time
    include Pubnub::Event
    include Pubnub::SingleEvent
    include Pubnub::Formatter
    include Pubnub::Validator

    def initialize(options, app)
      super
      @channel = @channel.first
      @event = 'time'
      @doesnt_require_callback = true
    end

    def validate!
      super
      # check callback
      raise ArgumentError.new(:object => self, :message => 'Callback parameter is required while using async time') if !@http_sync && @callback.blank?
    end

    private

    def path(app)
      '/time/0'
    end

    def timetoken(parsed_response)
      parsed_response.first if parsed_response.is_a? Array
    end

    def format_envelopes(response, app, error)

      parsed_response = Parser.parse_json(response.body) if Parser.valid_json?(response.body)

      envelopes = Array.new
      envelopes << Envelope.new(
          {
              :message           => timetoken(parsed_response),
              :response_message  => timetoken(parsed_response),
              :timetoken         => timetoken(parsed_response)
          },
          app
      )

      envelopes = add_common_data_to_envelopes(envelopes, response, app, error)

      envelopes

    end

  end
end


text:
package org.apache.zeppelin.interpreter;

import static org.junit.Assert.*;

import java.io.IOException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class InterpreterOutputTest implements InterpreterOutputListener {
  private InterpreterOutput out;
  int numAppendEvent;
  int numUpdateEvent;

  @Before
  public void setUp() {
    out = new InterpreterOutput(this);
    numAppendEvent = 0;
    numUpdateEvent = 0;
  }

  @After
  public void tearDown() throws IOException {
    out.close();
  }

  @Test
  public void testDetectNewline() throws IOException {
    out.write("hello\nworld");
    assertEquals("hello\n", new String(out.toByteArray()));
    assertEquals(1, numAppendEvent);
    assertEquals(1, numUpdateEvent);

    out.write("\n");
    assertEquals("hello\nworld\n", new String(out.toByteArray()));
    assertEquals(2, numAppendEvent);
    assertEquals(1, numUpdateEvent);
  }

  @Test
  public void testFlush() throws IOException {
    out.write("hello\nworld");
    assertEquals("hello\n", new String(out.toByteArray()));
    assertEquals(1, numAppendEvent);
    assertEquals(1, numUpdateEvent);

    out.flush();
    assertEquals("hello\nworld", new String(out.toByteArray()));
    assertEquals(2, numAppendEvent);
    assertEquals(1, numUpdateEvent);

    out.clear();
    out.write("%html div");
    assertEquals("", new String(out.toByteArray()));
    assertEquals(InterpreterResult.Type.TEXT, out.getType());

    out.flush();
    out.write("%html div");
    assertEquals("div", new String(out.toByteArray()));
    assertEquals(InterpreterResult.Type.HTML, out.getType());
  }

  @Test
  public void testType() throws IOException {
    // default output stream type is TEXT
    out.write("Text\n");
    assertEquals(InterpreterResult.Type.TEXT, out.getType());
    assertEquals("Text\n", new String(out.toByteArray()));
    assertEquals(1, numAppendEvent);
    assertEquals(1, numUpdateEvent);

    // change type
    out.write("%html\n");
    assertEquals(InterpreterResult.Type.HTML, out.getType());
    assertEquals("", new String(out.toByteArray()));
    assertEquals(1, numAppendEvent);
    assertEquals(2, numUpdateEvent);

    // none TEXT type output stream does not generate append event
    out.write("
html
\n");
    assertEquals(InterpreterResult.Type.HTML, out.getType());
    assertEquals(1, numAppendEvent);
    assertEquals(2, numUpdateEvent);
    assertEquals("
html
\n", new String(out.toByteArray()));

    // change type to text again
    out.write("%text hello\n");
    assertEquals(InterpreterResult.Type.TEXT, out.getType());
    assertEquals(2, numAppendEvent);
    assertEquals(3, numUpdateEvent);
    assertEquals("hello\n", new String(out.toByteArray()));
  }

  @Test
  public void testType2() throws IOException {
    out.write("%html\nHello");
    assertEquals(InterpreterResult.Type.HTML, out.getType());
  }

  @Override
  public void onAppend(InterpreterOutput out, byte[] line) {
    numAppendEvent++;
  }

  @Override
  public void onUpdate(InterpreterOutput out, byte[] output) {
    numUpdateEvent++;
  }
}


text:
module Viadeo
  def self.request(method, options={})
    headers = {
      :user_agent => "Viadeo gem/#{Viadeo::VERSION}",
      :authorization => "Bearer #{options[:access_token]}",
      :content_type => "application/x-www-form-urlencoded;charset=UTF-8"
    }
    timeout_options = {timeout: Viadeo.config.timeout, open_timeout: Viadeo.config.open_timeout}

    conn = Faraday.new(:url => Viadeo.config.url) do |faraday|
      faraday.request  :url_encoded             # form-encode POST params
      faraday.response :logger                  # log requests to STDOUT
      faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
    end
    response = conn.send(method) do |req|
      req.url(options[:id].nil? ?  options[:url] : options[:id])
      req.headers = headers
      req.options = timeout_options
      req.params = options[:params] if options[:params]
    end
    Viadeo.log "response : body : " + response.body
    Viadeo::Util.filter_response(response)
  end
end


text:
package com.example1.locationapp;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import Controller.BitmapConverter;
import Controller.LocalFileLoder;
import Controller.LocalFileSaver;
import InternetConnection.ConnectToInternet;
import InternetConnection.ElasticSearchResponse;
import InternetConnection.ElasticSearchSearchResponse;
import Model.CommentUser;
import Model.Comments;
import Model.FavouriteComment;
import Model.FavouriteModel;
import Model.IDModel;
import Model.SubCommentModel;
import Model.UserModel;
import Sort.SubCommentSort;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

/**
 * this class is to control the subFavouriteComment-comments part
 * It will find subFavouriteComment-comment of the master comment
 * @author qyu4
 */
public class SubCommetsRead extends Activity {
	public static final String SERVER = "http://cmput301.softwareprocess.es:8080/cmput301w14t11/";
	public static final String MASTERCOMMENT = "emouse/";
	private ListView listViewSubComment;
	private EditText editText;
	private Button button1;
	private CutAdapter ListAdapter;
	private ArrayList<Comments> comment_list;
	private Bitmap bitmap;
	private int number;
	private Context content;
	private Location location;
	private GPSTracker gps;
	private HttpClient httpclient;
	private double longitude;
	private double latitude;
	private int subCoId = 1;
	private Gson gson = new Gson();
	private CommentUser someuser;
	private double radius = 0.01;
	private IDModel id_obj;
	private int ServerID;
	private LocalFileLoder fileLoader = new LocalFileLoder(this);
	private LocalFileSaver fileSaver = new LocalFileSaver(this);
	private UserModel user;
	private Comments comment1;
	private String subCommentsTitle;
	private int replyFloor=0;
	private ConnectToInternet connect = new ConnectToInternet();
	private SubCommentModel subModel = new SubCommentModel(
			comment1);
	private int flag_location=0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sub_commets_read);
		listViewSubComment = (ListView) findViewById(R.id.listViewSubComments);
		editText = (EditText) findViewById(R.id.editTextSubmitSubComments);
		button1 = (Button) findViewById(R.id.buttonSaveSubComments);
		button1.setText("Send");
		comment_list = new ArrayList<Comments>();
		ActionBar bar = getActionBar();
		bar.setHomeButtonEnabled(false);
		httpclient = new DefaultHttpClient();
		Intent intent = getIntent();
		number = intent.getIntExtra("masterID", 0);
		id_obj = new IDModel(0);
		gps = new GPSTracker(this);
		ListAdapter = new CutAdapter(SubCommetsRead.this, R.layout.listlayout,comment_list);
		content = this;
		ConnectivityManager cm =
		        (ConnectivityManager)content.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
		boolean isConnected = activeNetwork != null &&
		                      activeNetwork.isConnectedOrConnecting();
		user = fileLoader.loadFromFile();

		if (user.getUser_name().equals(""))
			bar.setTitle("Welcome, Guest");
		else
			bar.setTitle("Welcome, " + user.getUser_name());
		if (isConnected)
		{

		new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... params) {

				comment_list =subModel.get_comments(comment_list, number,httpclient);

				if (comment_list.size() == 0)
				{
					user = fileLoader.loadFromFile();
					for (int i = 0; i < user.getComment().size(); i++)
					{
						if (user.getComment().get(i).getMaster_ID() == number)
						{
							comment_list = user.getComment().get(i).getSubComment();
						}
					}
				}
				subCoId=comment_list.size()+1;
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {

				super.onPostExecute(result);
				for (int i = 0; i<comment_list.size(); i++)
				{
					float DistanceResult [] = new float[10];
					Location.distanceBetween(location.getLatitude(),location.getLongitude(),comment_list.get(i).getLat(),comment_list.get(i).getLon(),DistanceResult);
					comment_list.get(i).setDistance(DistanceResult[0]);
				}
				Collections.sort(comment_list, new SubCommentSort());
				ListAdapter.notifyDataSetChanged();
			}

		}.execute();

		}
		else
		{
			setDisconnectComment();
		}

		if (gps.canGetLocation) {
			location = gps.getLocation();
			gps.stopUsingGPS();
		} else {
			gps.showSettingsAlert();
		}

		location.setLatitude(intent.getDoubleExtra("latitude",0));
		location.setLongitude(intent.getDoubleExtra("longitude",0));
		longitude = location.getLongitude();
		latitude = location.getLatitude();
		View footerView = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.footlayout, null, false);

		listViewSubComment.addFooterView(footerView);
		editText.setHint("reply to 1");
		listViewSubComment.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				replyFloor = arg2;
				editText.setHint("reply to "+(replyFloor+1));
			}
		});
		listViewSubComment.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					final int position, long id) {
				AlertDialog.Builder builder = new AlertDialog.Builder(content);
				String items[] = { "Edit Comment","View profile","Chat" };
				builder.setItems(items, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						switch (which) {
						case 0:
							String CheckName = user.getUser_name();
							final Comments SelectedComment = comment_list.get(position);
							if(SelectedComment.getUserName().equals(CheckName))
							{

								final Dialog dialogui = new Dialog(content);
								dialogui.setContentView(R.layout.dialogui);
								dialogui.setTitle("Edit my comment");
								dialogui.show();
								final TextView locationview = (TextView) dialogui.findViewById(R.id.textView1);
								final TextView locationview2 = (TextView) dialogui.findViewById(R.id.textView2);
								Button Changebutton = (Button) dialogui.findViewById(R.id.button1);
								Button Locationbutton = (Button) dialogui.findViewById(R.id.button2);
								final EditText titleedit = (EditText) dialogui.findViewById(R.id.editText1);
								final EditText subjectedit = (EditText) dialogui.findViewById(R.id.editText2);
								Locationbutton.setOnClickListener(new OnClickListener() {

									@Override
									public void onClick(View v) {
										locationview.setText("Enter Latitude");
										locationview2.setText("Enter Longitude");
										titleedit.setHint("Lat");
										subjectedit.setHint("Lon");
										flag_location = 1;
									}
								});
								Changebutton.setOnClickListener(new OnClickListener() {

									@Override
									public void onClick(View v) {
										if(flag_location==1)
										{
											double lat = Double.parseDouble(titleedit.getText().toString());
											double lon = Double.parseDouble(subjectedit.getText().toString());
											comment_list.get(position).setLat(lat);
											comment_list.get(position).setLon(lon);
											flag_location = 0;

										}
										comment_list.get(position).setThe_comment(titleedit.getText().toString());
										comment_list.get(position).setSubject_comment(subjectedit.getText().toString());
										ListAdapter.notifyDataSetChanged();
										dialogui.dismiss();

										new AsyncTask<Void,Void,Void>()
										{

											@Override
											protected Void doInBackground(
													Void... params) {
												HttpClient httpclient = new DefaultHttpClient();
												HttpPost httpPost = new HttpPost("http://cmput301.softwareprocess.es:8080/cmput301w14t11/emouse/"+comment_list.get(position).getSub_ID());
												try {
													StringEntity data = new StringEntity(gson.toJson(comment_list.get(position)));
													httpPost.setEntity(data);
													httpPost.setHeader("Accept", "application/json");
													httpclient.execute(httpPost);
												} catch (UnsupportedEncodingException e) {

													e.printStackTrace();
												} catch (ClientProtocolException e) {

													e.printStackTrace();
												} catch (IOException e) {

													e.printStackTrace();
												}
												return null;
											}

										}.execute();

										Toast.makeText(content,"Comment has changed",Toast.LENGTH_SHORT).show();
									}
								});
							}
							else
							{
								Toast.makeText(content,"You can only edit your own comment",Toast.LENGTH_SHORT).show();
							}
							break;
						case 1:
							final String name = comment_list.get(position).getUserName();
							new AsyncTask<Void, Void, Void>()
							{

								@Override
								protected void onPostExecute(Void result) {
									super.onPostExecute(result);
									if (flag==0)
									{
										AlertDialog.Builder builder = new AlertDialog.Builder(SubCommetsRead.this);
										builder.setTitle("User has did not create profile");
										builder.setMessage("Please check back later");
										builder.setCancelable(true);
										builder.setPositiveButton("Okay", new DialogInterface.OnClickListener() {

											@Override
											public void onClick(DialogInterface dialog, int which) {
												dialog.cancel();
											}
										});
										AlertDialog adialog = builder.create();
										adialog.show();
									}
								}
								int flag = 0;

								@Override
								protected Void doInBackground(Void... params) {
									try{
										Gson gson = new Gson();

										HttpPost httppost = new HttpPost("http://cmput301.softwareprocess.es:8080/cmput301w14t11/profile/_search?pretty=1");
										String query_profile = "{\"query\":{\"match\":{\"name\":\""+name+"\"}}}";
										StringEntity entity;
										entity = new StringEntity(query_profile);
										httppost.setHeader("Accept", "application/json");
										httppost.setEntity(entity);
										HttpResponse response = httpclient.execute(httppost);
										String json1 = connect.getEntityContent(response);
										Type elasticSearchSearchResponseType = new TypeToken<ElasticSearchSearchResponse<CommentUser>>() {
										}.getType();
										ElasticSearchSearchResponse<CommentUser> esResponse = gson.fromJson(
												json1, elasticSearchSearchResponseType);

										for(ElasticSearchResponse<CommentUser> r : esResponse.getHits())
										{   // get some result, then flag is 1
											someuser = r.getSource();
											flag=1;
											break;
										}
										if (flag==1)
										{
											// have result , result code 939
											Intent intent_profile = new Intent();
											intent_profile.setClass(content, ProfileActivity.class);

											intent_profile.putExtra("name",someuser);
											startActivityForResult(intent_profile, 939);
										}
										}
										 catch (ClientProtocolException e) {
											e.printStackTrace();
										} catch (IOException e) {
											e.printStackTrace();
										}
										return null;
								}
							}.execute();
							break;
							// adding chat function to the app
							case 2:
								Comments comments = comment_list.get(position);
								comments.setUserName(user.getUser_name());
								Intent intent = new Intent(SubCommetsRead.this,ChatActivity.class);
								intent.putExtra("UserName",comments.getUserName());
								startActivity(intent);

						}
					}
				});
				AlertDialog dialog = builder.create();
				dialog.show();
				return false;
			}
		});

		listViewSubComment.setAdapter(ListAdapter);
		footerView.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				editText.setHint("reply to 1");
				ConnectivityManager cm =
				        (ConnectivityManager)content.getSystemService(Context.CONNECTIVITY_SERVICE);

				NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
				boolean isConnected = activeNetwork != null &&
				                      activeNetwork.isConnectedOrConnecting();
				if (isConnected)
				{
					new AsyncTask<Void, Void, Void>() {

						@Override
						protected Void doInBackground(Void... params) {
							comment_list.clear();
							comment_list=subModel.get_comments(comment_list, number,httpclient);
							return null;
						}

						@Override
						protected void onPostExecute(Void result) {

							super.onPostExecute(result);
							for (int i = 0; i<comment_list.size(); i++)
							{
								float DistanceResult [] = new float[10];
								Location.distanceBetween(location.getLatitude(),location.getLongitude(),comment_list.get(i).getLat(),comment_list.get(i).getLon(),DistanceResult);
								comment_list.get(i).setDistance(DistanceResult[0]);
							}
							Collections.sort(comment_list, new SubCommentSort());
							ListAdapter.notifyDataSetChanged();
						}

					}.execute();
				}
				else
				{
					setDisconnectComment();
				}
			}
		});
		button1.setOnClickListener(new MyButton1Listener());
	}

	/**
	 * there are two subFavouriteComment-munu list which is using for saving favourite and
	 * another is using for save, it will help us save the comments and
	 * subFavouriteComment-comments in the file.
	 * @param item -- selected item
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.fav:
			faviSaving(0);
			break;
		case R.id.save:
			faviSaving(1);
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * Save the Faviourite comments into the local file
	 * @param code -- used to determine between faviourite and saving
	 */
	public void faviSaving(int code)
	{
		user = new UserModel();
		user = fileLoader.loadFromFile();
		boolean saved=false;
		if (user.getUser_name().equals(""))
		{
			Toast.makeText(SubCommetsRead.this,
					"Guest cannot add this comment",
					Toast.LENGTH_SHORT).show();
		}
		else
		{
			saved = saved(code, saved);
			if (saved == true)
			{
				Toast.makeText(SubCommetsRead.this,
						"You already saved this comment",
						Toast.LENGTH_SHORT).show();
			}
			else
			{
				FavouriteComment favouriteComment = new FavouriteComment();
				ArrayList<FavouriteComment> subcomment = new ArrayList<FavouriteComment>();
				favouriteComment.setText(comment_list.get(0).getSubject_comment());
				favouriteComment.setTitle(comment_list.get(0).getThe_comment());
				favouriteComment.setImage(comment_list.get(0).getImage_encode());
				favouriteComment.setDistance(comment_list.get(0).getDistance());
				favouriteComment.setUserName(comment_list.get(0).getUserName());
				favouriteComment.setLocation(location.getLatitude(), location.getLongitude());
				favouriteComment.setID(number);
				subcomment.add(favouriteComment);
				for (int i =1;i<comment_list.size();i++)
				{
					FavouriteComment subFavouriteComment = new FavouriteComment();
					subFavouriteComment.setText(comment_list.get(i).getSubject_comment());
					subFavouriteComment.setTitle(comment_list.get(i).getThe_comment());
					subFavouriteComment.setImage(comment_list.get(i).getImage_encode());
					subFavouriteComment.setDistance(comment_list.get(i).getDistance());
					subFavouriteComment.setUserName(comment_list.get(i).getUserName());
					subFavouriteComment.setLocation(location.getLatitude(), location.getLongitude());
					subcomment.add(subFavouriteComment);
				}

				FavouriteModel favouriteModel = new FavouriteModel(user.getUser_name(), favouriteComment,
						subcomment);
				favouriteModel.setID(number);
				favouriteModel.setCode(code);
				user.addFaviourte(favouriteModel);
				fileSaver.saveInFile(user);
			}

		}
	}

	/**
	 * this is code to save comments to local
	 * @param code -- 0 for favourite 1 for personal saving
	 * @param saved -- true -- it has been saved, false else
	 * @return
	 * true -- it has been saved, false else
	 */
	private boolean saved(int code, boolean saved) {
		for (int i = 0; i < user.getFaviourte().size(); i++) {
			if (user.getFaviourte().get(i).getID() == number
					&& user.getFaviourte().get(i).getUsername()
							.equals(user.getUser_name())
					&& user.getFaviourte().get(i).getCode() == code) {
				saved = true;
			}
		}
		return saved;
	}

	/**
	 * Inflate the menu; this adds items to the action bar if it is present.
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.sub_commets_read, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode==RESULT_OK)
		{
			switch(requestCode)
			{
				case 2828:
					String file = data.getStringExtra("image");
					String file2 = data.getStringExtra("choseimage");
					if (file != null) {
						bitmap = BitmapFactory.decodeFile(file);
					} else {
						bitmap = BitmapFactory.decodeFile(file2);
					}
					if(bitmap!=null)
					{
						Toast.makeText(SubCommetsRead.this, "Picture added", Toast.LENGTH_SHORT).show();
					}
					break;
				}
		}
	}

	/**
	 * clikc this button to add picture
	 * @param view
	 */
	public void picture(View view)
	{
		Intent intent = new Intent(this, ChoseImageActivity.class);
		startActivityForResult(intent,2828);
	}
	class MyButton1Listener implements OnClickListener {

		@Override
		public void onClick(View v) {

			user = fileLoader.loadFromFile();
			if (user.getUser_name().equals(""))
			{
				Toast.makeText(getBaseContext(),
						"Guest cannot add comments!!!",
						Toast.LENGTH_SHORT).show();
			}
			else
			{
				String title = editText.getText().toString();
				radius = radius + 0.01;
				if ("".equals(title)) {

					Toast.makeText(getBaseContext(),
							"Title is empty! add some words please!",
							Toast.LENGTH_SHORT).show();

				} else {
					new AsyncTask<Void, Void, Void>() {
						ProgressDialog dialog1 = new ProgressDialog(content);

						@Override
						protected void onPreExecute() {

							dialog1.setTitle("Loading... Please wait");
							dialog1.show();
							super.onPreExecute();
							new AsyncTask<Void, Void, Void>() {

								@Override
								protected Void doInBackground(Void... params) {

									ServerID = connect.get_id(content);
									ServerID++;
									return null;
								}

							}.execute();

						}

						@Override
						protected Void doInBackground(Void... params) {

							if (bitmap == null) {
								subCommentsTitle=subCoId+". Relpy to ";
								user = fileLoader.loadFromFile();
								final Comments new_comment = new Comments(0,
										number, subCoId,ServerID, (subCommentsTitle+" "+(replyFloor+1)).toString(), editText.getText()
												.toString(), new Date(),
										longitude, latitude, user.getUser_name());
								subModel.insertMaster(new_comment, ServerID);
								subCoId++;
								replyFloor =0;
							} else {
								subCommentsTitle=subCoId+". Relpy to ";
								JsonElement encode_image = new BitmapConverter().serialize(bitmap, null, null);
								final Comments new_comment = new Comments(0,
										number, subCoId, ServerID, (subCommentsTitle+" "+(replyFloor+1)), editText.getText()
												.toString(), new Date(),
										longitude, latitude, encode_image,
										user.getUser_name());
								subModel.insertMaster(new_comment, ServerID);
								subCoId++;
								replyFloor =0;

							}
							return null;
						}

						@Override
						protected void onPostExecute(Void result) {

							super.onPostExecute(result);
							new AsyncTask<Void, Void, Void>() {

								@Override
								protected Void doInBackground(Void... params) {

									id_obj.setId_for_master(ServerID);
									try {
										connect.insert(id_obj,content);
									} catch (IllegalStateException e) {

										e.printStackTrace();
									} catch (IOException e) {

										e.printStackTrace();
									}
									return null;
								}
							}.execute();
                        dialog1.dismiss();
                        bitmap=null;
                        editText.setText("");
						}
					}.execute();
					setResult(RESULT_OK);
				}
			}

		}
	}

	/**
	 * use this function to load from file, and show comments in listview
	 */
	public void setDisconnectComment()
	{

			user = fileLoader.loadFromFile();
			for (int i = 0; i < user.getComment().size(); i++)
			{
				if (user.getComment().get(i).getMaster_ID() == number)
				{
					comment_list = user.getComment().get(i).getSubComment();

				}
			}

			Collections.sort(comment_list, new SubCommentSort());
			subCoId=comment_list.size()+1;
			ListAdapter = new CutAdapter(SubCommetsRead.this, R.layout.listlayout,comment_list);
			listViewSubComment.setAdapter(ListAdapter);
			ListAdapter.notifyDataSetChanged();
	}

	/**
	 * go back to MainActivty from SUBcomment
	 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		Intent intent = new Intent();
		intent.setClass(SubCommetsRead.this, MainActivity.class);
	}
}


text:
"""Module that scrapes concept data to be used by the idea generator

Runs through a number of "Scrapers" that take concept data, such as magic
types, locations, and animals, and saves these in JSON files to be
loaded into the database as fixtures.
"""

import json
import os
import requests
from bs4 import BeautifulSoup

class Scraper:
    """Abstract class for a scraper object. Must implement a scrape method."""
    def scrape(self):
        raise NotImplementedError('User must implement the scrape method')

class MagicScraper(Scraper):
    """Scrapes types of magic from http://powerlisting.wikia.com/wiki/Magic"""
    def __init__(self, source):
        """ Initialize with URL for scraper"""
        self.source = source

    def scrape(self):
        """Scrapes the types of magic from the URL and returns the list.

        :return : list types of magic
        """
        response = requests.get(self.source)
        soup = BeautifulSoup(response.text, 'html.parser')
        types = []
        list1 = soup.select('#Types_of_Magic')[0].findNext('ul')
        list2 = list1.findNext('ul')
        for item in list1.select('li a'):
            types.append(item.text)
        for item in list2.select('li a'):
            types.append(item.text)

        return types

class AnimalScraper(Scraper):
    """Scrapes animals from Wikipedia."""
    def __init__(self, source):
        """Initialize with URL for scraper"""
        self.source = source

    def scrape(self):
        """Scrapes the names of animals from the URL and returns the list.

        :return : list names of animals
        """
        response = requests.get(self.source)
        soup = BeautifulSoup(response.text, 'html.parser')
        animals = []
        element = soup.select('#By_taxon_or_species')[0].parent
        next_element = element.next_sibling.next_sibling
        while next_element.select('#Names_for_males.2C_females.2C_young.2C_and_groups') == []:
            for item in next_element.select('li a'):
                animals.append(item.text)
            next_element = next_element.next_sibling.next_sibling

        return animals

class CreatureScraper(Scraper):
    """Scrapes mythical creatures from Wikipedia."""
    def __init__(self, base_url):
        """Initialize with base URL for scraper"""
        self.base_url = base_url

    def scrape(self):
        """Scrapes the lists of creatures from the lists from A-Z

        :return : list of mythical creatures
        """
        creatures = []
        for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
            response = requests.get(self.base_url + '_(' + letter + ')')
            soup = BeautifulSoup(response.text, 'html.parser')
            content = soup.select('#mw-content-text')[0]
            for item in content.select('li'):
                # creature = {}
                # creature['link'] = item.select('a')[0].get('href') if item.select('a') else ''
                # creature['name'] = item.text
                creatures.append(item.text.encode('ascii', errors='ignore').decode())

        return creatures

class EventScraper(Scraper):
    """Scrapes historical events from URL."""
    def __init__(self, source):
        """Initialize with source"""
        self.source = source

    def scrape(self):
        """Scrapes the URL for list of historical events

        :return : list of events
        """
        response = requests.get(self.source)
        soup = BeautifulSoup(response.text, 'html.parser')
        events = []
        for item in soup.select('.listItem__title'):
            if item.text.strip() != '':
                events.append(item.text)

        return events

class ScraperRunner:
    """Acts as the runner and controls the individual scrapers"""
    def __init__(self):
        self.data = []

    def run_scrapers(self):
        """Instantiates scrapers with sources and runs scrape."""
        magic_types = MagicScraper('http://powerlisting.wikia.com/wiki/Magic').scrape()
        self.add_fixture('Magic', magic_types)
        animals = AnimalScraper(
            'https://en.wikipedia.org/wiki/List_of_animals_by_common_name'
        ).scrape()
        self.add_fixture('Animals', animals)
        creatures = CreatureScraper(
            'https://en.wikipedia.org/wiki/List_of_legendary_creatures'
        ).scrape()
        self.add_fixture('Creatures', creatures)
        events = EventScraper(
            'http://www.ranker.com/list/most-important-historical-events-of-the-20th-century/mwahahahaha'
        ).scrape()
        self.add_fixture('Events', events)

        self.save_fixture()

    def add_fixture(self, category, items):
        """Adds to JSON object"""
        data = []
        for item in items:
            data.append({
                "model": "ideas.concept",
                "fields": {
                    "category": category,
                    "label": item
                }
            })

        self.data += data

    def save_fixture(self):
        """Saves to JSON fixture file to be loaded into the Django database."""
        with open('../ideas/fixtures/concepts.json', 'w') as handle:
            json.dump(self.data, handle)

if __name__ == '__main__':
    scraper = ScraperRunner()
    scraper.run_scrapers()


text:
#include <assert.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <vlc/vlc.h>

#include <jni.h>

#include <android/api-level.h>

#include "libvlcjni-vlcobject.h"
#include "utils.h"
#include "std_logger.h"

struct fields fields;

#define VLC_JNI_VERSION JNI_VERSION_1_2

#define THREAD_NAME "libvlcjni"
JNIEnv *jni_get_env(const char *name);

/* Pointer to the Java virtual machine
 * Note: It's okay to use a static variable for the VM pointer since there
 * can only be one instance of this shared library in a single VM
 */
static JavaVM *myVm;

static pthread_key_t jni_env_key;

/* This function is called when a thread attached to the Java VM is canceled or
 * exited */
static void jni_detach_thread(void *data)
{
    //JNIEnv *env = data;
    (*myVm)->DetachCurrentThread(myVm);
}

JNIEnv *jni_get_env(const char *name)
{
    JNIEnv *env;

    env = pthread_getspecific(jni_env_key);
    if (env == NULL) {
        /* if GetEnv returns JNI_OK, the thread is already attached to the
         * JavaVM, so we are already in a java thread, and we don't have to
         * setup any destroy callbacks */
        if ((*myVm)->GetEnv(myVm, (void **)&env, VLC_JNI_VERSION) != JNI_OK)
        {
            /* attach the thread to the Java VM */
            JavaVMAttachArgs args;
            jint result;

            args.version = VLC_JNI_VERSION;
            args.name = name;
            args.group = NULL;

            if ((*myVm)->AttachCurrentThread(myVm, &env, &args) != JNI_OK)
                return NULL;

            /* Set the attached env to the thread-specific data area (TSD) */
            if (pthread_setspecific(jni_env_key, env) != 0)
            {
                (*myVm)->DetachCurrentThread(myVm);
                return NULL;
            }
        }
    }

    return env;
}

#ifndef NDEBUG
static std_logger *p_std_logger = NULL;
#endif

jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
    JNIEnv* env = NULL;
    // Keep a reference on the Java VM.
    myVm = vm;

    if ((*vm)->GetEnv(vm, (void**) &env, VLC_JNI_VERSION) != JNI_OK)
        return -1;

    /* Create a TSD area and setup a destroy callback when a thread that
     * previously set the jni_env_key is canceled or exited */
    if (pthread_key_create(&jni_env_key, jni_detach_thread) != 0)
        return -1;

#ifndef NDEBUG
    p_std_logger = std_logger_Open("VLC-std");
#endif

#define GET_CLASS(clazz, str, b_globlal) do { \
    (clazz) = (*env)->FindClass(env, (str)); \
    if (!(clazz)) { \
        LOGE("FindClass(%s) failed", (str)); \
        return -1; \
    } \
    if (b_globlal) { \
        (clazz) = (jclass) (*env)->NewGlobalRef(env, (clazz)); \
        if (!(clazz)) { \
            LOGE("NewGlobalRef(%s) failed", (str)); \
            return -1; \
        } \
    } \
} while (0)

#define GET_ID(get, id, clazz, str, args) do { \
    (id) = (*env)->get(env, (clazz), (str), (args)); \
    if (!(id)) { \
        LOGE(#get"(%s) failed", (str)); \
        return -1; \
    } \
} while (0)

    jclass Version_clazz;
    jfieldID SDK_INT_fieldID;

    GET_CLASS(Version_clazz, "android/os/Build$VERSION", false);
    GET_ID(GetStaticFieldID, SDK_INT_fieldID, Version_clazz, "SDK_INT", "I");
    fields.SDK_INT = (*env)->GetStaticIntField(env, Version_clazz,
                                               SDK_INT_fieldID);

    GET_CLASS(fields.IllegalStateException.clazz,
              "java/lang/IllegalStateException", true);
    GET_CLASS(fields.IllegalArgumentException.clazz,
              "java/lang/IllegalArgumentException", true);
    GET_CLASS(fields.String.clazz,
              "java/lang/String", true);
    GET_CLASS(fields.FileDescriptor.clazz,
              "java/io/FileDescriptor", true);
    GET_ID(GetFieldID,
           fields.FileDescriptor.descriptorID,
           fields.FileDescriptor.clazz,
           "descriptor", "I");
    GET_CLASS(fields.VLCObject.clazz,
              "org/videolan/libvlc/VLCObject", true);
    GET_CLASS(fields.Media.clazz,
              "org/videolan/libvlc/Media", true);
    GET_CLASS(fields.Media.Track.clazz,
              "org/videolan/libvlc/Media$Track", true);
    GET_CLASS(fields.Media.Slave.clazz,
              "org/videolan/libvlc/Media$Slave", true);
    GET_CLASS(fields.MediaPlayer.clazz,
              "org/videolan/libvlc/MediaPlayer", true);
    GET_CLASS(fields.MediaPlayer.Title.clazz,
              "org/videolan/libvlc/MediaPlayer$Title", true);
    GET_CLASS(fields.MediaPlayer.Chapter.clazz,
              "org/videolan/libvlc/MediaPlayer$Chapter", true);
    GET_CLASS(fields.MediaPlayer.TrackDescription.clazz,
              "org/videolan/libvlc/MediaPlayer$TrackDescription", true);
    GET_CLASS(fields.MediaPlayer.Equalizer.clazz,
              "org/videolan/libvlc/MediaPlayer$Equalizer", true);
    GET_CLASS(fields.MediaDiscoverer.clazz,
              "org/videolan/libvlc/MediaDiscoverer", true);
    GET_CLASS(fields.MediaDiscoverer.Description.clazz,
              "org/videolan/libvlc/MediaDiscoverer$Description", true);
    GET_CLASS(fields.Dialog.clazz,
              "org/videolan/libvlc/Dialog", true);

    GET_ID(GetFieldID,
           fields.VLCObject.mInstanceID,
           fields.VLCObject.clazz,
           "mInstance", "J");

    GET_ID(GetFieldID,
           fields.MediaPlayer.Equalizer.mInstanceID,
           fields.MediaPlayer.Equalizer.clazz,
           "mInstance", "J");

    GET_ID(GetMethodID,
           fields.VLCObject.dispatchEventFromNativeID,
           fields.VLCObject.clazz,
           "dispatchEventFromNative", "(IJF)V");

    if (fields.SDK_INT <= 13)
    {
        LOGE("fields.SDK_INT is less than 13 (honeycomb_mr2): using compat WeakReference");
        GET_ID(GetMethodID,
               fields.VLCObject.getWeakReferenceID,
               fields.VLCObject.clazz,
               "getWeakReference", "()Ljava/lang/Object;");
        GET_ID(GetStaticMethodID,
               fields.VLCObject.dispatchEventFromWeakNativeID,
               fields.VLCObject.clazz,
               "dispatchEventFromWeakNative", "(Ljava/lang/Object;IJF)V");
    } else
    {
        fields.VLCObject.getWeakReferenceID = NULL;
        fields.VLCObject.dispatchEventFromWeakNativeID = NULL;
    }

    GET_ID(GetStaticMethodID,
           fields.Media.createAudioTrackFromNativeID,
           fields.Media.clazz,
           "createAudioTrackFromNative",
           "(Ljava/lang/String;Ljava/lang/String;IIIILjava/lang/String;Ljava/lang/String;II)"
           "Lorg/videolan/libvlc/Media$Track;");

    GET_ID(GetStaticMethodID,
           fields.Media.createVideoTrackFromNativeID,
           fields.Media.clazz,
           "createVideoTrackFromNative",
           "(Ljava/lang/String;Ljava/lang/String;IIIILjava/lang/String;Ljava/lang/String;IIIIIIII)"
           "Lorg/videolan/libvlc/Media$Track;");

    GET_ID(GetStaticMethodID,
           fields.Media.createSubtitleTrackFromNativeID,
           fields.Media.clazz,
           "createSubtitleTrackFromNative",
           "(Ljava/lang/String;Ljava/lang/String;IIIILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)"
           "Lorg/videolan/libvlc/Media$Track;");

    GET_ID(GetStaticMethodID,
           fields.Media.createUnknownTrackFromNativeID,
           fields.Media.clazz,
           "createUnknownTrackFromNative",
           "(Ljava/lang/String;Ljava/lang/String;IIIILjava/lang/String;Ljava/lang/String;)"
           "Lorg/videolan/libvlc/Media$Track;");

    GET_ID(GetStaticMethodID,
           fields.Media.createSlaveFromNativeID,
           fields.Media.clazz,
           "createSlaveFromNative",
           "(IILjava/lang/String;)"
           "Lorg/videolan/libvlc/Media$Slave;");

    GET_ID(GetStaticMethodID,
           fields.Media.createStatsFromNativeID,
           fields.Media.clazz,
           "createStatsFromNative",
           "(IFIFIIIIIIIIIIF)"
           "Lorg/videolan/libvlc/Media$Stats;");

    GET_ID(GetStaticMethodID,
           fields.MediaPlayer.createTitleFromNativeID,
           fields.MediaPlayer.clazz,
           "createTitleFromNative",
           "(JLjava/lang/String;I)Lorg/videolan/libvlc/MediaPlayer$Title;");

    GET_ID(GetStaticMethodID,
           fields.MediaPlayer.createChapterFromNativeID,
           fields.MediaPlayer.clazz,
           "createChapterFromNative",
           "(JJLjava/lang/String;)Lorg/videolan/libvlc/MediaPlayer$Chapter;");

    GET_ID(GetStaticMethodID,
           fields.MediaPlayer.createTrackDescriptionFromNativeID,
           fields.MediaPlayer.clazz,
           "createTrackDescriptionFromNative",
           "(ILjava/lang/String;)Lorg/videolan/libvlc/MediaPlayer$TrackDescription;");

    GET_ID(GetStaticMethodID,
           fields.MediaDiscoverer.createDescriptionFromNativeID,
           fields.MediaDiscoverer.clazz,
           "createDescriptionFromNative",
           "(Ljava/lang/String;Ljava/lang/String;I)"
           "Lorg/videolan/libvlc/MediaDiscoverer$Description;");

    GET_ID(GetStaticMethodID,
           fields.Dialog.displayErrorFromNativeID,
           fields.Dialog.clazz,
           "displayErrorFromNative",
           "(Ljava/lang/String;Ljava/lang/String;)V");

    GET_ID(GetStaticMethodID,
           fields.Dialog.displayLoginFromNativeID,
           fields.Dialog.clazz,
           "displayLoginFromNative",
           "(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)"
           "Lorg/videolan/libvlc/Dialog;");

    GET_ID(GetStaticMethodID,
           fields.Dialog.displayQuestionFromNativeID,
           fields.Dialog.clazz,
           "displayQuestionFromNative",
           "(JLjava/lang/String;Ljava/lang/String;ILjava/lang/String;"
           "Ljava/lang/String;Ljava/lang/String;)"
           "Lorg/videolan/libvlc/Dialog;");

    GET_ID(GetStaticMethodID,
           fields.Dialog.displayProgressFromNativeID,
           fields.Dialog.clazz,
           "displayProgressFromNative",
           "(JLjava/lang/String;Ljava/lang/String;ZFLjava/lang/String;)"
           "Lorg/videolan/libvlc/Dialog;");

    GET_ID(GetStaticMethodID,
           fields.Dialog.cancelFromNativeID,
           fields.Dialog.clazz,
           "cancelFromNative",
           "(Lorg/videolan/libvlc/Dialog;)V");

    GET_ID(GetStaticMethodID,
           fields.Dialog.updateProgressFromNativeID,
           fields.Dialog.clazz,
           "updateProgressFromNative",
           "(Lorg/videolan/libvlc/Dialog;FLjava/lang/String;)V");

#undef GET_CLASS
#undef GET_ID

    LOGD("JNI interface loaded.");
    return VLC_JNI_VERSION;
}

void JNI_OnUnload(JavaVM* vm, void* reserved)
{
    JNIEnv* env = NULL;

    if ((*vm)->GetEnv(vm, (void**) &env, VLC_JNI_VERSION) != JNI_OK)
        return;

    (*env)->DeleteGlobalRef(env, fields.IllegalStateException.clazz);
    (*env)->DeleteGlobalRef(env, fields.IllegalArgumentException.clazz);
    (*env)->DeleteGlobalRef(env, fields.String.clazz);
    (*env)->DeleteGlobalRef(env, fields.VLCObject.clazz);
    (*env)->DeleteGlobalRef(env, fields.Media.clazz);

    pthread_key_delete(jni_env_key);

#ifndef NDEBUG
    std_logger_Close(p_std_logger);
#endif
}

void Java_org_videolan_libvlc_LibVLC_nativeNew(JNIEnv *env, jobject thiz,
                                               jobjectArray jstringArray,
                                               jstring jhomePath)
{
    vlcjni_object *p_obj = NULL;
    libvlc_instance_t *p_libvlc = NULL;
    jstring *strings = NULL;
    const char **argv = NULL;
    int argc = 0;

    if (jhomePath)
    {
        const char *psz_home = (*env)->GetStringUTFChars(env, jhomePath, 0);
        if (psz_home)
        {
            setenv("HOME", psz_home, 1);
            (*env)->ReleaseStringUTFChars(env, jhomePath, psz_home);
        }
    }

    if (jstringArray)
    {
        argc = (*env)->GetArrayLength(env, jstringArray);

        argv = malloc(argc * sizeof(const char *));
        strings = malloc(argc * sizeof(jstring));
        if (!argv || !strings)
        {
            argc = 0;
            goto error;
        }
        for (int i = 0; i < argc; ++i)
        {
            strings[i] = (*env)->GetObjectArrayElement(env, jstringArray, i);
            if (!strings[i])
            {
                argc = i;
                goto error;
            }
            argv[i] = (*env)->GetStringUTFChars(env, strings[i], 0);
            if (!argv)
            {
                argc = i;
                goto error;
            }
        }
    }

    p_libvlc = libvlc_new(argc, argv);

error:

    if (jstringArray)
    {
        for (int i = 0; i < argc; ++i)
        {
            (*env)->ReleaseStringUTFChars(env, strings[i], argv[i]);
            (*env)->DeleteLocalRef(env, strings[i]);
        }
    }
    free(argv);
    free(strings);

    if (!p_libvlc)
    {
        throw_IllegalStateException(env, "can't create LibVLC instance");
        return;
    }

    p_obj = VLCJniObject_newFromLibVlc(env, thiz, NULL);
    if (!p_obj)
    {
        libvlc_release(p_libvlc);
        return;
    }
    p_obj->u.p_libvlc = p_libvlc;
}

void Java_org_videolan_libvlc_LibVLC_nativeRelease(JNIEnv *env, jobject thiz)
{
    vlcjni_object *p_obj = VLCJniObject_getInstance(env, thiz);

    libvlc_release(p_obj->u.p_libvlc);
}

jstring Java_org_videolan_libvlc_LibVLC_version(JNIEnv* env, jobject thiz)
{
    return (*env)->NewStringUTF(env, libvlc_get_version());
}

jstring Java_org_videolan_libvlc_LibVLC_compiler(JNIEnv* env, jobject thiz)
{
    return (*env)->NewStringUTF(env, libvlc_get_compiler());
}

jstring Java_org_videolan_libvlc_LibVLC_changeset(JNIEnv* env, jobject thiz)
{
    return (*env)->NewStringUTF(env, libvlc_get_changeset());
}

void Java_org_videolan_libvlc_LibVLC_nativeSetUserAgent(JNIEnv* env,
                                                        jobject thiz,
                                                        jstring jname,
                                                        jstring jhttp)
{
    vlcjni_object *p_obj = VLCJniObject_getInstance(env, thiz);
    const char *psz_name, *psz_http;

    if (!p_obj)
        return;

    psz_name = jname ? (*env)->GetStringUTFChars(env, jname, 0) : NULL;
    psz_http = jhttp ? (*env)->GetStringUTFChars(env, jhttp, 0) : NULL;

    if (psz_http && psz_http)
        libvlc_set_user_agent(p_obj->u.p_libvlc, psz_name, psz_http);

    if (psz_name)
        (*env)->ReleaseStringUTFChars(env, jname, psz_name);
    if (psz_http)
        (*env)->ReleaseStringUTFChars(env, jhttp, psz_http);

    if (!psz_name || !psz_http)
        throw_IllegalArgumentException(env, "name or http invalid");
}


text:
package org.zalando.limil;

public interface LinkingResource {

    Links getLinks();

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.dev.bins.shop.ui.ManageAddressActivity">

    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <Button
                android:id="@+id/btn_add_address"
                android:background="@mipmap/plus"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="right" />

        </LinearLayout>
    </android.support.v7.widget.Toolbar>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_address"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

</LinearLayout>


text:
Repozitorij z gradivi pri predmetu APPR v študijskem letu 2015/16.

## ANALIZA DOLGA IN LETNEGA PRIMAKLJAJA DRŽAV V EVROOBMOČJU
Dolgovi in primakljaji držav so zelo vroča tema v Evropski uniji. Na eni strani so nekateri ekonomisti prepričani, da je treba vzdrževati strogo proračunsko disciplino, torej porabiti toliko kolikor država pobere z davki. Ostali pa verjamejo, da je proračunski primakljaj nujen, če hočemo preprečiti ponoven padec v recesijo.

Analiziral bom podatke držav evroobmočja, torej njihove letne primakljaje, delež zadolženosti glede na BDP in poskusil na grobo oceniti korelacijo med zadolženostjo in razvitostjo razičnih EU držav. Glede na to, da so ZDA najbolj razvita država na svetu, če kot merilo uporabimo bruto domači proizvod na prebivalca, bom tudi primerjal njihov in naš (evropski) dolg.

Podatke bom pridobival iz:

- https://data.oecd.org/gga/general-government-debt.htm
- https://en.wikipedia.org/wiki/National_debt_of_the_United_States

## Program

Glavni program in poročilo se nahajata v datoteki `projekt.Rmd`. Ko ga prevedemo,
se izvedejo programi, ki ustrezajo drugi, tretji in četrti fazi projekta:

* obdelava, uvoz in čiščenje podatkov: `uvoz/uvoz.r`
* analiza in vizualizacija podatkov: `vizualizacija/vizualizacija.r`
* napredna analiza podatkov: `analiza/analiza.r`

Vnaprej pripravljene funkcije se nahajajo v datotekah v mapi `lib/`. Podatkovni
viri so v mapi `podatki/`. Zemljevidi v obliki SHP, ki jih program pobere, se
shranijo v mapo `../zemljevidi/` (torej izven mape projekta).

## Spletni vmesnik

Spletni vmesnik se nahaja v datotekah v mapi `shiny/`. Poženemo ga tako, da v
RStudiu odpremo datoteko `server.R` ali `ui.R` ter kliknemo na gumb *Run App*.
Alternativno ga lahko poženemo tudi tako, da poženemo program `shiny.r`.

## Potrebni paketi za R

Za zagon tega vzorca je potrebno namestiti sledeče pakete za R:

* `knitr` - za izdelovanje poročila
* `rmarkdown` - za prevajanje poročila v obliki RMarkdown
* `shiny` - za prikaz spletnega vmesnika
* `DT` - za prikaz interaktivne tabele
* `maptools` - za uvoz zemljevidov
* `sp` - za delo z zemljevidi
* `digest` - za zgoščevalne funkcije (uporabljajo se za shranjevanje zemljevidov)
* `httr` - za pobiranje spletnih strani
* `XML` - za branje spletnih strani
* `extrafont` - za pravilen prikaz šumnikov (neobvezno)


text:
/**
 * Locals: passport
 *
 * @author Zongmin Lei <leizongmin@gmail.com>
 */

module.exports = function (ns, registerLocals, debug) {
  var app = ns('app');
  var utils = ns('lib.utils');

  registerLocals('passport_types', function (name, callback, context) {
    callback(null, (ns('config.passport.enable') || []));
  });

};


text:
module KG {

    import MathFunction = KG.MathFunction;

    export interface MultivariateFunctionDefinition extends MathFunctionDefinition {
        fn: string;
        domainCondition?: string;
    }

    export interface IMultivariateFunction extends IMathFunction {
        inDomain: (x: number, y: number, z: number) => boolean;
        evaluate: (x: number, y: number) => number;
        mathboxFn: (maxY, maxZ, minY?, minZ?) => (emit: (y: number, z: number, x: number) => any, x: number, y: number, i?: number, j?: number, t?: number) => void;
        contour: (level: number, xScale: Scale, yScale: Scale) => string;
    }

    export class MultivariateFunction extends MathFunction implements IMultivariateFunction {

        private fnString;
        private domainConditionString;
        public fnStringDef;
        public domainConditionStringDef;
        private compiledFunction;
        private compiledDomainCondition;

        constructor(def: MultivariateFunctionDefinition) {
            def.samplePoints = 100;
            setProperties(def, 'constants', ['fn']);
            super(def);
            this.fnStringDef = def.fn;
            this.domainConditionStringDef = def.domainCondition;
        }

        inDomain(x, y, z) {
            let fn = this;
            if (fn.hasOwnProperty('compiledDomainCondition')) {
                return fn.compiledDomainCondition.evaluate({x: x, y: y, z: z});
            } else {
                return true;
            }
        }

        evaluate(x, y) {
            let fn = this;
            if (fn.hasOwnProperty('compiledFunction')) {
                const z = fn.compiledFunction.evaluate({x: x, y: y});
                if (fn.inDomain(x, y, z)) {
                    return z;
                }
            }
        }

        mathboxFn() {
            const fn = this;
            return function (emit, x, y) {
                emit(y, fn.evaluate(x, y), x);
            };
        }

        contour(level, xScale, yScale, bounds?) {
            const fn = this;

            bounds = setDefaults(bounds || {}, {
                xMin: xScale.domainMin,
                xMax: xScale.domainMax,
                yMin: yScale.domainMin,
                yMax: yScale.domainMax
            });

            let n = 100, m = 100, values = new Array(n * m);
                for (let j = 0.5, k = 0; j < m; ++j) {
                    for (let i = 0.5; i < n; ++i, ++k) {
                        let x = bounds.xMin + i * (bounds.xMax - bounds.xMin) / n,
                            y = bounds.yMin + j * (bounds.yMax - bounds.yMin) / m;
                        values[k] = fn.evaluate(x, y);
                    }
                }

                let transform = ({type, value, coordinates}) => {
                    return {
                        type, value, coordinates: coordinates.map(rings => {
                            return rings.map(points => {
                                return points.map(([x, y]) => ([xScale.scale(bounds.xMin + x * (bounds.xMax - bounds.xMin) / 100), yScale.scale(bounds.yMin + y * (bounds.yMax - bounds.yMin) / 100)]));
                            });
                        })
                    };
                };

                const p = d3.geoPath();

                // Compute the contour polygons at log-spaced intervals; returns an array of MultiPolygon.
                const contourLine = d3.contours().size([n, m]).contour(values, level);

                return p(transform(contourLine));
        }

        update(force) {
            let fn = super.update(force);
            //console.log('updating; currently ', fn.fnString);
            fn.scope = {
                params: fn.model.currentParamValues,
                calcs: fn.model.currentCalcValues,
                colors: fn.model.currentColors
            };
            const originalString = fn.fnString,
                originalDomainCondition = fn.domainConditionString;
            if (originalString != fn.updateFunctionString(fn.fnStringDef, fn.scope)) {
                fn.hasChanged = true;
                fn.fnString = fn.updateFunctionString(fn.fnStringDef, fn.scope);
                fn.compiledFunction = math.compile(fn.fnString);
            }
            if (fn.domainConditionStringDef != undefined) {
                if (originalDomainCondition != fn.updateFunctionString(fn.domainConditionStringDef, fn.scope)) {
                    fn.hasChanged = true;
                    fn.domainConditionString = fn.updateFunctionString(fn.domainConditionStringDef, fn.scope);
                    fn.compiledDomainCondition = math.compile(fn.domainConditionString);
                }
            }

            return fn;
        }

    }
}


text:
----------
     This page was generated by a tool.
     Manual changes to this page are lost when the page is regenerated.

This repository contains ArcObjects SDK Samples for the ArcObjects SDK 10.8.  The samples are demonstrating the key functions that are falling under the 'Editing' topic.

## Features

This folder contains ArcObjects SDK Samples that fall under the 'Editing' topic:

* [AngleAngleConstructor (C#, VB)](../../../../tree/master/Net/Editing/AngleAngleConstructor)
* [Editing_EditEventListener (C#, VB)](../../../../tree/master/Net/Editing/Editing_EditEventListener)
* [PointsAlongLine (C#, VB)](../../../../tree/master/Net/Editing/PointsAlongLine)
* [RSSWeatherGraphicTracker (C#, VB)](../../../../tree/master/Net/Editing/RSSWeatherGraphicTracker)
* [TabbedFeatureInspector (C#, VB)](../../../../tree/master/Net/Editing/TabbedFeatureInspector)
* [ViperPin (C#, VB)](../../../../tree/master/Net/Editing/ViperPin)
* [WorkingWithPackages (C#, VB)](../../../../tree/master/Net/Editing/WorkingWithPackages)


text:
<!DOCTYPE html>

  <meta charset="UTF-8">

  <link rel="stylesheet" href="../bower_components/bulma/css/bulma.css">
  <link rel="stylesheet" href="../bower_components/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="main.css">

Failed to Load

Please check your Network Connection

  <webview src="about:blank"></webview>

         Read


text:
package net.dryanhild.collada.schema14.parser.geometry.source;

import net.dryanhild.collada.schema14.data.geometry.source.FloatSource;
import net.dryanhild.collada.schema14.parser.BaseParserTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.xmlpull.v1.XmlPullParserException;

import javax.inject.Inject;
import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;

public class WithBasicAccessor extends BaseParserTest {

    @Inject
    private SourceParser sourceParser;

    private FloatSource floatSource;

    @Override
    protected String getDataString() {
        return "<source id=\"test1\">\n" + //
               "  <float_array id=\"values\" count=\"9\">\n" + //
               "    1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0\n" + //
               "  </float_array>\n" + //
               "  <technique_common>\n" + //
               "    <accessor source=\"#values\" count=\"3\" stride=\"3\">\n" + //
               "      <param name=\"A\" type=\"float\"/>\n" + //
               "      <param name=\"F\" type=\"float\"/>\n" + //
               "      <param name=\"X\" type=\"float\"/>\n" + //
               "    </accessor>\n" + //
               "  </technique_common>\n" + //
               "</source>";
    }

    @BeforeMethod
    public void setFloatSource() throws IOException, XmlPullParserException {
        floatSource = sourceParser.parse();
    }

    @Test
    public void idIsCorrect() {
        assertThat(floatSource.getId()).isEqualTo("test1");
    }

    @Test
    public void floatArrayExists() {
        assertThat(floatSource.getSource().values).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9);
    }

    @Test
    public void floatArrayHasCorrectId() {
        assertThat(floatSource.getSource().getId()).isEqualTo("values");
    }

    @Test
    public void countIsCorrect() {
        assertThat(floatSource.getCommonAccessor().getCount()).isEqualTo(3);
    }

    @Test
    public void strideIsCorrect() {
        assertThat(floatSource.getCommonAccessor().getCount()).isEqualTo(3);
    }

    @Test
    public void correctParamsExist() {
        assertThat(floatSource.getCommonAccessor().getParams()).extracting("name").containsExactly("A", "F", "X");
        assertThat(floatSource.getCommonAccessor().getParams()).extracting("type")
                .containsExactly("float", "float", "float");
    }
}


text:
package org.locationtech.geowave.core.geotime.store;

import org.locationtech.geowave.core.store.adapter.InternalDataAdapter;
import org.opengis.feature.simple.SimpleFeature;

public interface InternalGeotoolsFeatureDataAdapter<T extends SimpleFeature> extends
    InternalDataAdapter<T>,
    GeotoolsFeatureDataAdapter<T> {

}


text:
+++
title = "ipsum in"
+++

Curabitur ligula sapien, tincidunt non, euismod vitae, posuere imperdiet, leo. Maecenas malesuada. Praesent congue erat at massa. Sed cursus turpis vitae tortor. Donec posuere vulputate arcu. Phasellus accumsan cursus velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed aliquam, nisi quis porttitor congue, elit erat euismod orci, ac placerat dolor lectus quis orci.


text:
/**
 * Constructs a new graph editor
 */
Menus = function(editorUi)
{
	this.editorUi = editorUi;
	this.menus = new Object();
	this.init();

	// Pre-fetches checkmark image
	new Image().src = IMAGE_PATH + '/checkmark.gif';
};

/**
 * Adds the label menu items to the given menu and parent.
 */
Menus.prototype.init = function()
{
	var graph = this.editorUi.editor.graph;

	this.put('fontFamily', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		var fonts = ['Helvetica', 'Verdana', 'Times New Roman', 'Garamond', 'Comic Sans MS',
		             'Courier New', 'Georgia', 'Lucida Console', 'Tahoma'];

		for (var i = 0; i < fonts.length; i++)
		{
			var tr = this.styleChange(menu, fonts[i], [mxConstants.STYLE_FONTFAMILY], [fonts[i]], null, parent);
			tr.firstChild.nextSibling.style.fontFamily = fonts[i];
		}

		menu.addSeparator(parent);
		this.promptChange(menu, mxResources.get('custom'), '', mxConstants.DEFAULT_FONTFAMILY, mxConstants.STYLE_FONTFAMILY, parent);
	})));
	this.put('fontSize', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		var sizes = [6, 8, 9, 10, 11, 12, 14, 18, 24, 36, 48, 72];

		for (var i = 0; i < sizes.length; i++)
		{
			this.styleChange(menu, sizes[i], [mxConstants.STYLE_FONTSIZE], [sizes[i]], null, parent);
		}

		menu.addSeparator(parent);
		this.promptChange(menu, mxResources.get('custom'), '(pt)', '12', mxConstants.STYLE_FONTSIZE, parent);
	})));
	this.put('linewidth', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		var sizes = [1, 2, 3, 4, 8, 12, 16, 24];

		for (var i = 0; i < sizes.length; i++)
		{
			this.styleChange(menu, sizes[i] + 'px', [mxConstants.STYLE_STROKEWIDTH], [sizes[i]], null, parent);
		}

		menu.addSeparator(parent);
		this.promptChange(menu, mxResources.get('custom'), '(px)', '1', mxConstants.STYLE_STROKEWIDTH, parent);
	})));
	this.put('line', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.styleChange(menu, mxResources.get('straight'), [mxConstants.STYLE_EDGE], [null], null, parent);
		this.styleChange(menu, mxResources.get('entityRelation'), [mxConstants.STYLE_EDGE], ['entityRelationEdgeStyle'], null, parent);
		menu.addSeparator(parent);
		this.styleChange(menu, mxResources.get('horizontal'), [mxConstants.STYLE_EDGE, mxConstants.STYLE_ELBOW], ['elbowEdgeStyle', 'horizontal'], null, parent);
		this.styleChange(menu, mxResources.get('vertical'), [mxConstants.STYLE_EDGE, mxConstants.STYLE_ELBOW], ['elbowEdgeStyle', 'vertical'], null, parent);
		menu.addSeparator(parent);
		this.styleChange(menu, mxResources.get('plain'), [mxConstants.STYLE_EDGE], ['segmentEdgeStyle'], null, parent);
		this.styleChange(menu, mxResources.get('orthogonal'), [mxConstants.STYLE_EDGE], ['orthogonalEdgeStyle'], null, parent);
	})));
	this.put('lineend', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.styleChange(menu, mxResources.get('classic'), [mxConstants.STYLE_ENDARROW], [mxConstants.ARROW_CLASSIC], null, parent);
		this.styleChange(menu, mxResources.get('openArrow'), [mxConstants.STYLE_ENDARROW], [mxConstants.ARROW_OPEN], null, parent);
		this.styleChange(menu, mxResources.get('block') , [mxConstants.STYLE_ENDARROW], [mxConstants.ARROW_BLOCK], null, parent);
		menu.addSeparator(parent);
		this.styleChange(menu, mxResources.get('oval'), [mxConstants.STYLE_ENDARROW], [mxConstants.ARROW_OVAL], null, parent);
		this.styleChange(menu, mxResources.get('diamond'), [mxConstants.STYLE_ENDARROW], [mxConstants.ARROW_DIAMOND], null, parent);
		this.styleChange(menu, mxResources.get('diamondThin'), [mxConstants.STYLE_ENDARROW], [mxConstants.ARROW_DIAMOND_THIN], null, parent);
		menu.addSeparator(parent);
		this.styleChange(menu, mxResources.get('none'), [mxConstants.STYLE_ENDARROW], [mxConstants.NONE], null, parent);
		menu.addSeparator(parent);
		menu.addItem(mxResources.get('transparent'), null, function() { graph.toggleCellStyles('endFill', true); }, parent, null, true);
		menu.addSeparator(parent);
		this.promptChange(menu, mxResources.get('size'), '(px)', mxConstants.DEFAULT_MARKERSIZE, mxConstants.STYLE_ENDSIZE, parent);
	})));
	this.put('linestart', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.styleChange(menu, mxResources.get('classic'), [mxConstants.STYLE_STARTARROW], [mxConstants.ARROW_CLASSIC], null, parent);
		this.styleChange(menu, mxResources.get('openArrow'), [mxConstants.STYLE_STARTARROW], [mxConstants.ARROW_OPEN], null, parent);
		this.styleChange(menu, mxResources.get('block'), [mxConstants.STYLE_STARTARROW], [mxConstants.ARROW_BLOCK], null, parent);
		menu.addSeparator(parent);
		this.styleChange(menu, mxResources.get('oval'), [mxConstants.STYLE_STARTARROW], [mxConstants.ARROW_OVAL], null, parent);
		this.styleChange(menu, mxResources.get('diamond'), [mxConstants.STYLE_STARTARROW], [mxConstants.ARROW_DIAMOND], null, parent);
		this.styleChange(menu, mxResources.get('diamondThin'), [mxConstants.STYLE_STARTARROW], [mxConstants.ARROW_DIAMOND_THIN], null, parent);
		menu.addSeparator(parent);
		this.styleChange(menu, mxResources.get('none'), [mxConstants.STYLE_STARTARROW], [mxConstants.NONE], null, parent);
		menu.addSeparator(parent);
		menu.addItem(mxResources.get('transparent'), null, function() { graph.toggleCellStyles('startFill', true); }, parent, null, true);
		menu.addSeparator(parent);
		this.promptChange(menu, mxResources.get('size'), '(px)', mxConstants.DEFAULT_MARKERSIZE, mxConstants.STYLE_STARTSIZE, parent);
	})));
	this.put('spacing', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		// Uses shadow action and line menu to analyze selection
		var vertexSelected = this.editorUi.actions.get('shadow').enabled;
		var edgeSelected = this.get('line').enabled;

		if (vertexSelected || menu.showDisabled)
		{
			this.promptChange(menu, mxResources.get('top'), '(px)', '0', mxConstants.STYLE_SPACING_TOP, parent, vertexSelected);
			this.promptChange(menu, mxResources.get('right'), '(px)', '0', mxConstants.STYLE_SPACING_RIGHT, parent, vertexSelected);
			this.promptChange(menu, mxResources.get('bottom'), '(px)', '0', mxConstants.STYLE_SPACING_BOTTOM, parent, vertexSelected);
			this.promptChange(menu, mxResources.get('left'), '(px)', '0', mxConstants.STYLE_SPACING_LEFT, parent, vertexSelected);
			menu.addSeparator(parent);
			this.promptChange(menu, mxResources.get('global'), '(px)', '0', mxConstants.STYLE_SPACING, parent, vertexSelected);
			this.promptChange(menu, mxResources.get('perimeter'), '(px)', '0', mxConstants.STYLE_PERIMETER_SPACING, parent, vertexSelected);
		}

		if (edgeSelected || menu.showDisabled)
		{
			menu.addSeparator(parent);
			this.promptChange(menu, mxResources.get('sourceSpacing'), '(px)', '0', mxConstants.STYLE_SOURCE_PERIMETER_SPACING, parent, edgeSelected);
			this.promptChange(menu, mxResources.get('targetSpacing'), '(px)', '0', mxConstants.STYLE_TARGET_PERIMETER_SPACING, parent, edgeSelected);
		}
	})));
	this.put('format', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.addSubmenu('spacing', menu, parent);
		this.addMenuItems(menu, ['-', 'fillColor'], parent);
		this.addSubmenu('gradient', menu, parent);
		this.addMenuItems(menu, ['-', 'shadow'], parent);
		this.promptChange(menu, mxResources.get('opacity'), '(%)', '100', mxConstants.STYLE_OPACITY, parent, this.get('format').enabled);
		this.addMenuItems(menu, ['-', 'rounded', 'dashed', '-', 'strokeColor'], parent);
		this.addSubmenu('linewidth', menu, parent);
		this.addMenuItems(menu, ['-'], parent);
		this.addSubmenu('line', menu, parent);
		this.addMenuItems(menu, ['-'], parent);
		this.addSubmenu('linestart', menu, parent);
		this.addSubmenu('lineend', menu, parent);
		menu.addSeparator(parent);
		this.addMenuItem(menu, 'style', parent);
	})));
	this.put('gradient', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.addMenuItems(menu, ['gradientColor', '-'], parent);
		this.styleChange(menu, mxResources.get('north'), [mxConstants.STYLE_GRADIENT_DIRECTION], [mxConstants.DIRECTION_NORTH], null, parent);
		this.styleChange(menu, mxResources.get('east'), [mxConstants.STYLE_GRADIENT_DIRECTION], [mxConstants.DIRECTION_EAST], null, parent);
		this.styleChange(menu, mxResources.get('south'), [mxConstants.STYLE_GRADIENT_DIRECTION], [mxConstants.DIRECTION_SOUTH], null, parent);
		this.styleChange(menu, mxResources.get('west'), [mxConstants.STYLE_GRADIENT_DIRECTION], [mxConstants.DIRECTION_WEST], null, parent);
	})));
	this.put('text', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.addMenuItem(menu, 'fontColor', parent);
		menu.addSeparator(parent);
		this.addSubmenu('fontFamily', menu, parent);
		this.addSubmenu('fontSize', menu, parent);

		this.addMenuItems(menu, ['-', 'bold', 'italic', 'underline', '-'], parent);
	    this.addSubmenu('alignment', menu, parent);
	    this.addSubmenu('position', menu, parent);
		this.addMenuItems(menu, ['-', 'backgroundColor', 'borderColor', '-'], parent);

		var enabled = this.get('text').enabled;
		this.promptChange(menu, mxResources.get('textOpacity'), '(%)', '100', mxConstants.STYLE_TEXT_OPACITY, parent, enabled);
		menu.addItem(mxResources.get('hide'), null, function() { graph.toggleCellStyles(mxConstants.STYLE_NOLABEL, false); }, parent, null, enabled);
		menu.addItem(mxResources.get('rotate'), null, function() { graph.toggleCellStyles(mxConstants.STYLE_HORIZONTAL, true); }, parent, null, enabled);
	})));
	this.put('alignment', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.styleChange(menu, mxResources.get('leftAlign'), [mxConstants.STYLE_ALIGN], [mxConstants.ALIGN_LEFT], null, parent);
		this.styleChange(menu, mxResources.get('center'), [mxConstants.STYLE_ALIGN], [mxConstants.ALIGN_CENTER], null, parent);
		this.styleChange(menu, mxResources.get('rightAlign'), [mxConstants.STYLE_ALIGN], [mxConstants.ALIGN_RIGHT], null, parent);
		menu.addSeparator(parent);
		this.styleChange(menu, mxResources.get('topAlign'), [mxConstants.STYLE_VERTICAL_ALIGN], [mxConstants.ALIGN_TOP], null, parent);
		this.styleChange(menu, mxResources.get('middle'), [mxConstants.STYLE_VERTICAL_ALIGN], [mxConstants.ALIGN_MIDDLE], null, parent);
		this.styleChange(menu, mxResources.get('bottomAlign'), [mxConstants.STYLE_VERTICAL_ALIGN], [mxConstants.ALIGN_BOTTOM], null, parent);
	})));
	this.put('position', new Menu(mxUtils.bind(this, function(menu, parent)
	{
	    this.styleChange(menu, mxResources.get('left'), [mxConstants.STYLE_LABEL_POSITION, mxConstants.STYLE_ALIGN], [mxConstants.ALIGN_LEFT, mxConstants.ALIGN_RIGHT], null, parent);
	    this.styleChange(menu, mxResources.get('center'), [mxConstants.STYLE_LABEL_POSITION, mxConstants.STYLE_ALIGN], [mxConstants.ALIGN_CENTER, mxConstants.ALIGN_CENTER], null, parent);
	    this.styleChange(menu, mxResources.get('right'), [mxConstants.STYLE_LABEL_POSITION, mxConstants.STYLE_ALIGN], [mxConstants.ALIGN_RIGHT, mxConstants.ALIGN_LEFT], null, parent);
		menu.addSeparator(parent);
		this.styleChange(menu, mxResources.get('top'), [mxConstants.STYLE_VERTICAL_LABEL_POSITION, mxConstants.STYLE_VERTICAL_ALIGN], [mxConstants.ALIGN_TOP, mxConstants.ALIGN_BOTTOM], null, parent);
		this.styleChange(menu, mxResources.get('middle'), [mxConstants.STYLE_VERTICAL_LABEL_POSITION, mxConstants.STYLE_VERTICAL_ALIGN], [mxConstants.ALIGN_MIDDLE, mxConstants.ALIGN_MIDDLE], null, parent);
		this.styleChange(menu, mxResources.get('bottom'), [mxConstants.STYLE_VERTICAL_LABEL_POSITION, mxConstants.STYLE_VERTICAL_ALIGN], [mxConstants.ALIGN_BOTTOM, mxConstants.ALIGN_TOP], null, parent);
	})));
	this.put('direction', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.styleChange(menu, mxResources.get('north'), [mxConstants.STYLE_DIRECTION], [mxConstants.DIRECTION_NORTH], null, parent);
		this.styleChange(menu, mxResources.get('east'), [mxConstants.STYLE_DIRECTION], [mxConstants.DIRECTION_EAST], null, parent);
		this.styleChange(menu, mxResources.get('south'), [mxConstants.STYLE_DIRECTION], [mxConstants.DIRECTION_SOUTH], null, parent);
		this.styleChange(menu, mxResources.get('west'), [mxConstants.STYLE_DIRECTION], [mxConstants.DIRECTION_WEST], null, parent);
		menu.addSeparator(parent);
		menu.addItem(mxResources.get('flipH'), null, function()
		{
			graph.getModel().beginUpdate();
			try
			{
				graph.toggleCellStyles(mxConstants.STYLE_STENCIL_FLIPH, false);
				graph.toggleCellStyles(mxConstants.STYLE_IMAGE_FLIPH, false);
			}
			finally
			{
				graph.getModel().endUpdate();
			}
		}, parent);
		menu.addItem(mxResources.get('flipV'), null, function()
		{
			graph.getModel().beginUpdate();
			try
			{
				graph.toggleCellStyles(mxConstants.STYLE_STENCIL_FLIPV, false);
				graph.toggleCellStyles(mxConstants.STYLE_IMAGE_FLIPV, false);
			}
			finally
			{
				graph.getModel().endUpdate();
			}
		}, parent);
		this.addMenuItem(menu, 'rotation', parent);
	})));
	this.put('align', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		menu.addItem(mxResources.get('leftAlign'), null, function() { graph.alignCells(mxConstants.ALIGN_LEFT); }, parent);
		menu.addItem(mxResources.get('center'), null, function() { graph.alignCells(mxConstants.ALIGN_CENTER); }, parent);
		menu.addItem(mxResources.get('rightAlign'), null, function() { graph.alignCells(mxConstants.ALIGN_RIGHT); }, parent);
		menu.addSeparator(parent);
		menu.addItem(mxResources.get('topAlign'), null, function() { graph.alignCells(mxConstants.ALIGN_TOP); }, parent);
		menu.addItem(mxResources.get('middle'), null, function() { graph.alignCells(mxConstants.ALIGN_MIDDLE); }, parent);
		menu.addItem(mxResources.get('bottomAlign'), null, function() { graph.alignCells(mxConstants.ALIGN_BOTTOM); }, parent);
	})));
	this.put('layout', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		menu.addItem(mxResources.get('horizontalTree'), null, mxUtils.bind(this, function()
		{
			if (!graph.isSelectionEmpty())
			{
				var layout = new mxCompactTreeLayout(graph, true);
				layout.edgeRouting = false;
				layout.levelDistance = 30;
	    		this.editorUi.executeLayout(layout, true, true);
			}
		}), parent);
		menu.addItem(mxResources.get('verticalTree'), null, mxUtils.bind(this, function()
		{
			if (!graph.isSelectionEmpty())
			{
				var layout = new mxCompactTreeLayout(graph, false);
				layout.edgeRouting = false;
				layout.levelDistance = 30;
	    		this.editorUi.executeLayout(layout, true, true);
			}
		}), parent);
		menu.addSeparator(parent);
		menu.addItem(mxResources.get('horizontalFlow'), null, mxUtils.bind(this, function()
		{
			var layout = new mxHierarchicalLayout(graph, mxConstants.DIRECTION_WEST);
			this.editorUi.executeLayout(layout, true, true);
		}), parent);
		menu.addItem(mxResources.get('verticalFlow'), null, mxUtils.bind(this, function()
		{
			var layout = new mxHierarchicalLayout(graph, mxConstants.DIRECTION_NORTH);
			this.editorUi.executeLayout(layout, true, true);
		}), parent);
		menu.addSeparator(parent);
		menu.addItem(mxResources.get('organic'), null, mxUtils.bind(this, function()
		{
			var layout = new mxFastOrganicLayout(graph);
    		this.editorUi.executeLayout(layout, true, true);
		}), parent);
		menu.addItem(mxResources.get('circle'), null, mxUtils.bind(this, function()
		{
			var layout = new mxCircleLayout(graph);
    		this.editorUi.executeLayout(layout, true, true, graph.getSelectionCells());
		}), parent);
	})));
	this.put('navigation', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.addMenuItems(menu, ['home', '-', 'exitGroup', 'enterGroup', '-', 'expand', 'collapse'], parent);
	})));
	this.put('arrange', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.addMenuItems(menu, ['toFront', 'toBack', '-'], parent);
		this.addSubmenu('direction', menu, parent);
		this.addSubmenu('layout', menu, parent);
		this.addSubmenu('align', menu, parent);
		menu.addSeparator(parent);
		this.addSubmenu('navigation', menu, parent);
		this.addMenuItems(menu, ['-', 'group', 'ungroup', 'removeFromGroup', '-', 'autosize', 'rotate'], parent);
	})));
	this.put('view', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.addMenuItems(menu, ['actualSize'], parent);
		menu.addSeparator();
		var scales = [0.25, 0.5, 0.75, 1, 2, 4];

		for (var i = 0; i < scales.length; i++)
		{
			(function(scale)
			{
				menu.addItem((scale * 100) + '%', null, function()
				{
					graph.zoomTo(scale);
				}, parent);
			})(scales[i]);
		}

		this.addMenuItems(menu, ['-', 'zoomIn', 'zoomOut', '-', 'fitWindow', 'customZoom', '-', 'fitPage', 'fitPageWidth'], parent);
	})));
	this.put('file', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.addMenuItems(menu, ['new', 'open', '-', 'save', 'saveAs', '-', 'export', '-', 'import', 'editFile', '-', 'pageSetup', 'print'], parent);
	})));
	this.put('edit', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.addMenuItems(menu, ['undo', 'redo', '-', 'cut', 'copy', 'paste', 'delete', '-', 'duplicate', '-',
		                         'editLink', 'openLink', '-',
		                         'selectVertices', 'selectEdges', 'selectAll', '-', 'setAsDefaultEdge']);
	})));
	this.put('options', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.addMenuItems(menu, ['grid', 'guides', 'tooltips', '-', 'connect', 'navigation',
		                         'scrollbars', '-', 'pageView', '-', 'pageBackgroundColor']);
	})));
	this.put('help', new Menu(mxUtils.bind(this, function(menu, parent)
	{
		this.addMenuItems(menu, ['help', '-', 'about']);
	})));
};

/**
 * Adds the label menu items to the given menu and parent.
 */
Menus.prototype.put = function(name, menu)
{
	this.menus[name] = menu;
};

/**
 * Adds the label menu items to the given menu and parent.
 */
Menus.prototype.get = function(name)
{
	return this.menus[name];
};

/**
 * Adds the given submenu.
 */
Menus.prototype.addSubmenu = function(name, menu, parent)
{
	var enabled = this.get(name).enabled;

	if (menu.showDisabled || enabled)
	{
		var submenu = menu.addItem(mxResources.get(name), null, null, parent, null, enabled);
		this.addMenu(name, menu, submenu);
	}
};

/**
 * Adds the label menu items to the given menu and parent.
 */
Menus.prototype.addMenu = function(name, popupMenu, parent)
{
	var menu = this.get(name);

	if (menu != null && (popupMenu.showDisabled || menu.enabled))
	{
		this.get(name).execute(popupMenu, parent);
	}
};

/**
 * Adds a style change item to the given menu.
 */
Menus.prototype.styleChange = function(menu, label, keys, values, sprite, parent)
{
	return menu.addItem(label, null, mxUtils.bind(this, function()
	{
		var graph = this.editorUi.editor.graph;

		graph.getModel().beginUpdate();
		try
		{
			for (var i = 0; i < keys.length; i++)
			{
				graph.setCellStyles(keys[i], values[i]);
			}
		}
		finally
		{
			graph.getModel().endUpdate();
		}
	}), parent, sprite);
};

/**
 * Adds a style change item with a prompt to the given menu.
 */
Menus.prototype.promptChange = function(menu, label, hint, defaultValue, key, parent, enabled)
{
	return menu.addItem(label, null, mxUtils.bind(this, function()
	{
		var graph = this.editorUi.editor.graph;
		var value = defaultValue;
    	var state = graph.getView().getState(graph.getSelectionCell());

    	if (state != null)
    	{
    		value = state.style[key] || value;
    	}

		value = mxUtils.prompt(mxResources.get('enterValue') + ((hint.length > 0) ? (' ' + hint) : ''), value);

    	if (value != null && value.length > 0)
    	{
        	graph.setCellStyles(key, value);
        }
	}), parent, null, enabled);
};

/**
 * Adds a handler for showing a menu in the given element.
 */
Menus.prototype.pickColor = function(key)
{
	if (this.colorDialog == null)
	{
		this.colorDialog = new ColorDialog(this.editorUi);
	}

	this.colorDialog.currentColorKey = key;
	var graph = this.editorUi.editor.graph;
	var state = graph.getView().getState(graph.getSelectionCell());
	var color = 'none';

	if (state != null)
	{
		color = state.style[key] || color;
	}

	if (color == 'none')
	{
		color = 'ffffff';
		this.colorDialog.picker.fromString('ffffff');
		this.colorDialog.colorInput.value = 'none';
	}
	else
	{
		this.colorDialog.picker.fromString(color);
	}

	this.editorUi.showDialog(this.colorDialog.container, 220, 360, true, false);

	if (!mxClient.IS_TOUCH)
	{
		this.colorDialog.colorInput.focus();
	}
};

/**
 * Creates the keyboard event handler for the current graph and history.
 */
Menus.prototype.addMenuItem = function(menu, key, parent)
{
	var action = this.editorUi.actions.get(key);

	if (action != null && (menu.showDisabled || action.enabled))
	{
		var item = menu.addItem(action.label, null, action.funct, parent, null, action.enabled);

		// Adds checkmark image
		if (action.toggleAction && action.isSelected())
		{
			this.addCheckmark(item);
		}

		this.addShortcut(item, action);

		return item;
	}

	return null;
};

/**
 * Adds a checkmark to the given menuitem.
 */
Menus.prototype.addShortcut = function(item, action)
{
	if (action.shortcut != null)
	{
		var td = item.firstChild.nextSibling.nextSibling;
		var span = document.createElement('span');
		span.style.color = 'gray';
		mxUtils.write(span, action.shortcut);
		td.appendChild(span);
	}
};

/**
 * Adds a checkmark to the given menuitem.
 */
Menus.prototype.addCheckmark = function(item)
{
	var td = item.firstChild.nextSibling;
	td.style.backgroundImage = 'url(' + IMAGE_PATH + '/checkmark.gif)';
	td.style.backgroundRepeat = 'no-repeat';
	td.style.backgroundPosition = '2px 50%';
	td.style.width = '20px';
};

/**
 * Creates the keyboard event handler for the current graph and history.
 */
Menus.prototype.addMenuItems = function(menu, keys, parent)
{
	for (var i = 0; i < keys.length; i++)
	{
		if (keys[i] == '-')
		{
			menu.addSeparator(parent);
		}
		else
		{
			this.addMenuItem(menu, keys[i], parent);
		}
	}
};

/**
 * Creates the keyboard event handler for the current graph and history.
 */
Menus.prototype.createPopupMenu = function(menu, cell, evt)
{
	var graph = this.editorUi.editor.graph;
	menu.smartSeparators = true;

	if (graph.isSelectionEmpty())
	{
		this.addMenuItems(menu, ['undo', 'redo', '-', 'paste', '-']);
	}
	else
	{
		this.addMenuItems(menu, ['delete', '-', 'cut', 'copy', '-', 'duplicate', '-']);
	}

	if (graph.getSelectionCount() > 0)
	{
		this.addMenuItems(menu, ['toFront', 'toBack', '-']);
		this.addSubmenu('linewidth', menu);

		if (graph.getModel().isEdge(graph.getSelectionCell()))
		{
			this.addSubmenu('line', menu);
			menu.addSeparator();
			this.addSubmenu('linestart', menu);
			this.addSubmenu('lineend', menu);
			menu.addSeparator();
			this.addMenuItems(menu, ['setAsDefaultEdge']);
		}
		else if (graph.getSelectionCount() > 1)
		{
			menu.addSeparator();
			this.addMenuItems(menu, ['group']);
		}
		else
		{

			menu.addSeparator();
			this.addSubmenu('layout', menu);
		}

		menu.addSeparator();

		if (graph.getSelectionCount() == 1)
		{
			this.addMenuItems(menu, ['editLink']);

			var link = graph.getLinkForCell(graph.getSelectionCell());

			if (link != null)
			{
				this.addMenuItems(menu, ['openLink']);
			}
		}
	}
	else
	{
		this.addMenuItems(menu, ['-', 'selectVertices', 'selectEdges', '-', 'selectAll']);
	}
};

/**
 * Creates the keyboard event handler for the current graph and history.
 */
Menus.prototype.createMenubar = function(container)
{
	var menubar = new Menubar(this.editorUi, container);
	var menus = ['file', 'edit', 'view', 'format', 'text', 'arrange', 'options', 'help'];

	for (var i = 0; i < menus.length; i++)
	{
		menubar.addMenu(mxResources.get(menus[i]), this.get(menus[i]).funct);
	}

	return menubar;
};

/**
 * Construcs a new menubar for the given editor.
 */
function Menubar(editorUi, container)
{
	this.editorUi = editorUi;
	this.container = container;

	// Global handler to hide the current menu
	var md = (mxClient.IS_TOUCH) ? 'touchstart' : 'mousedown';
	mxEvent.addListener(document, md, mxUtils.bind(this, function(evt)
	{
		this.hideMenu();
	}));
};

/**
 * Adds the menubar elements.
 */
Menubar.prototype.hideMenu = function()
{
	if (this.currentMenu != null)
	{
		this.currentMenu.hideMenu();
	}
};

/**
 * Adds a submenu to this menubar.
 */
Menubar.prototype.addMenu = function(label, funct)
{
	var elt = document.createElement('a');
	elt.setAttribute('href', 'javascript:void(0);');
	elt.className = 'geItem';
	mxUtils.write(elt, label);

	this.addMenuHandler(elt, funct);
	this.container.appendChild(elt);

	return elt;
};

/**
 * Adds a handler for showing a menu in the given element.
 */
Menubar.prototype.addMenuHandler = function(elt, funct)
{
	if (funct != null)
	{
		var show = true;

		var clickHandler = mxUtils.bind(this, function(evt)
		{
			if (show && elt.enabled == null || elt.enabled)
			{
				this.editorUi.editor.graph.panningHandler.hideMenu();
				var menu = new mxPopupMenu(funct);
				menu.div.className += ' geMenubarMenu';
				menu.smartSeparators = true;
				menu.showDisabled = true;
				menu.autoExpand = true;

				// Disables autoexpand and destroys menu when hidden
				menu.hideMenu = mxUtils.bind(this, function()
				{
					mxPopupMenu.prototype.hideMenu.apply(menu, arguments);
					menu.destroy();
					this.currentMenu = null;
					this.currentElt = null;
				});

				menu.popup(elt.offsetLeft + 4, elt.offsetTop + elt.offsetHeight + 4, null, evt);
				this.currentMenu = menu;
				this.currentElt = elt;
			}

			show = true;
			mxEvent.consume(evt);
		});

		// Shows menu automatically while in expanded state
		mxEvent.addListener(elt, 'mousemove', mxUtils.bind(this, function(evt)
		{
			if (this.currentMenu != null && this.currentElt != elt)
			{
				this.hideMenu();
				clickHandler(evt);
			}
		}));

		// Hides menu if already showing
		mxEvent.addListener(elt, 'mousedown', mxUtils.bind(this, function()
		{
			show = this.currentElt != elt;
		}));

		mxEvent.addListener(elt, 'click', clickHandler);
	}
};

/**
 * Constructs a new action for the given parameters.
 */
function Menu(funct, enabled)
{
	mxEventSource.call(this);
	this.funct = funct;
	this.enabled = (enabled != null) ? enabled : true;
};

// Menu inherits from mxEventSource
mxUtils.extend(Menu, mxEventSource);

/**
 * Sets the enabled state of the action and fires a stateChanged event.
 */
Menu.prototype.setEnabled = function(value)
{
	if (this.enabled != value)
	{
		this.enabled = value;
		this.fireEvent(new mxEventObject('stateChanged'));
	}
};

/**
 * Sets the enabled state of the action and fires a stateChanged event.
 */
Menu.prototype.execute = function(menu, parent)
{
	this.funct(menu, parent);
};


text:
namespace rocksdb {

Status PlainTableFactory::NewTableReader(const Options& options,
                                         const EnvOptions& soptions,
                                         const InternalKeyComparator& icomp,
                                         unique_ptr<RandomAccessFile>&& file,
                                         uint64_t file_size,
                                         unique_ptr<TableReader>* table) const {
  return PlainTableReader::Open(options, soptions, icomp, std::move(file),
                                file_size, table, bloom_bits_per_key_,
                                hash_table_ratio_, index_sparseness_,
                                huge_page_tlb_size_);
}

TableBuilder* PlainTableFactory::NewTableBuilder(
    const Options& options, const InternalKeyComparator& internal_comparator,
    WritableFile* file, CompressionType compression_type) const {
  return new PlainTableBuilder(options, file, user_key_len_);
}

extern TableFactory* NewPlainTableFactory(uint32_t user_key_len,
                                          int bloom_bits_per_key,
                                          double hash_table_ratio,
                                          size_t index_sparseness,
                                          size_t huge_page_tlb_size) {
  return new PlainTableFactory(user_key_len, bloom_bits_per_key,
                               hash_table_ratio, index_sparseness,
                               huge_page_tlb_size);
}

extern TableFactory* NewTotalOrderPlainTableFactory(uint32_t user_key_len,
                                                    int bloom_bits_per_key,
                                                    size_t index_sparseness,
                                                    size_t huge_page_tlb_size) {
  return new PlainTableFactory(user_key_len, bloom_bits_per_key, 0,
                               index_sparseness, huge_page_tlb_size);
}

}  // namespace rocksdb
#endif  // ROCKSDB_LITE