text:
<?php

/*
abstract class Upfront_Endpoint extends Upfront_Server {

	abstract public function create_endpoint ();
	abstract public function apply_endpoint ();

	protected function _add_hooks () {
		add_action('init', array($this, "create_endpoint"));
		add_action('template_redirect', array($this, "apply_endpoint"));
	}

}
*/

abstract class Upfront_VirtualPage extends Upfront_Server {

	protected $_subpages = array();
	protected $_subpage;

	abstract public function get_slug ();
	abstract public function parse ($request);
	abstract public function render ($request);

	protected function _add_hooks () {
		$this->_add_subpages();
		add_action('template_redirect', array($this, "intercept_page"), 0);
	}

	protected function _add_subpages () {}

	public function intercept_page () {
		if (!$this->_parse_request(true)) return false;
		//if ($this->get_slug() != get_query_var('name')) return false;
		//$this->render();
	}

	public function parse_page () {
		if (!$this->_parse_request(false)) return false;
		return true;
	}

	public static function redirect ($request) {
		$url = get_option('permalink_structure')
			? home_url($request)
			: home_url() . '?name=' . $request
		;
		wp_safe_redirect($url);
		die;
	}

	private function _parse_request ($render = true) {
		$raw_request = get_option('permalink_structure')
			? $this->_parse_pretty_permalink_request()
			: $this->_parse_default_request()
		;
		if (!$raw_request) return false;
		$request = array_map('trim', explode('/', $raw_request));
		if (empty($request) || empty($request[0])) return false;
		if ($this->get_slug() !== $request[0]) return false;

		if (!empty($request[1]) && !empty($this->_subpages)) {
			foreach($this->_subpages as $subpage) {
				if ($subpage->get_slug() !== $request[1]) continue;
				status_header(200);
				if ($render)
					$subpage->render($request);
				else
					$subpage->parse($request);
				$this->_subpage = $subpage;
				break;
			}
		} else {
			status_header(200);
			if ($render)
				$this->render($request);
			else
				$this->parse($request);
		}
		return true;
	}

	public static function get_url ($request) {
		return get_option('permalink_structure')
			? home_url($request)
			: home_url() . '?name=' . $request
		;
	}

	private function _parse_pretty_permalink_request () {
		global $wp;
		return $wp->request;
	}

	private function _parse_default_request () {
		return !empty($_GET['name']) ? $_GET['name'] : false;
	}
}

abstract class Virtual_Content_Page extends Upfront_VirtualPage {

	protected function _add_hooks () {
		if (!current_user_can('edit_posts')) return false;
		parent::_add_hooks();
	}

}

abstract class Upfront_VirtualSubpage {
	abstract public function get_slug ();
	abstract public function parse ($request);
	abstract public function render ($request);
}

// ----- Implementations

// --- Creators

/*
class Upfront_NewPage_VirtualSubpage extends Upfront_VirtualSubpage {

	public function get_slug () {
		return 'page';
	}

	public function render ($request) {
		$page = Upfront_PostModel::create('page', __('Change me, please', 'upfront'), __('Super awesome content', 'upfront'));
		Upfront_VirtualPage::redirect('edit/page/' . $page->ID);
	}
}

class Upfront_NewPost_VirtualSubpage extends Upfront_VirtualSubpage {

	public function get_slug () {
		return 'post';
	}

	public function render ($request) {
		$page = Upfront_PostModel::create('post', __('I am a post title - change me, please', 'upfront'), __('Super awesome post content', 'upfront'));
		Upfront_VirtualPage::redirect('edit/post/' . $page->ID);
	}
}
class Upfront_ContentCreator_VirtualPage extends Virtual_Content_Page {

	public static function serve () {
		$me = new self;
		$me->_add_hooks();
	}

	protected function _add_subpages () {
		$this->_subpages = array(
			new Upfront_NewPage_VirtualSubpage(),
			new Upfront_NewPost_VirtualSubpage(),
		);
	}

	public function get_slug () {
		return 'create';
	}

	public function render ($request) {}

}
Upfront_ContentCreator_VirtualPage::serve();
*/

// --- Editors

class Upfront_EditPage_VirtualSubpage extends Upfront_VirtualSubpage {

	public function get_slug () {
		return 'page';
	}

	public function parse ($request) {
		$post_id = end($request);
		global $post, $wp_query;
		$wp_query = new WP_Query(array(
			'page_id' => $post_id,
		));
		add_filter('upfront-data-post_id', create_function('', "return $post_id;"));
	}

	public function render ($request) {
		$this->parse($request);
		$post_id = end($request);
		$template = !empty($post_id)
			? get_post_meta($post_id, '_wp_page_template', true)
			: false
		;
		if (!empty($template)) {
			$template = locate_template($template);
		}

		if (empty($template)) $template = get_single_template();
		load_template($template);
		die;
	}

	public function get_title () {
		return 'Edit page';
	}
}

class Upfront_EditPost_VirtualSubpage extends Upfront_VirtualSubpage {

	public function get_slug () {
		return 'post';
	}

	public function parse ($request) {
		$post_id = end($request);
		global $post, $wp_query;
		$wp_query = new WP_Query(array(
			'p' => $post_id,
		));
		add_filter('upfront-data-post_id', create_function('', "return $post_id;"));
	}

	public function render ($request) {
		$this->parse($request);
		//add_filter('wp_title', array($this, 'get_title'));
		add_action('wp_footer', array($this, 'start_editor'), 999);
		load_template(get_single_template());
		die;
	}

	public function get_title () {
		return 'Edit post';
	}

	public function start_editor () {
		echo upfront_boot_editor_trigger();
		echo <<<EOSEJS
<script>
(function ($) {

var this_post = false;

function loaded_layout_ready () {
	setTimeout(function () {
		if ($("#upfront-loading").length) return loaded_layout_ready();
		else {
			if (!this_post) return Upfront.Util.log("NO SUCH POST");
			Upfront.Events.off("upfront:layout:loaded", loaded_layout_ready);
			$("#" + this_post.model.get_property_value_by_name("element_id")).trigger("dblclick");
		}
	}, 200);
}

$(document).on("upfront-load", function () {
	Upfront.Events.on("upfront:layout:loaded", loaded_layout_ready);
	Upfront.Events.on("elements:this_post:loaded", function (post) {
		var el = $("#" + post.model.get_property_value_by_name("element_id")).closest(".upfront-region-shadow");
		if (!el.length) this_post = post;
	});
});
})(jQuery);
</script>
EOSEJS;
	}
}

class Upfront_ContentEditor_VirtualPage extends Virtual_Content_Page {

	public static function serve () {
		$me = new self;
		$me->_add_hooks();
		return $me;
	}

	protected function _add_subpages () {
		$this->_subpages = array(
			new Upfront_EditPage_VirtualSubpage(),
			new Upfront_EditPost_VirtualSubpage(),
		);
	}

	public function get_slug () {
		return 'edit';
	}

	public function parse ($request) {}
	public function render ($request) {}

}
//Upfront_ContentEditor_VirtualPage::serve();
add_action('init', array('Upfront_ContentEditor_VirtualPage', 'serve'));

// --- Save handlers

class Upfront_Editor_Ajax extends Upfront_Server {
	public static function serve () {
		$me = new self;
		$me->_add_hooks();
	}

	private function _add_hooks () {
		//add_action('wp_ajax_upfront-edit-publish', array($this, "publish_post"));
		upfront_add_ajax('upfront-edit-publish', array($this, "publish_post"));

		upfront_add_ajax('upfront-create-post_type', array($this, "create_post_type"));

		//add_action('wp_ajax_upfront-edit-draft', array($this, "draft_post"));
		upfront_add_ajax('upfront-edit-draft', array($this, "draft_post"));

		//add_action('wp_ajax_upfront-post-get_taxonomy', array($this, "get_post_taxonomy"));
		upfront_add_ajax('upfront-post-get_taxonomy', array($this, "get_post_taxonomy"));

		//add_action('wp_ajax_upfront-post-create_term', array($this, "create_new_term"));
		upfront_add_ajax('upfront-post-create_term', array($this, "create_new_term"));

		//add_action('wp_ajax_upfront-post-update_terms', array($this, "update_post_terms"));
		upfront_add_ajax('upfront-post-update_terms', array($this, "update_post_terms"));

		//add_action('wp_ajax_upfront-get_page_data', array($this, "get_page_data"));
		//add_action('wp_ajax_upfront-get_post_data', array($this, "get_post_data"));

		//add_action('wp_ajax_upfront-post-update_slug', array($this, "update_post_slug"));
		upfront_add_ajax('upfront-post-update_slug', array($this, "update_post_slug"));

		//add_action('wp_ajax_upfront-post-update_status', array($this, "update_post_status"));
		upfront_add_ajax('upfront-post-update_status', array($this, "update_post_status"));

		//add_action('wp_ajax_upfront-post-update_password', array($this, "update_post_password"));
		upfront_add_ajax('upfront-post-update_password', array($this, "update_post_password"));

		//add_action('wp_ajax_upfront-comments-approve', array($this, "approve_comment"));
		upfront_add_ajax('upfront-comments-approve', array($this, "approve_comment"));

		//add_action('wp_ajax_upfront-comments-unapprove', array($this, "unapprove_comment"));
		upfront_add_ajax('upfront-comments-unapprove', array($this, "unapprove_comment"));

		//add_action('wp_ajax_upfront-comments-thrash', array($this, "thrash_comment"));
		upfront_add_ajax('upfront-comments-thrash', array($this, "thrash_comment"));

		//add_action('wp_ajax_upfront-comments-unthrash', array($this, "unthrash_comment"));
		upfront_add_ajax('upfront-comments-unthrash', array($this, "unthrash_comment"));

		//add_action('wp_ajax_upfront-comments-spam', array($this, "spam_comment"));
		upfront_add_ajax('upfront-comments-spam', array($this, "spam_comment"));

		//add_action('wp_ajax_upfront-comments-unspam', array($this, "unthrash_comment"));
		upfront_add_ajax('upfront-comments-unspam', array($this, "unthrash_comment"));

		//add_action('wp_ajax_upfront-comments-reply_to', array($this, "post_comment"));
		upfront_add_ajax('upfront-comments-reply_to', array($this, "post_comment"));

		//add_action('wp_ajax_upfront-comments-update_comment', array($this, "update_comment"));
		upfront_add_ajax('upfront-comments-update_comment', array($this, "update_comment"));

		//add_action('wp_ajax_upfront-wp-model', array($this, "handle_model_request"));
		upfront_add_ajax('upfront-wp-model', array($this, "handle_model_request"));
	}

	function handle_model_request(){
		$data = stripslashes_deep($_POST);
		$action = $data['model_action'];

		if(!method_exists($this, $action))
			$this->_out(new Upfront_JsonResponse_Error($action . ' not implemented.'));

		call_user_func(array($this, $action), $data);
	}

	function create_post_type () {
		if (!Upfront_Permissions::current(Upfront_Permissions::EDIT)) $this->_reject();
		$data = wp_parse_args(
			stripslashes_deep($_POST['data']),
			array(
				'post_type' => 'post',
				'title' => 'Write a title...',
			)
		);

		$post = Upfront_PostModel::create($data['post_type'], $data['title']);
		if (!empty($data['permalink'])) $post->post_name = $data['permalink'];
		if (!empty($data['template'])) update_post_meta($post->ID, '_wp_page_template', $data['template']);

		$post->post_status = 'draft';
		Upfront_PostModel::save($post);
		$this->_out(new Upfront_JsonResponse_Success(array(
			'post_id' => $post->ID,
			'permalink' => get_permalink($post->ID),
		)));
	}

	function publish_post () {
		if (!Upfront_Permissions::current(Upfront_Permissions::EDIT)) $this->_reject();
		$this->_process_post('publish');
	}

	function draft_post () {
		if (!Upfront_Permissions::current(Upfront_Permissions::EDIT)) $this->_reject();
		$this->_process_post('draft');
	}

	private function _process_post ($status) {
		$data = stripslashes_deep($_POST['data']);
		$post_id = !empty($data['id']) ? $data['id'] : false;
		if (!$post_id) $this->_out(new Upfront_JsonResponse_Error("No post id"));

		if (!current_user_can('edit_post', $post_id)) $this->_out(new Upfront_JsonResponse_Error("You can't do this"));

		$post = (array)Upfront_PostModel::get($post_id);
		if (empty($post)) $this->_out(new Upfront_JsonResponse_Error("Invalid post"));

		$post['post_status'] = $status;
		$post['post_title'] = $data['title'];
		$post['post_content'] = $data['body'];

		$updated = Upfront_PostModel::save($post);
		$updated->permalink = get_permalink($updated->ID);
		$this->_out(new Upfront_JsonResponse_Success($updated));
	}

	function update_post_slug () {
		if (!Upfront_Permissions::current(Upfront_Permissions::EDIT)) $this->_reject();
		$data = stripslashes_deep($_POST);
		$post_id = !empty($data['post_id']) ? $data['post_id'] : false;
		if (!$post_id) $this->_out(new Upfront_JsonResponse_Error("No post id"));

		$slug = !empty($data['slug']) ? $data['slug'] : false;
		if (!$slug) $this->_out(new Upfront_JsonResponse_Error("No slug"));

		if (!current_user_can('edit_post', $post_id)) $this->_out(new Upfront_JsonResponse_Error("You can't do this"));

		$post = (array)Upfront_PostModel::get($post_id);
		if (empty($post)) $this->_out(new Upfront_JsonResponse_Error("Invalid post"));
		$post['post_name'] = $slug;

		$updated = Upfront_PostModel::save($post);
		$updated->permalink = get_permalink($updated->ID);
		$this->_out(new Upfront_JsonResponse_Success($updated));
	}

	function update_post_status () {
		if (!Upfront_Permissions::current(Upfront_Permissions::EDIT)) $this->_reject();
		$data = stripslashes_deep($_POST);
		$post_id = !empty($data['post_id']) ? $data['post_id'] : false;
		if (!$post_id) $this->_out(new Upfront_JsonResponse_Error("No post id"));

		$status = !empty($data['status']) ? $data['status'] : false;
		if (!$status) $this->_out(new Upfront_JsonResponse_Error("No status"));

		if (!current_user_can('edit_post', $post_id)) $this->_out(new Upfront_JsonResponse_Error("You can't do this"));

		$post = (array)Upfront_PostModel::get($post_id);
		if (empty($post)) $this->_out(new Upfront_JsonResponse_Error("Invalid post"));
		$post['post_status'] = $status;

		$updated = Upfront_PostModel::save($post);
		$updated->permalink = get_permalink($updated->ID);
		$this->_out(new Upfront_JsonResponse_Success($updated));
	}

	function update_post_password () {
		if (!Upfront_Permissions::current(Upfront_Permissions::EDIT)) $this->_reject();
		$data = stripslashes_deep($_POST);
		$post_id = !empty($data['post_id']) ? $data['post_id'] : false;
		if (!$post_id) $this->_out(new Upfront_JsonResponse_Error("No post id"));

		$password = !empty($data['password']) ? $data['password'] : '';

		if (!current_user_can('edit_post', $post_id)) $this->_out(new Upfront_JsonResponse_Error("You can't do this"));

		$post = (array)Upfront_PostModel::get($post_id);
		if (empty($post)) $this->_out(new Upfront_JsonResponse_Error("Invalid post"));
		$post['post_password'] = $password;

		$updated = Upfront_PostModel::save($post);
		$updated->permalink = get_permalink($updated->ID);
		$this->_out(new Upfront_JsonResponse_Success($updated));
	}

	function fetch_term($data) {
		if(!$data['taxonomy'])
			$this->_out(new Upfront_JsonResponse_Error("Invalid taxonomy."));
		if(!$data['id'])
			$this->_out(new Upfront_JsonResponse_Error("Invalid id."));

		$term = get_term(intval($data['id']), $data['taxonomy']);

		if(is_wp_error($term))
			$this->_out(new Upfront_JsonResponse_Error($term->get_error_message()));
		if(!$term)
			$this->_out(new Upfront_JsonResponse_Error("Term not found."));
		$this->_out(new Upfront_JsonResponse_Success($term));
	}

	function save_term($data){
		if (!Upfront_Permissions::current(Upfront_Permissions::EDIT)) $this->_reject();
		if(!current_user_can('manage_categories'))
			$this->_out(new Upfront_JsonResponse_Error("You can't do this"));
		if(!$data['taxonomy'])
			$this->_out(new Upfront_JsonResponse_Error("Invalid taxonomy."));

		$term = get_term(intval($data['term_id']), $data['taxonomy']);

		if(!$term || is_wp_error($term)){
			$term = wp_insert_term($data['name'], $data['taxonomy'], $data);
		}
		else{
			$term = wp_update_term($data['term_id'], $data['taxonomy'], $data);
		}

		if(isset( $data['postId'] ))
			wp_set_object_terms($data['postId'], $term['term_id'], $data['taxonomy']);

		if(is_wp_error($term))
			$this->_out(new Upfront_JsonResponse_Error($term->get_error_message()));
		if(!$term)
			$this->_out(new Upfront_JsonResponse_Error("Term not found."));
		$this->_out(new Upfront_JsonResponse_Success($term));
	}

	function fetch_term_list($data){
		if(!$data['taxonomy'])
			$this->_out(new Upfront_JsonResponse_Error("Invalid taxonomy."));
		$response = array();
		if($data['postId']){
			$response['results'] = array_values((array) get_the_terms($data['postId'], $data['taxonomy']));
			if($data['allTerms']){
				$response['allTerms'] = array_values((array)get_terms($data['taxonomy'], array('hide_empty' => false)));
			}
		}
		else{
			$response['results'] = array_values(get_terms($data['taxonomy'], array('hide_empty' => true)));
		}

		if(! $response['results'])
			$response['results'] = array();

		$response['taxonomy'] = get_taxonomy($data['taxonomy']);

		$this->_out(new Upfront_JsonResponse_Success($response));
	}

	function save_term_list($data){
		if (!Upfront_Permissions::current(Upfront_Permissions::EDIT)) $this->_reject();
		if(!$data['taxonomy'])
			$this->_out(new Upfront_JsonResponse_Error("Invalid taxonomy."));

		if(!$data['postId'])
			$this->_out(new Upfront_JsonResponse_Error("No post id."));

		foreach($data['all'] as $term){
			$terms[] = $term['slug'] ? $term['slug'] : $term['name'];
		}

		$terms = wp_set_object_terms($data['postId'], $terms, $data['taxonomy']);
		if(is_wp_error($terms))
			$this->_out(new Upfront_JsonResponse_Error($terms->get_error_message()));

		$this->_out(new Upfront_JsonResponse_Success(get_the_terms($data['postId'], $data['taxonomy'])));
	}

	/**
	 * Updates the template file for a page.
	 * @param  Object $data The data sent to update the template, at least a postId and a template name are needed.
	 * @return null       Json response {postId, template}
	 */
	function update_page_template($data){
		if (!Upfront_Permissions::current(Upfront_Permissions::EDIT)) $this->_reject();
		if(!current_user_can('edit_pages'))
			$this->_out(new Upfront_JsonResponse_Error("You can't do this."));

		if(!$data['postId'])
			$this->_out(new Upfront_JsonResponse_Error("No page id."));
		if(!$data['template'])
			$this->_out(new Upfront_JsonResponse_Error("No template given."));

		$key = '_wp_page_template';
		$post_id = $data['postId'];
		$template = $data['template'];
		$success_response = new Upfront_JsonResponse_Success(array(
			'template' => $data['template'],
			'postId' => $data['postId']
		));

		$tpl = get_post_meta($post_id, $key, true);
		if($template){
			if(update_post_meta($post_id, $key, $template))
				$this->_out($success_response);
		}
		else if(add_post_meta($post_id, $key, $template, true))
				$this->_out($success_response);

		$this->_out(new Upfront_JsonResponse_Error("There was an error saving the template." . $post_id . $key . $template));

	}

	function fetch_post($data) {
		if( is_numeric($data['id']) ){
			$post = get_post($data['id']);
		}elseif( $data['id'] === "fake_post" ){
			$posts = get_posts(array('orderby' => 'rand', 'posts_per_page' => 1));
			if (!empty($posts[0])) {
				$post = $posts[0];
			}else{
				return $this->_out(new Upfront_JsonResponse_Error('Error'));
			}
		}

		if($post){
			if(!empty($data['filterContent'])){
				$post->post_content = apply_filters('the_content', $post->post_content);
				$post->post_title = apply_filters('the_title', $post->post_title);
				$post->post_excerpt = apply_filters('the_excerpt', $post->post_excerpt);
			}
			if(!empty($data['withAuthor'])){
				$post->author = $this->remove_private_user_fields(new WP_User($post->post_author));
			}
			if(!empty($data['withMeta'])){
				$post->meta = $this->parse_single_meta(get_metadata('post', $post->ID));
			}

			$post->permalink = get_permalink($post->ID);
			$post->sticky = is_sticky($post->ID);
			$post->is_new = false;

			$this->_out(new Upfront_JsonResponse_Success($post));
		}
		else if( $data['id'] === '0') { //New post
			$post_type = $data['post_type'] ? $data['post_type'] : 'post';
			$post = Upfront_PostModel::create($post_type, 'Please enter your new ' . $post_type . ' title here', 'Your ' . $post_type . ' content goes here. Have fun writing :)');

			if($post_type == 'page'){
				$post->post_content = 'Type your page content here. Feel free to add some elements from the left sidebar.';
			}

			$post->is_new = true;
			$post->sticky = false;

			$this->_out(new Upfront_JsonResponse_Success($post));
		}

		$this->_out(new Upfront_JsonResponse_Error("Post not found."));
	}

	function remove_private_user_fields($user) {
		if (!empty($user->data) && !empty($user->data->user_email)) $user->gravatar = md5($user->data->user_email);
		unset($user->data->user_pass);
		unset($user->data->user_registered);
		unset($user->data->user_activation_key);
		unset($user->data->user_email);
		return $user;
	}

	function fetch_post_list($data){
		if(!$data['postType'])
			$this->_out(new Upfront_JsonResponse_Error("Invalid post type."));

		$query = $this->_spawn_query($data['postType'], $data);
		$posts = $query->posts;
		$limit = isset($data['limit']) ? (int)$data['limit'] : 10;
		$page = isset($data['page']) ? (int)$data['page'] : 0;

		if($posts) {
			for ($i=0; $i < sizeof($posts); $i++) {
				if(!empty($data['filterContent'])){
					$posts[$i]->post_content = apply_filters('the_content', $posts[$i]->post_content);
					$posts[$i]->post_title = apply_filters('the_title', $posts[$i]->post_title);
					$posts[$i]->post_excerpt = apply_filters('the_excerpt', $posts[$i]->post_excerpt);
				}

				if($data['withAuthor']){
					$posts[$i]->author = $this->remove_private_user_fields(new WP_User($posts[$i]->post_author));
				}

				if($data['withMeta']){
					$posts[$i]->meta = $this->parse_single_meta(get_metadata('post', $posts[$i]->ID));
				}
				$posts[$i]->permalink = get_permalink($posts[$i]->ID);
			}
		}

		$this->_out(new Upfront_JsonResponse_Success(array(
			"results" => $posts,
			"pagination" => array(
				"total" => $query->found_posts,
				"page_size" => $limit,
				"page" => $page,
			)
		)));

	}

	function parse_single_meta($metadata){
		$parsed = array();
		foreach($metadata as $key => $val){
			if(is_array($val) && sizeof($val) == 1)
				$parsed[] = array('meta_key' => $key, 'meta_value' => maybe_unserialize($val[0]));
			else
				$parsed[] = array('meta_key' => $key, 'meta_value' => maybe_unserialize($val));
		}
		return $parsed;
	}

	function save_post($data) {
		if(!current_user_can('edit_posts'))
			$this->_out(new Upfront_JsonResponse_Error("You can't do this."));

		if($data['post_type'] == 'page' && !current_user_can('edit_pages'))
			$this->_out(new Upfront_JsonResponse_Error("You can't do this."));

		if($data['post_status'] == 'publish'){
			if($data['post_type'] == 'post' && !current_user_can('publish_posts') || $data['post_type'] == 'page' && !current_user_can('publish_pages'))
			$this->_out(new Upfront_JsonResponse_Error("You can't do this."));
		}

		unset($data['post_modified']);
		unset($data['post_modified_gmt']);

		if(!$data['ID']){
			unset($data['ID']);
			$id = wp_insert_post($data);
		}
		else {
			$post = get_post($data['ID']);
			if($post->post_status == 'trash' && $data['post_status'] != 'trash')
				$post = wp_untrash_post($data['ID']);
			else if($post->post_status != 'trash' && $data['post_status'] == 'trash')
				$post = wp_trash_post($data['ID']);

			//GMT date
			if($data['post_date']){
				$data['post_date_gmt'] = get_gmt_from_date($data['post_date']);
			}

			// Update if not deleted
			if($post)
				$id = wp_update_post($data);
			else
				$id = 0;
		}

		if(is_wp_error($id))
			$this->_out(new Upfront_JsonResponse_Error($id->get_error_message()));

		if(isset($data['sticky'])){
			$is_sticky = is_sticky($id);
			if($data['sticky'] && !$is_sticky){
				$posts = get_option('sticky_posts');
				if($posts)
					$posts[] = $id;
				else
					$posts = array($id);
				add_option('sticky_posts', $posts);
			}
			else if(!$data['sticky'] && $is_sticky) {
				$posts = get_option('sticky_posts');
				$index = array_search($id, $posts);
				if($index !== FALSE){
					array_splice($posts, $index, 1);
					if(!sizeof($posts))
						delete_option('sticky_posts');
					else
						add_option('sticky_posts', $posts);
				}
			}
		}

		$post = get_post($id);

		$this->_out(new Upfront_JsonResponse_Success(array(
			'id' => $id,
			'post_name' => $post->post_name,
            'permalink' => get_permalink($id)
		)));
	}

	function fetch_user($data) {
		if(empty($data['ID']))
			$data['ID'] = get_current_user_id();

		$user = $this->remove_private_user_fields(new WP_User(wp_get_current_user()));

		$this->_out(new Upfront_JsonResponse_Success($user));
	}

	function fetch_comment ($data) {
		if(!$data['id'])
			$this->_out(new Upfront_JsonResponse_Error("No comment id given."));

		$comment = get_comment( $data['id'] );

		if(!$comment)
			$this->_out(new Upfront_JsonResponse_Error("Comment not found."));

		$comment->gravatar = md5($comment->comment_author_email);

		$this->_out(new Upfront_JsonResponse_Success($comment));
	}

	function save_comment ($data) {
		if (!current_user_can('moderate_comments')) $this->_out(new Upfront_JsonResponse_Error("You can't do this"));

		if($data['comment_ID']){
			if(wp_update_comment($data))
				$this->_out(new Upfront_JsonResponse_Success(array('comment_ID' => $data['comment_ID'])));
			$this->_out(new Upfront_JsonResponse_Error("Error saving the comment."));
		}
		else {
			$comment_id = wp_new_comment($data);
				$this->_out(new Upfront_JsonResponse_Success(array('comment_ID' => $comment_id)));
		}

	}

	function fetch_comment_list ($data) {
		$post_id = !empty($data['postId']) ? $data['postId'] : false;
		$orderby = !empty($data['orderby']) ? $data['orderby'] : 'comment_date';
		$order = !empty($data['order']) ? $data['order'] : 'ASC';
		$limit = isset($data['limit']) ? (int)$data['limit'] : 10;
		$page = isset($data['page']) ? (int)$data['page'] : 0;
		$search = !empty($data['search']) ? $data['search'] : false;

		if(!isset($data['commentType']) || $data['commentType'] == 'all')
			$comment_type = false;
		else if ($data['commentType'] == 'comment')
			$comment_type = '';
		else
			$comment_type = $data['commentType'];
		$comment_approved = !empty($data['comment_approved']) ? $data['comment_approved'] : false;

		global $wpdb;
		$where_query = array();

		if($post_id)
			$where_query[] = $wpdb->prepare('comment_post_ID=%d', $post_id);
		if($comment_type !== false)
			$where_query[] = $wpdb->prepare('comment_type=%s', $comment_type);
		if($comment_approved)
			$where_query[] = $wpdb->prepare('comment_approved=%s', $comment_approved);
		if($search)
			$where_query[] = "comment_content LIKE '%" . esc_sql(like_escape($search)) . "%'";

		$where = sizeof($where_query) ? 'WHERE ' . implode(' AND ', $where_query) : '';

		$sql = "SELECT * FROM {$wpdb->comments} "  . $where . $wpdb->prepare(" ORDER BY {$orderby} {$order} LIMIT %d, %d", ($page*$limit), $limit);

		$comments = $wpdb->get_results(
			$sql
		);

		foreach ($comments as $idx => $comment) {
			$comment->gravatar = md5($comment->comment_author_email);
		}

		$comments_count = $wpdb->get_var(
			"SELECT COUNT(*) FROM {$wpdb->comments} " . $where
		);

		$this->_out(new Upfront_JsonResponse_Success(array(
			"results" => $comments,
			"pagination" => array(
				"total" => $comments_count,
				"page_size" => $limit,
				"page" => $page,
			),
			"sql" => $sql,
			"comment_type" => $comment_type
		)));
	}

	function fetch_meta_list($data) {
		$meta_type = $data['metaType'];
		if(!$meta_type && array_search($meta_type, array('comment', 'post', 'user')) == FALSE)
			$this->_out(new Upfront_JsonResponse_Error("Invalid meta type"));

		$object_id = $data['objectId'];
		if(!$object_id)
			$this->_out(new Upfront_JsonResponse_Error("No object id given"));

		$meta = $this->parse_single_meta(get_metadata($meta_type, $object_id));

		// Extract values
		foreach($meta as $key => $val){
			if(is_array($val) && sizeof($val) == 1)
				$meta[$key] = $val[0];
		}
		$this->_out(new Upfront_JsonResponse_Success(array('results' => $meta)));
	}

	function save_meta_list($data){
		$meta_type = $data['metaType'];
		if(!$meta_type && array_search($meta_type, array('comment', 'post', 'user')) == FALSE)
			$this->_out(new Upfront_JsonResponse_Error("Invalid meta type"));

		$object_id = $data['objectId'];
		if(!$object_id)
			$this->_out(new Upfront_JsonResponse_Error("No object id given"));

		if(
			($meta_type == 'post' && !current_user_can('edit_posts')) ||
			($meta_type == 'comment' && !current_user_can('moderate_comments')) ||
			($meta_type == 'user' && !current_user_can('edit_users'))
			){
			$this->_out(new Upfront_JsonResponse_Error("You can't do this"));
		}

		$updated = array();

		if(!empty($data['removed'])){
			foreach($data['removed'] as $meta)
				delete_metadata($meta_type, $object_id, $meta['meta_key']);
		}

		if(!empty($data['added'])){
			foreach($data['added'] as $meta)
				update_metadata($meta_type, $object_id, $meta['meta_key'], (!empty($meta['meta_value']) ? $meta['meta_value'] : false));
		}

		if(!empty($data['changed'])){
			foreach($data['changed'] as $meta)
				update_metadata($meta_type, $object_id, $meta['meta_key'], (!empty($meta['meta_value']) ? $meta['meta_value'] : false));

		}

		$meta = $this->parse_single_meta(get_metadata($meta_type, $object_id));

		$this->_out(new Upfront_JsonResponse_Success($meta));
	}

	function get_post_extra($data) {
		if(!$data['postId'])
			$this->_out(new Upfront_JsonResponse_Error("No post id."));

		$post_id = $data['postId'];

		$extra = array('postId' => $post_id);
		if(!empty($data['allTemplates']))
			$extra['allTemplates'] = get_page_templates();
		if(!empty($data['template']))
			$extra['template'] = get_page_template_slug($post_id);
		if(!empty($data['thumbnail'])){
			$size = $data['thumbnail'] ? $data['thumbnail'] : 'post-thumbnail';
				$extra['thumbnail'] = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), $size );
		}

		$this->_out(new Upfront_JsonResponse_Success($extra));
	}

	private function _spawn_query ($post_type, $data=array()) {
		$sort = !empty($data['orderby']) ? str_replace('post_', '', $data['orderby']) : 'date';
		$direction = !empty($data['order']) ? $data['order'] : 'desc';
		$limit = isset($data['limit']) ? (int)$data['limit'] : 10;
		$page = isset($data['page']) ? (int)$data['page'] + 1 : 1;
		$search = !empty($data['search']) ? $data['search'] : false;

		$args = array(
			'orderby' => $sort,
			'order' => strtoupper($direction),
			'post_type' => $post_type,
			'posts_per_page' => $limit,
			'paged' => $page,
		);
		if ($search) $args['s'] = $search;

		return new WP_Query($args);
	}

	private function _get_post_hierarchy ($post) {
		if ($post->post_parent) return $this->_get_post_info($post->post_parent);
	}

	private function _get_post_featured_image ($post) {
		$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) );
		if (!empty($image[0])) return $image[0];
		return 'http://imgsrc.hubblesite.org/hu/db/images/hs-2012-49-a-small_web.jpg';
	}

	private function _get_post_info ($post_id) {
		$post = get_post($post_id);
		$post->permalink = get_permalink($post->ID);
		$post->hierarchy = $this->_get_post_hierarchy($post);
		$post->featured_image = $this->_get_post_featured_image($post);
		return $post;
	}
}
//Upfront_Editor_Ajax::serve();
add_action('init', array('Upfront_Editor_Ajax', 'serve'));

/* ----- Prettify frontend element dependencies loading ----- */

class Upfront_ElementDependiecies_Styles_VirtualSubpage extends Upfront_VirtualSubpage {

	public function get_slug () { return 'styles'; }

	public function parse ($request) {}

	public function render ($request) {
		if (empty($request)) return false;
		if (empty($request[2])) return false;
		$_REQUEST['key'] = $request[2];
		$action = is_user_logged_in() ? 'wp_ajax_upfront-element-styles' : 'wp_ajax_nopriv_upfront-element-styles';
		do_action($action);
		die;
	}
}

class Upfront_ElementDependiecies_Scripts_VirtualSubpage extends Upfront_VirtualSubpage {

	public function get_slug () { return 'scripts'; }

	public function parse ($request) {}

	public function render ($request) {
		if (empty($request)) return false;
		if (empty($request[2])) return false;
		$_REQUEST['key'] = $request[2];
		$action = is_user_logged_in() ? 'wp_ajax_upfront-element-scripts' : 'wp_ajax_nopriv_upfront-element-scripts';
		do_action($action);
		die;
	}
}

class Upfront_ElementDependencies_VirtualPage extends Upfront_VirtualPage {

	public static function serve () {
		$me = new self;
		$me->_add_hooks();
	}

	protected function _add_subpages () {
		$this->_subpages = array(
			new Upfront_ElementDependiecies_Styles_VirtualSubpage(),
			new Upfront_ElementDependiecies_Scripts_VirtualSubpage(),
		);
	}

	public function get_slug () { return 'upfront-dependencies'; }

	public function parse ($request) { }
	public function render ($request) { die; }

}
//Upfront_ElementDependencies_VirtualPage::serve();
add_action('init', array('Upfront_ElementDependencies_VirtualPage', 'serve'));

if (!(defined('UF_THX_TMP_SWITCH') && UF_THX_TMP_SWITCH)) {
/**
 * Create new endpoint
 */
class Upfront_CreateNew_Theme_VirtualSubpage extends Upfront_VirtualSubpage {

	public function get_slug () { return 'theme'; }

	public function parse ($request) {
		upfront_switch_stylesheet('upfront');
		add_filter('upfront-storage-key', array($this, 'storage_key_filter'));
		add_filter('upfront-data-storage-key', array($this, 'storage_key_filter'));
		add_filter('upfront-enable-dev-saving', '__return_false');
		query_posts('');
	}

	public function render ($request) {
		$this->parse($request);
		add_action('wp_footer', array($this, 'start_editor'), 999);
		load_template(get_home_template());
		die;
	}

	public function get_title () {
		return 'Create New Theme';
	}

	public function storage_key_filter ($key) {
		return $key . '_new';
	}

	public function template_filter () {
		return 'upfront';
	}

	public function stylesheet_filter () {
		return 'upfront';
	}

	public function start_editor () {
		echo upfront_boot_editor_trigger('theme');
	}
}

class Upfront_Builder_VirtualSubpage extends Upfront_CreateNew_Theme_VirtualSubpage {
	public function __construct($stylesheet) {
		$this->slug = $stylesheet;
		$this->stylesheet = $stylesheet;
		$this->storage_key = $stylesheet;
	}
	public function get_slug () {
		return $this->slug;
 	}
	public function parse ($request) {
		upfront_switch_stylesheet($this->stylesheet);
		add_filter('upfront-storage-key', array($this, 'storage_key_filter'));
		add_filter('upfront-data-storage-key', array($this, 'storage_key_filter'));
		add_filter('upfront-enable-dev-saving', '__return_false');
		query_posts('');
	}
	public function storage_key_filter ($key) {
		return $this->storage_key;
	}

}

class Upfront_CreateNew_VirtualPage extends Upfront_VirtualPage {
	public static function serve () {
		$me = new self;
		$me->_add_hooks();
	}

	protected function _add_subpages () {
		$subpages = array(
			new Upfront_CreateNew_Theme_VirtualSubpage(),
		);

		// Add all Upfront child themes
		// TODO add grandchild themes
		foreach(wp_get_themes() as $stylesheet=>$theme) {
			if ($theme->get('Template') !== 'upfront') continue;
			$subpages[] =  new Upfront_Builder_VirtualSubpage($stylesheet);
		}
		$this->_subpages = $subpages;
	}

	public function get_slug () { return 'create_new'; }

	public function parse ($request) { }
	public function render ($request) { die; }

}
//Upfront_CreateNew_VirtualPage::serve();
add_action('init', array('Upfront_CreateNew_VirtualPage', 'serve'));
}


text:
package org.apache.zeppelin.interpreter;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.internal.StringMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.zeppelin.conf.ZeppelinConfiguration;
import org.apache.zeppelin.dep.Dependency;
import org.apache.zeppelin.dep.DependencyResolver;
import org.apache.zeppelin.display.AngularObjectRegistry;
import org.apache.zeppelin.display.AngularObjectRegistryListener;
import org.apache.zeppelin.helium.ApplicationEventListener;
import org.apache.zeppelin.interpreter.launcher.InterpreterLaunchContext;
import org.apache.zeppelin.interpreter.launcher.InterpreterLauncher;
import org.apache.zeppelin.interpreter.lifecycle.NullLifecycleManager;
import org.apache.zeppelin.interpreter.recovery.NullRecoveryStorage;
import org.apache.zeppelin.interpreter.recovery.RecoveryStorage;
import org.apache.zeppelin.interpreter.remote.RemoteAngularObjectRegistry;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreter;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterProcess;
import org.apache.zeppelin.interpreter.remote.RemoteInterpreterProcessListener;
import org.apache.zeppelin.plugin.PluginManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;

import static org.apache.zeppelin.conf.ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_MAX_POOL_SIZE;
import static org.apache.zeppelin.conf.ZeppelinConfiguration.ConfVars.ZEPPELIN_INTERPRETER_OUTPUT_LIMIT;
import static org.apache.zeppelin.util.IdHashes.generateId;

/**
 * Represent one InterpreterSetting in the interpreter setting page
 */
public class InterpreterSetting {

  private static final Logger LOGGER = LoggerFactory.getLogger(InterpreterSetting.class);
  private static final String SHARED_PROCESS = "shared_process";
  private static final String SHARED_SESSION = "shared_session";
  private static final Map<String, Object> DEFAULT_EDITOR = ImmutableMap.of(
      "language", (Object) "text",
      "editOnDblClick", false);

  private String id;
  private String name;
  // the original interpreter setting template name where it is created from
  private String group;

  //TODO(zjffdu) make the interpreter.json consistent with interpreter-setting.json
  /**
   * properties can be either Properties or Map<String, InterpreterProperty>
   * properties should be:
   * - Properties when Interpreter instances are saved to `conf/interpreter.json` file
   * - Map<String, InterpreterProperty> when Interpreters are registered
   * : this is needed after https://github.com/apache/zeppelin/pull/1145
   * which changed the way of getting default interpreter setting AKA interpreterSettingsRef
   * Note(mina): In order to simplify the implementation, I chose to change properties
   * from Properties to Object instead of creating new classes.
   */
  private Object properties = new Properties();

  private Status status;
  private String errorReason;

  @SerializedName("interpreterGroup")
  private List<InterpreterInfo> interpreterInfos;

  private List<Dependency> dependencies = new ArrayList<>();
  private InterpreterOption option = new InterpreterOption();

  @SerializedName("runner")
  private InterpreterRunner interpreterRunner;

  ///////////////////////////////////////////////////////////////////////////////////////////
  private transient InterpreterSettingManager interpreterSettingManager;
  private transient String interpreterDir;
  private final transient Map<String, ManagedInterpreterGroup> interpreterGroups =
      new ConcurrentHashMap<>();

  private final transient ReentrantReadWriteLock.ReadLock interpreterGroupReadLock;
  private final transient ReentrantReadWriteLock.WriteLock interpreterGroupWriteLock;

  private transient AngularObjectRegistryListener angularObjectRegistryListener;
  private transient RemoteInterpreterProcessListener remoteInterpreterProcessListener;
  private transient ApplicationEventListener appEventListener;
  private transient DependencyResolver dependencyResolver;

  private transient ZeppelinConfiguration conf = new ZeppelinConfiguration();

  // TODO(zjffdu) ShellScriptLauncher is the only launcher implemention for now. It could be other
  // launcher in future when we have other launcher implementation. e.g. third party launcher
  // service like livy
  private transient InterpreterLauncher launcher;
  private transient LifecycleManager lifecycleManager;
  private transient RecoveryStorage recoveryStorage;
  private transient RemoteInterpreterEventServer interpreterEventServer;
  ///////////////////////////////////////////////////////////////////////////////////////////

  /**
   * Builder class for InterpreterSetting
   */
  public static class Builder {
    private InterpreterSetting interpreterSetting;

    public Builder() {
      this.interpreterSetting = new InterpreterSetting();
    }

    public Builder setId(String id) {
      interpreterSetting.id = id;
      return this;
    }

    public Builder setName(String name) {
      interpreterSetting.name = name;
      return this;
    }

    public Builder setGroup(String group) {
      interpreterSetting.group = group;
      return this;
    }

    public Builder setInterpreterInfos(List<InterpreterInfo> interpreterInfos) {
      interpreterSetting.interpreterInfos = interpreterInfos;
      return this;
    }

    public Builder setProperties(Object properties) {
      interpreterSetting.properties = properties;
      return this;
    }

    public Builder setOption(InterpreterOption option) {
      interpreterSetting.option = option;
      return this;
    }

    public Builder setInterpreterDir(String interpreterDir) {
      interpreterSetting.interpreterDir = interpreterDir;
      return this;
    }

    public Builder setRunner(InterpreterRunner runner) {
      interpreterSetting.interpreterRunner = runner;
      return this;
    }

    public Builder setDependencies(List<Dependency> dependencies) {
      interpreterSetting.dependencies = dependencies;
      return this;
    }

    public Builder setConf(ZeppelinConfiguration conf) {
      interpreterSetting.conf = conf;
      return this;
    }

    public Builder setDependencyResolver(DependencyResolver dependencyResolver) {
      interpreterSetting.dependencyResolver = dependencyResolver;
      return this;
    }

    public Builder setInterpreterRunner(InterpreterRunner runner) {
      interpreterSetting.interpreterRunner = runner;
      return this;
    }

    public Builder setIntepreterSettingManager(
        InterpreterSettingManager interpreterSettingManager) {
      interpreterSetting.interpreterSettingManager = interpreterSettingManager;
      return this;
    }

    public Builder setRemoteInterpreterEventServer(RemoteInterpreterEventServer interpreterEventServer) {
      interpreterSetting.interpreterEventServer = interpreterEventServer;
      return this;
    }

    public Builder setRemoteInterpreterProcessListener(RemoteInterpreterProcessListener
                                                       remoteInterpreterProcessListener) {
      interpreterSetting.remoteInterpreterProcessListener = remoteInterpreterProcessListener;
      return this;
    }

    public Builder setAngularObjectRegistryListener(
        AngularObjectRegistryListener angularObjectRegistryListener) {
      interpreterSetting.angularObjectRegistryListener = angularObjectRegistryListener;
      return this;
    }

    public Builder setApplicationEventListener(ApplicationEventListener applicationEventListener) {
      interpreterSetting.appEventListener = applicationEventListener;
      return this;
    }

    public Builder setLifecycleManager(LifecycleManager lifecycleManager) {
      interpreterSetting.lifecycleManager = lifecycleManager;
      return this;
    }

    public Builder setRecoveryStorage(RecoveryStorage recoveryStorage) {
      interpreterSetting.recoveryStorage = recoveryStorage;
      return this;
    }

    public InterpreterSetting create() {
      // post processing
      interpreterSetting.postProcessing();
      return interpreterSetting;
    }
  }

  public InterpreterSetting() {
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    this.id = generateId();
    interpreterGroupReadLock = lock.readLock();
    interpreterGroupWriteLock = lock.writeLock();
  }

  void postProcessing() {
    this.status = Status.READY;
    this.id = this.name;
    if (this.lifecycleManager == null) {
      this.lifecycleManager = new NullLifecycleManager(conf);
    }
    if (this.recoveryStorage == null) {
      try {
        this.recoveryStorage = new NullRecoveryStorage(conf, interpreterSettingManager);
      } catch (IOException e) {
        // ignore this exception as NullRecoveryStorage will do nothing.
      }
    }
  }

  /**
   * Create interpreter from InterpreterSettingTemplate
   *
   * @param o interpreterSetting from InterpreterSettingTemplate
   */
  public InterpreterSetting(InterpreterSetting o) {
    this();
    this.id = o.name;
    this.name = o.name;
    this.group = o.group;
    this.properties = convertInterpreterProperties(
        (Map<String, DefaultInterpreterProperty>) o.getProperties());
    this.interpreterInfos = new ArrayList<>(o.getInterpreterInfos());
    this.option = InterpreterOption.fromInterpreterOption(o.getOption());
    this.dependencies = new ArrayList<>(o.getDependencies());
    this.interpreterDir = o.getInterpreterDir();
    this.interpreterRunner = o.getInterpreterRunner();
    this.conf = o.getConf();
  }

  private void createLauncher() throws IOException {
    this.launcher = PluginManager.get().loadInterpreterLauncher(
        getLauncherPlugin(), recoveryStorage);
  }

  public AngularObjectRegistryListener getAngularObjectRegistryListener() {
    return angularObjectRegistryListener;
  }

  public RemoteInterpreterProcessListener getRemoteInterpreterProcessListener() {
    return remoteInterpreterProcessListener;
  }

  public ApplicationEventListener getAppEventListener() {
    return appEventListener;
  }

  public DependencyResolver getDependencyResolver() {
    return dependencyResolver;
  }

  public InterpreterSettingManager getInterpreterSettingManager() {
    return interpreterSettingManager;
  }

  public InterpreterSetting setAngularObjectRegistryListener(AngularObjectRegistryListener
                                                   angularObjectRegistryListener) {
    this.angularObjectRegistryListener = angularObjectRegistryListener;
    return this;
  }

  public InterpreterSetting setAppEventListener(ApplicationEventListener appEventListener) {
    this.appEventListener = appEventListener;
    return this;
  }

  public InterpreterSetting setRemoteInterpreterProcessListener(RemoteInterpreterProcessListener
                                                      remoteInterpreterProcessListener) {
    this.remoteInterpreterProcessListener = remoteInterpreterProcessListener;
    return this;
  }

  public InterpreterSetting setDependencyResolver(DependencyResolver dependencyResolver) {
    this.dependencyResolver = dependencyResolver;
    return this;
  }

  public InterpreterSetting setInterpreterSettingManager(
      InterpreterSettingManager interpreterSettingManager) {
    this.interpreterSettingManager = interpreterSettingManager;
    return this;
  }

  public InterpreterSetting setLifecycleManager(LifecycleManager lifecycleManager) {
    this.lifecycleManager = lifecycleManager;
    return this;
  }

  public InterpreterSetting setRecoveryStorage(RecoveryStorage recoveryStorage) {
    this.recoveryStorage = recoveryStorage;
    return this;
  }

  public InterpreterSetting setInterpreterEventServer(
      RemoteInterpreterEventServer interpreterEventServer) {
    this.interpreterEventServer = interpreterEventServer;
    return this;
  }

  public InterpreterInfo getInterpreterInfo(String name) {
    Iterator it = this.interpreterInfos.iterator();
    while (it.hasNext()) {
      InterpreterInfo info = (InterpreterInfo) it.next();
      if (StringUtils.equals(info.getName(), name)) {
        return info;
      }
    }

    return null;
  }

  public RecoveryStorage getRecoveryStorage() {
    return recoveryStorage;
  }

  public LifecycleManager getLifecycleManager() {
    return lifecycleManager;
  }

  public String getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public String getGroup() {
    return group;
  }

  private String getInterpreterGroupId(String user, String noteId) {
    List<String> keys = new ArrayList<>();
    if (option.isExistingProcess) {
      keys.add(Constants.EXISTING_PROCESS);
    } else if (getOption().isIsolated()) {
      if (option.perUserIsolated()) {
        keys.add(user);
      }
      if (option.perNoteIsolated()) {
        keys.add(noteId);
      }
    } else {
      keys.add(SHARED_PROCESS);
    }

    //TODO(zjffdu) we encode interpreter setting id into groupId, this is not a good design
    return id + "-" + StringUtils.join(keys, "-");
  }

  private String getInterpreterSessionId(String user, String noteId) {
    String key;
    if (option.isExistingProcess()) {
      key = Constants.EXISTING_PROCESS;
    } else if (option.perNoteScoped() && option.perUserScoped()) {
      key = user + ":" + noteId;
    } else if (option.perUserScoped()) {
      key = user;
    } else if (option.perNoteScoped()) {
      key = noteId;
    } else {
      key = SHARED_SESSION;
    }

    return key;
  }

  public ManagedInterpreterGroup getOrCreateInterpreterGroup(String user, String noteId) {
    String groupId = getInterpreterGroupId(user, noteId);
    try {
      interpreterGroupWriteLock.lock();
      if (!interpreterGroups.containsKey(groupId)) {
        LOGGER.info("Create InterpreterGroup with groupId: {} for user: {} and note: {}",
            groupId, user, noteId);
        ManagedInterpreterGroup intpGroup = createInterpreterGroup(groupId);
        interpreterGroups.put(groupId, intpGroup);
      }
      return interpreterGroups.get(groupId);
    } finally {
      interpreterGroupWriteLock.unlock();;
    }
  }

  void removeInterpreterGroup(String groupId) {
    try {
      interpreterGroupWriteLock.lock();
      this.interpreterGroups.remove(groupId);
    } finally {
      interpreterGroupWriteLock.unlock();
    }
  }

  public ManagedInterpreterGroup getInterpreterGroup(String user, String noteId) {
    String groupId = getInterpreterGroupId(user, noteId);
    try {
      interpreterGroupReadLock.lock();
      return interpreterGroups.get(groupId);
    } finally {
      interpreterGroupReadLock.unlock();;
    }
  }

  ManagedInterpreterGroup getInterpreterGroup(String groupId) {
    return interpreterGroups.get(groupId);
  }

  public ArrayList<ManagedInterpreterGroup> getAllInterpreterGroups() {
    try {
      interpreterGroupReadLock.lock();
      return new ArrayList(interpreterGroups.values());
    } finally {
      interpreterGroupReadLock.unlock();
    }
  }

  Map<String, Object> getEditorFromSettingByClassName(String className) {
    for (InterpreterInfo intpInfo : interpreterInfos) {
      if (className.equals(intpInfo.getClassName())) {
        if (intpInfo.getEditor() == null) {
          break;
        }
        return intpInfo.getEditor();
      }
    }
    return DEFAULT_EDITOR;
  }

  void closeInterpreters(String user, String noteId) {
    ManagedInterpreterGroup interpreterGroup = getInterpreterGroup(user, noteId);
    if (interpreterGroup != null) {
      String sessionId = getInterpreterSessionId(user, noteId);
      interpreterGroup.close(sessionId);
    }
  }

  public void close() {
    LOGGER.info("Close InterpreterSetting: " + name);
    List<Thread> closeThreads = interpreterGroups.values().stream()
            .map(g -> new Thread(g::close, name + "-close"))
            .peek(t -> t.setUncaughtExceptionHandler((th, e) ->
                    LOGGER.error("InterpreterSetting close error", e)))
            .peek(Thread::start)
            .collect(Collectors.toList());
    interpreterGroups.clear();
    for (Thread t : closeThreads) {
      try {
        t.join();
      } catch (InterruptedException e) {
        LOGGER.error("Can't wait InterpreterSetting close threads", e);
        Thread.currentThread().interrupt();
        break;
      }
    }
  }

  public void setProperties(Object object) {
    if (object instanceof StringMap) {
      StringMap<String> map = (StringMap) properties;
      Properties newProperties = new Properties();
      for (String key : map.keySet()) {
        newProperties.put(key, map.get(key));
      }
      this.properties = newProperties;
    } else {
      this.properties = object;
    }
  }

  public Object getProperties() {
    return properties;
  }

  @VisibleForTesting
  public void setProperty(String name, String value) {
    ((Map<String, InterpreterProperty>) properties).put(name, new InterpreterProperty(name, value));
  }

  // This method is supposed to be only called by InterpreterSetting
  // but not InterpreterSetting Template
  public Properties getJavaProperties() {
    Properties jProperties = new Properties();
    Map<String, InterpreterProperty> iProperties = (Map<String, InterpreterProperty>) properties;
    for (Map.Entry<String, InterpreterProperty> entry : iProperties.entrySet()) {
      if (entry.getValue().getValue() != null) {
        jProperties.setProperty(entry.getKey().trim(),
            entry.getValue().getValue().toString().trim());
      }
    }

    if (!jProperties.containsKey("zeppelin.interpreter.output.limit")) {
      jProperties.setProperty("zeppelin.interpreter.output.limit",
          conf.getInt(ZEPPELIN_INTERPRETER_OUTPUT_LIMIT) + "");
    }

    if (!jProperties.containsKey("zeppelin.interpreter.max.poolsize")) {
      jProperties.setProperty("zeppelin.interpreter.max.poolsize",
          conf.getInt(ZEPPELIN_INTERPRETER_MAX_POOL_SIZE) + "");
    }

    String interpreterLocalRepoPath = conf.getInterpreterLocalRepoPath();
    //TODO(zjffdu) change it to interpreterDir/{interpreter_name}
    jProperties.setProperty("zeppelin.interpreter.localRepo",
        interpreterLocalRepoPath + "/" + id);
    return jProperties;
  }

  public ZeppelinConfiguration getConf() {
    return conf;
  }

  public InterpreterSetting setConf(ZeppelinConfiguration conf) {
    this.conf = conf;
    return this;
  }

  public List<Dependency> getDependencies() {
    return dependencies;
  }

  public void setDependencies(List<Dependency> dependencies) {
    this.dependencies = dependencies;
    loadInterpreterDependencies();
  }

  public InterpreterOption getOption() {
    return option;
  }

  public void setOption(InterpreterOption option) {
    this.option = option;
  }

  public String getInterpreterDir() {
    return interpreterDir;
  }

  public void setInterpreterDir(String interpreterDir) {
    this.interpreterDir = interpreterDir;
  }

  public List<InterpreterInfo> getInterpreterInfos() {
    return interpreterInfos;
  }

  void appendDependencies(List<Dependency> dependencies) {
    for (Dependency dependency : dependencies) {
      if (!this.dependencies.contains(dependency)) {
        this.dependencies.add(dependency);
      }
    }
    loadInterpreterDependencies();
  }

  void setInterpreterOption(InterpreterOption interpreterOption) {
    this.option = interpreterOption;
  }

  public void setProperties(Properties p) {
    this.properties = p;
  }

  void setGroup(String group) {
    this.group = group;
  }

  void setName(String name) {
    this.name = name;
  }

  /***
   * Interpreter status
   */
  public enum Status {
    DOWNLOADING_DEPENDENCIES,
    ERROR,
    READY
  }

  public Status getStatus() {
    return status;
  }

  public void setStatus(Status status) {
    this.status = status;
  }

  public String getErrorReason() {
    return errorReason;
  }

  public void setErrorReason(String errorReason) {
    this.errorReason = errorReason;
  }

  public void setInterpreterInfos(List<InterpreterInfo> interpreterInfos) {
    this.interpreterInfos = interpreterInfos;
  }

  public InterpreterRunner getInterpreterRunner() {
    return interpreterRunner;
  }

  public void setInterpreterRunner(InterpreterRunner interpreterRunner) {
    this.interpreterRunner = interpreterRunner;
  }

  public String getLauncherPlugin() {
    if (isRunningOnKubernetes()) {
      return "K8sStandardInterpreterLauncher";
    } else if (isRunningOnCluster()) {
      return "ClusterInterpreterLauncher";
    } if (isRunningOnDocker()) {
      return "DockerInterpreterLauncher";
    } else {
      if (group.equals("spark")) {
        return "SparkInterpreterLauncher";
      } else {
        return "StandardInterpreterLauncher";
      }
    }
  }

  private boolean isRunningOnKubernetes() {
    return conf.getRunMode() == ZeppelinConfiguration.RUN_MODE.K8S;
  }

  private boolean isRunningOnCluster() {
    return conf.isClusterMode();
  }

  private boolean isRunningOnDocker() {
    return conf.getRunMode() == ZeppelinConfiguration.RUN_MODE.DOCKER;
  }

  public boolean isUserAuthorized(List<String> userAndRoles) {
    if (!option.permissionIsSet()) {
      return true;
    }
    Set<String> intersection = new HashSet<>(userAndRoles);
    intersection.retainAll(option.getOwners());
    return intersection.isEmpty();
  }

  //////////////////////////// IMPORTANT ////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////
  // This is the only place to create interpreters. For now we always create multiple interpreter
  // together (one session). We don't support to create single interpreter yet.
  List<Interpreter> createInterpreters(String user, String interpreterGroupId, String sessionId) {
    List<Interpreter> interpreters = new ArrayList<>();
    List<InterpreterInfo> interpreterInfos = getInterpreterInfos();
    Properties intpProperties = getJavaProperties();
    for (InterpreterInfo info : interpreterInfos) {
      Interpreter interpreter = new RemoteInterpreter(intpProperties, sessionId,
          info.getClassName(), user, lifecycleManager);
      if (info.isDefaultInterpreter()) {
        interpreters.add(0, interpreter);
      } else {
        interpreters.add(interpreter);
      }
      LOGGER.info("Interpreter {} created for user: {}, sessionId: {}",
          interpreter.getClassName(), user, sessionId);
    }

    // TODO(zjffdu) this kind of hardcode is ugly. For now SessionConfInterpreter is used
    // for livy, we could add new property in interpreter-setting.json when there's new interpreter
    // require SessionConfInterpreter
    if (group.equals("livy")) {
      interpreters.add(
          new SessionConfInterpreter(intpProperties, sessionId, interpreterGroupId, this));
    } else {
      interpreters.add(new ConfInterpreter(intpProperties, sessionId, interpreterGroupId, this));
    }
    return interpreters;
  }

  synchronized RemoteInterpreterProcess createInterpreterProcess(String interpreterGroupId,
                                                                 String userName,
                                                                 Properties properties)
      throws IOException {
    if (launcher == null) {
      createLauncher();
    }
    InterpreterLaunchContext launchContext = new
        InterpreterLaunchContext(properties, option, interpreterRunner, userName,
        interpreterGroupId, id, group, name, interpreterEventServer.getPort(), interpreterEventServer.getHost());
    RemoteInterpreterProcess process = (RemoteInterpreterProcess) launcher.launch(launchContext);
    recoveryStorage.onInterpreterClientStart(process);
    return process;
  }

  List<Interpreter> getOrCreateSession(String user, String noteId) {
    ManagedInterpreterGroup interpreterGroup = getOrCreateInterpreterGroup(user, noteId);
    Preconditions.checkNotNull(interpreterGroup, "No InterpreterGroup existed for user {}, " +
        "noteId {}", user, noteId);
    String sessionId = getInterpreterSessionId(user, noteId);
    return interpreterGroup.getOrCreateSession(user, sessionId);
  }

  public Interpreter getDefaultInterpreter(String user, String noteId) {
    return getOrCreateSession(user, noteId).get(0);
  }

  public Interpreter getInterpreter(String user, String noteId, String replName) {
    Preconditions.checkNotNull(noteId, "noteId should be not null");
    Preconditions.checkNotNull(replName, "replName should be not null");

    String className = getInterpreterClassFromInterpreterSetting(replName);
    if (className == null) {
      return null;
    }
    List<Interpreter> interpreters = getOrCreateSession(user, noteId);
    for (Interpreter interpreter : interpreters) {
      if (className.equals(interpreter.getClassName())) {
        return interpreter;
      }
    }
    return null;
  }

  private String getInterpreterClassFromInterpreterSetting(String replName) {
    Preconditions.checkNotNull(replName, "replName should be not null");

    for (InterpreterInfo info : interpreterInfos) {
      String infoName = info.getName();
      if (null != info.getName() && replName.equals(infoName)) {
        return info.getClassName();
      }
    }
    //TODO(zjffdu) It requires user can not create interpreter with name `conf`,
    // conf is a reserved word of interpreter name
    if (replName.equals("conf")) {
      if (group.equals("livy")) {
        return SessionConfInterpreter.class.getName();
      } else {
        return ConfInterpreter.class.getName();
      }
    }
    return null;
  }

  private ManagedInterpreterGroup createInterpreterGroup(String groupId) {
    AngularObjectRegistry angularObjectRegistry;
    ManagedInterpreterGroup interpreterGroup = new ManagedInterpreterGroup(groupId, this);
    angularObjectRegistry =
        new RemoteAngularObjectRegistry(groupId, angularObjectRegistryListener, interpreterGroup);
    interpreterGroup.setAngularObjectRegistry(angularObjectRegistry);
    return interpreterGroup;
  }

  /**
   * Throw exception when interpreter process has already launched
   *
   * @param interpreterGroupId
   * @param properties
   * @throws IOException
   */
  public void setInterpreterGroupProperties(String interpreterGroupId, Properties properties)
      throws IOException {
    ManagedInterpreterGroup interpreterGroup = this.interpreterGroups.get(interpreterGroupId);
    for (List<Interpreter> session : interpreterGroup.sessions.values()) {
      for (Interpreter intp : session) {
        if (!intp.getProperties().equals(properties) &&
            interpreterGroup.getRemoteInterpreterProcess() != null &&
            interpreterGroup.getRemoteInterpreterProcess().isRunning()) {
          throw new IOException("Can not change interpreter properties when interpreter process " +
              "has already been launched");
        }
        intp.setProperties(properties);
      }
    }
  }

  private void loadInterpreterDependencies() {
    setStatus(Status.DOWNLOADING_DEPENDENCIES);
    setErrorReason(null);
    Thread t = new Thread() {
      public void run() {
        try {
          // dependencies to prevent library conflict
          File localRepoDir = new File(conf.getInterpreterLocalRepoPath() + "/" + id);
          if (localRepoDir.exists()) {
            try {
              FileUtils.forceDelete(localRepoDir);
            } catch (FileNotFoundException e) {
              LOGGER.info("A file that does not exist cannot be deleted, nothing to worry", e);
            }
          }

          // load dependencies
          List<Dependency> deps = getDependencies();
          if (deps != null) {
            for (Dependency d : deps) {
              File destDir = new File(
                  conf.getRelativeDir(ZeppelinConfiguration.ConfVars.ZEPPELIN_DEP_LOCALREPO));

              if (d.getExclusions() != null) {
                dependencyResolver.load(d.getGroupArtifactVersion(), d.getExclusions(),
                    new File(destDir, id));
              } else {
                dependencyResolver
                    .load(d.getGroupArtifactVersion(), new File(destDir, id));
              }
            }
          }

          setStatus(Status.READY);
          setErrorReason(null);
        } catch (Exception e) {
          LOGGER.error(String.format("Error while downloading repos for interpreter group : %s," +
                  " go to interpreter setting page click on edit and save it again to make " +
                  "this interpreter work properly. : %s",
              getGroup(), e.getLocalizedMessage()), e);
          setErrorReason(e.getLocalizedMessage());
          setStatus(Status.ERROR);
        }
      }
    };

    t.start();
  }

  //TODO(zjffdu) ugly code, should not use JsonObject as parameter. not readable
  public void convertPermissionsFromUsersToOwners(JsonObject jsonObject) {
    if (jsonObject != null) {
      JsonObject option = jsonObject.getAsJsonObject("option");
      if (option != null) {
        JsonArray users = option.getAsJsonArray("users");
        if (users != null) {
          if (this.option.getOwners() == null) {
            this.option.owners = new LinkedList<>();
          }
          for (JsonElement user : users) {
            this.option.getOwners().add(user.getAsString());
          }
        }
      }
    }
  }

  // For backward compatibility of interpreter.json format after ZEPPELIN-2403
  static Map<String, InterpreterProperty> convertInterpreterProperties(Object properties) {
    if (properties != null && properties instanceof StringMap) {
      Map<String, InterpreterProperty> newProperties = new HashMap<>();
      StringMap p = (StringMap) properties;
      for (Object o : p.entrySet()) {
        Map.Entry entry = (Map.Entry) o;
        if (!(entry.getValue() instanceof StringMap)) {
          InterpreterProperty newProperty = new InterpreterProperty(
              entry.getKey().toString(),
              entry.getValue(),
              InterpreterPropertyType.STRING.getValue());
          newProperties.put(entry.getKey().toString(), newProperty);
        } else {
          // already converted
          return (Map<String, InterpreterProperty>) properties;
        }
      }
      return newProperties;

    } else if (properties instanceof Map) {
      Map<String, Object> dProperties =
          (Map<String, Object>) properties;
      Map<String, InterpreterProperty> newProperties = new HashMap<>();
      for (String key : dProperties.keySet()) {
        Object value = dProperties.get(key);
        if (value instanceof InterpreterProperty) {
          return (Map<String, InterpreterProperty>) properties;
        } else if (value instanceof StringMap) {
          StringMap stringMap = (StringMap) value;
          InterpreterProperty newProperty = new InterpreterProperty(
              key,
              stringMap.get("value"),
              stringMap.containsKey("type") ? stringMap.get("type").toString() : "string");

          newProperties.put(newProperty.getName(), newProperty);
        } else if (value instanceof DefaultInterpreterProperty){
          DefaultInterpreterProperty dProperty = (DefaultInterpreterProperty) value;
          InterpreterProperty property = new InterpreterProperty(
              key,
              dProperty.getValue(),
              dProperty.getType() != null ? dProperty.getType() : "string"
              // in case user forget to specify type in interpreter-setting.json
          );
          newProperties.put(key, property);
        } else if (value instanceof String) {
          InterpreterProperty newProperty = new InterpreterProperty(
              key,
              value,
              "string");

          newProperties.put(newProperty.getName(), newProperty);
        } else {
          throw new RuntimeException("Can not convert this type of property: " +
              value.getClass());
        }
      }
      return newProperties;
    }
    throw new RuntimeException("Can not convert this type: " + properties.getClass());
  }

  public void waitForReady(long timeout) throws InterpreterException {
    long start = System.currentTimeMillis();
    while(status != Status.READY) {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        throw new InterpreterException(e);
      }
      long now = System.currentTimeMillis();
      if ((now - start) > timeout) {
        throw new InterpreterException("Fail to download dependencies in " + timeout / 1000
                + " seconds");
      }
    }
  }

  public void waitForReady() throws InterpreterException {
    waitForReady(Long.MAX_VALUE);
  }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <TITLE>Adobe Software Technology Lab: Assignable</TITLE>
    <META HTTP-EQUIV="content-type" CONTENT="text/html;charset=ISO-8859-1"/>
    <LINK TYPE="text/css" REL="stylesheet" HREF="adobe_source.css"/>
    <LINK REL="alternate" TITLE="stlab.adobe.com RSS" HREF="http://sourceforge.net/export/rss2_projnews.php?group_id=132417&rss_fulltext=1" TYPE="application/rss+xml"/>

Documentation

        Overview

        Building ASL

        Documentation

        Library Wiki Docs

        Indices

        Browse Perforce

More Info

        Release Notes

        Wiki

        Site Search

        License

        Success Stories

        Contributors

Media

        Download

        Perforce Depots

Support

        ASL SourceForge Home

        Mailing Lists

        Discussion Forums

        Report Bugs

        Suggest Features

        Contribute to ASL

RSS

        Short-text news

        Full-text news

        File releases

Other Adobe Projects

        Open @ Adobe

        Adobe Open Source

        Adobe Labs

        Adobe Media Gallery

        C++ Benchmarks

Other Resources

        Boost

        RIAForge

        SGI STL

Assignable

Category: utilities 		Component type: concept

Description

A type is Assignable if it is possible to copy objects of that type and to assign values to variables.

Refinement of

Associated types

Notation

X 	A type that is a model of Assignable

x, y 	Object of type X

Definitions

Valid expressions

Name	Expression	Type requirements	Return type

Copy constructor 	X(x) 	  	X

Copy constructor

X x(y);
X x = y;

Assignment 	x = y [1] 	  	X&

Swap 	swap(x,y) 	  	void

Expression semantics

Name	Expression	Precondition	Semantics	Postcondition

Copy constructor 	X(x) 	  	  	X(x) is a copy of x [2]

Copy constructor 	X(x) 	  	  	X(x) is a copy of x [2]

Copy constructor

X x(y);
X x = y;

  	  	  	x is a copy of y [2]

Assignment 	x = y [1] 	  	  	x is a copy of y [2]

Swap 	adobe::swap(x,y)[3] 	  	Equivalent to

{
  X tmp = x;
  x = y;
  y = tmp;
}

Complexity guarantees

Invariants

Models

int

Notes

[1] One implication of this requirement is that a const type is not Assignable. For example, const int is not Assignable: if x is declared to be of type const int, then x = 7 is illegal. Similarly, the type pair<const int, int> is not Assignable.

[2] The reason this says "x is a copy of y", rather than "x == y", is that operator== is not necessarily defined: equality is not a requirement of Assignable. If the type X is EqualityComparable as well as Assignable, then a copy of x should compare equal to x.

[3] swap will not throw an exception for an assignable type. For types with remote parts, swap must be specialized to swap the remote parts. Please see the documentation on adobe::swap for more information.

[4] If assignment can throw an exception it must leave the value being assigned to untouched. For types with remote parts, this can be accomplished by implementing assignment as copy constructing a temp, and then swapping the temp with the value being assigned to. See the note adobe::swap().

See also

DefaultConstructible

Company |

Online Privacy Policy |

Terms of Use |

Contact Us |

Accessibility |

Report Piracy |

Permissions & Trademarks |

Product License Agreements |

Send Feedback

Copyright © 2006-2007 Adobe Systems Incorporated.

Use of this website signifies your agreement to the Terms of Use and Online Privacy Policy.

Search powered by Google


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Die Gattung Phlegmacium (Schleimköpfe). Die Pilze Mitteleuropas 4 260 (1960)

#### Original name
Cortinarius subbalteatus Kühner

### Remarks
null


text:
#include "NotificationServer.h"

#include "FanoutLogger.h"
#include "NotificationClientHandler.h"
#include "NotificationChannel.h"

#include <string>

#ifdef HAVE_ERRNO_H
    #include <errno.h>
#endif

#ifdef HAVE_EVENT2_EVENT_H
    #include <event2/event.h>
#endif

#ifdef HAVE_NETINET_IN_H
    #include <netinet/in.h>
#endif
#ifdef HAVE_NETINET_TCP_H
    #include <netinet/tcp.h>
#endif

#ifdef HAVE_SYS_SOCKET_H
    #include <sys/socket.h>
#endif
#ifdef HAVE_SYS_TYPES_H
    #include <sys/types.h>
#endif
#ifdef HAVE_SYS_UN_H
    #include <sys/un.h>
#endif

#ifdef HAVE_UNISTD_H
    #include <unistd.h>
#endif

using namespace std;

namespace NotificationServer
{
    int listenSocket = -1;
    #ifdef USE_IPV6
    int listenSocketV6 = -1;
    #endif

    event_base* eventBase = NULL;
    const struct timeval cleanupTimeout = {300, 0};

    void CleanupEmptyChannelsCallback(evutil_socket_t nullSocket, short flags, void* socketParam);

    void StartServer(unsigned short port)
    {
        // Cleanup in case the server was started before
        if (eventBase || listenSocket != -1)
            ShutdownServer();

        // Clean up if IPv6 is used and the socket is still valid
        #ifdef USE_IPV6
            if (listenSocketV6 != -1)
                ShutdownServer();
        #endif

        // Create new event base
        eventBase = event_base_new();
        if (!eventBase)
        {
            FanoutLogger::LogMessage(FanoutLogger::FANOUT_LOG_ERROR, "NotificationServer", "Error starting new event base.");
            return;
        }

        // Bind for IPv4
        {
            // Create new listen socket, make it non-blocking and reusable
            listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

            evutil_make_socket_nonblocking(listenSocket);
            evutil_make_listen_socket_reuseable(listenSocket);

            if (listenSocket < 0)
            {
                FanoutLogger::LogMessage(FanoutLogger::FANOUT_LOG_ERROR, "NotificationServer", "Error opening IPv4 listen socket.");
                return;
            }

            // Listen on all IPv4 addresses, port as passed in
            sockaddr_in serverAddress;
            serverAddress.sin_family = AF_INET;
            serverAddress.sin_addr.s_addr = INADDR_ANY;
            serverAddress.sin_port = htons(port);
            memset(&serverAddress.sin_zero, 0, sizeof(serverAddress.sin_zero));

            // Bind to socket
            if (bind(listenSocket, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0)
            {
                ostringstream errorMessage;
                errorMessage << errno << " - " << "Error binding to the IPv4 listening socket.";
                FanoutLogger::LogMessage(FanoutLogger::FANOUT_LOG_ERROR, "NotificationServer", errorMessage);
                return;
            }

            // Listen on socket
            if (listen(listenSocket, 5) < 0)
            {
                ostringstream errorMessage;
                errorMessage << errno << " - " << "Listening to the IPv4 listening socket.";
                FanoutLogger::LogMessage(FanoutLogger::FANOUT_LOG_ERROR, "NotificationServer", errorMessage);
                return;
            }

            // Create new event to accept clients, add it
            event* listener_event = event_new(eventBase, listenSocket, EV_READ|EV_PERSIST, &NotificationClientHandler::AcceptClient, (void*) eventBase);
            event_add(listener_event, NULL);
        }

        #ifdef USE_IPV6
        {
            // Create new listen socket, make it non-blocking and reusable
            listenSocketV6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);

            evutil_make_socket_nonblocking(listenSocketV6);
            evutil_make_listen_socket_reuseable(listenSocketV6);

            #ifdef IPV6_V6ONLY
            {
                unsigned int nOne = 1;
                if (setsockopt(listenSocketV6, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(nOne)) != 0)
                {
                    ostringstream errorMessage;
                    errorMessage << errno << " - " << "Error setting IPV6_V6ONLY.";
                    FanoutLogger::LogMessage(FanoutLogger::FANOUT_LOG_ERROR, "NotificationServer", errorMessage);
                    return;

                }
            }
            #endif

            if (listenSocketV6 < 0)
            {
                FanoutLogger::LogMessage(FanoutLogger::FANOUT_LOG_ERROR, "NotificationServer", "Error opening IPv6 listen socket.");
                return;
            }

            sockaddr_in6 serverAddress6;
            serverAddress6.sin6_family = AF_INET6;
            serverAddress6.sin6_addr = in6addr_any;
            serverAddress6.sin6_port = htons(port);

            // Bind to socket
            if (bind(listenSocketV6, (struct sockaddr *) &serverAddress6, sizeof(serverAddress6)) < 0)
            {
                ostringstream errorMessage;
                errorMessage << errno << " - " << "Error binding to the IPv6 listening socket.";
                FanoutLogger::LogMessage(FanoutLogger::FANOUT_LOG_ERROR, "NotificationServer", errorMessage);
                return;
            }

            // Listen on socket
            if (listen(listenSocketV6, 5) < 0)
            {
                ostringstream errorMessage;
                errorMessage << errno << " - " << "Listening to the IPv6 listening socket.";
                FanoutLogger::LogMessage(FanoutLogger::FANOUT_LOG_ERROR, "NotificationServer", errorMessage);
                return;
            }

            // Create new event to accept clients, add it
            event* listener_v6_event = event_new(eventBase, listenSocketV6, EV_READ|EV_PERSIST, &NotificationClientHandler::AcceptClient, (void*) eventBase);
            event_add(listener_v6_event, NULL);

        }
        #endif // USE_IPV6

        // Create timer to cleanup stale channels
        event* cleanupEmptyChannels_event = evtimer_new(eventBase, &CleanupEmptyChannelsCallback, NULL);
        evtimer_add(cleanupEmptyChannels_event, &cleanupTimeout);

        // Loop through all events (more will be added
        event_base_loop(eventBase, 0);
    }

    void ShutdownServer()
    {
        // Break the loop if event container is set
        if (eventBase)
            event_base_loopbreak(eventBase);

        // Cleanup clients and channels
        NotificationClientHandler::CleanupClients();
        NotificationChannel::CleanupChannels();

        // Cleanup socket if set
        if (listenSocket != -1)
        {
            close(listenSocket);
            listenSocket = -1;
        }

        #ifdef USE_IPV6
            if (listenSocketV6 != -1)
            {
                close(listenSocketV6);
                listenSocketV6 = -1;
            }
        #endif

        // Cleanup event container if set
        if (eventBase)
        {
            event_base_free(eventBase);
            eventBase = NULL;
        }

    }

    void CleanupEmptyChannelsCallback(evutil_socket_t nullSocket, short flags, void* socketParam)
    {
        NotificationChannel::CleanupEmptyChannels();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TextView android:text="Select Conversion:" android:id="@+id/explanationtext"
		android:layout_width="fill_parent" android:layout_below="@+id/buttonrow"
		android:layout_height="wrap_content"></TextView>
	<Spinner android:layout_width="fill_parent"
		android:layout_below="@+id/explanationtext" android:layout_height="wrap_content"
		android:id="@+id/conversions">
	</Spinner>

	<EditText android:layout_width="fill_parent" android:id="@+id/invalue"
		android:text="1.0" android:numeric="decimal" android:layout_height="wrap_content"></EditText>

	<TextView android:text="1.0 Meters is 3.28083 Feet"
		android:id="@+id/conversiontext" android:layout_width="fill_parent"
		 android:layout_height="wrap_content"></TextView>

	<com.google.ads.AdView android:id="@+id/adView"
		android:layout_alignParentBottom="true" android:layout_width="fill_parent"
		android:layout_height="wrap_content" ads:adUnitId="a14e172929306dd" ads:adSize="BANNER"
		ads:loadAdOnCreate="false" />

</LinearLayout>


text:
package org.apache.provisionr.activiti.karaf.commands.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;

/**
 * This class provides common utils for commands processing
 *
 * @author Srinivasan Chikkala
 */
public class Commands {

    public static final Commands UTIL = new Commands();

    public void printNameValues(PrintWriter out, Map<String, String> nvMap) {
        String fmt = "  %-16.16s %-20.60s\n";
        for (Map.Entry<String, String> entry : nvMap.entrySet()) {
            out.printf(fmt, entry.getKey() + ":", entry.getValue());
        }
    }

    public String formatDate(Date date) {
        String dateTxt = "--";
        if (date != null) {
            dateTxt = DateFormat.getDateTimeInstance().format(date);
        }
        return dateTxt;
    }

    public String formatDuration(Long duration) {
        String dTxt = "--";
        if (duration != null) {
            SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss:SSS");
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            dTxt = format.format(new Date(duration));
        }
        return dTxt;
    }

    public void printText(PrintWriter out, Reader txtReader, String tabSpace) {
        BufferedReader in = new BufferedReader(txtReader);
        String line = null;
        try {
            while ((line = in.readLine()) != null) {
                out.printf("  %-16.16s %s\n", tabSpace, line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Convert a simple object to string.
     *
     * @param obj object .
     * @return string if the object is simple. else return null.
     */
    public String valueOf(Object obj) {
        String value = null;
        if (obj == null) {
            value = "NULL";
        } else if (obj.getClass().isPrimitive()
            || obj.getClass().isEnum()
            || obj instanceof java.lang.String) {
            value = obj.toString();
        } else if (obj instanceof Date) {
            value = formatDate((Date) obj);
        } else {
            value = null;
        }
        return value;
    }
}


text:
<head>
    <title>{% if page.title %}{{ site.name }} - {{ page.title }}{% else %}{{ site.name }}{% endif %}</title>
    <meta charset="utf-8">
    <meta name="author" content="{{ site.author }}">
    <meta name="description" content="{{ site.description }}">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
    <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Martel:200,400,700">
    <link rel="stylesheet" href="{{ site.url }}/css/min.css">
<!--    <link rel="stylesheet" href="{{ site.url }}/css/full.css">-->
    <link rel="apple-touch-icon" sizes="57x57" href="{{ site.url }}/favicon/apple-touch-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="{{ site.url }}/favicon/apple-touch-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="{{ site.url }}/favicon/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="{{ site.url }}/favicon/apple-touch-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="{{ site.url }}/favicon/apple-touch-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="{{ site.url }}/favicon/apple-touch-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="{{ site.url }}/favicon/apple-touch-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="{{ site.url }}/favicon/apple-touch-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="{{ site.url }}/favicon/apple-touch-icon-180x180.png">
    <link rel="icon" type="image/png" href="{{ site.url }}/favicon/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="{{ site.url }}/favicon/favicon-194x194.png" sizes="194x194">
    <link rel="icon" type="image/png" href="{{ site.url }}/favicon/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="{{ site.url }}/favicon/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="{{ site.url }}/favicon/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="{{ site.url }}/favicon/manifest.json">
    <link rel="mask-icon" href="{{ site.url }}/favicon/safari-pinned-tab.svg" color="#7a7878">
    <link rel="shortcut icon" href="{{ site.url }}/favicon/favicon.ico">
    <meta name="apple-mobile-web-app-title" content="Italian">
    <meta name="application-name" content="Italian">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="{{ site.url }}/favicon/mstile-144x144.png">
    <meta name="msapplication-config" content="{{ site.url }}/favicon/browserconfig.xml">
    <meta name="theme-color" content="#ffffff">
</head>


text:
var through = require('through2'),
    gutil = require('gulp-util'),
    vfs = require('vinyl-fs'),
    es = require('event-stream'),
    fs = require('fs'),
    PluginError = gutil.PluginError;

// Consts
const PLUGIN_NAME = 'gulp-replace-ref';

// Plugin level function (dealing with files)
function gulpReplaceRef(opts) {

    opts = opts || {};

    var stream;

    // Creating a stream through which each file will pass
    stream = through.obj(function (srcFile, enc, callback) {
        var self = this;
        if (srcFile.isNull()) {
            self.push(srcFile); // Do nothing if no contents
            return callback();
        }

        if (srcFile.isBuffer()) {

            var strToReplace = srcFile.path.match( opts.srcMatch )[0], stream, targetMatch = opts.targetMatch;

            vfs.src(opts.target).pipe(es.map(function(phpFile, cb){
                //console.log(phpFile.path);
                var content = phpFile.contents.toString();
                if(targetMatch(srcFile.path).test(content)){
                    fs.writeFile(phpFile.path, content.replace(targetMatch(srcFile.path), strToReplace));
                    console.log('php file updated: ' + phpFile.path);
                }

                cb(null, phpFile);
            }));

            self.push(srcFile);
            return callback();
        }

        if (srcFile.isStream()) {
            this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!'));
            return callback();
        }
    });

    // returning the file stream
    return stream;
};

// Exporting the plugin main function
module.exports = gulpReplaceRef;


text:
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.8.0'" to load this file. \quit

DROP FUNCTION IF EXISTS cdb_dataservices_server.cdb_route_with_waypoints(text, text, geometry(Geometry, 4326)[], text, text[], text);
DROP FUNCTION IF EXISTS cdb_dataservices_server._cdb_mapzen_route_with_waypoints(text, text, geometry(Geometry, 4326)[], text, text[], text);

CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapzen_route_point_to_point(
  username TEXT,
  orgname TEXT,
  origin geometry(Point, 4326),
  destination geometry(Point, 4326),
  mode TEXT,
  options text[] DEFAULT ARRAY[]::text[],
  units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
  import json
  from cartodb_services.mapzen import MapzenRouting, MapzenRoutingResponse
  from cartodb_services.mapzen.types import polyline_to_linestring
  from cartodb_services.metrics import QuotaService
  from cartodb_services.tools import Coordinate

  redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
  user_routing_config = GD["user_routing_config_{0}".format(username)]

  quota_service = QuotaService(user_routing_config, redis_conn)
  if not quota_service.check_user_quota():
    plpy.error('You have reached the limit of your quota')

  try:
    client = MapzenRouting(user_routing_config.mapzen_api_key)

    if not origin or not destination:
      plpy.notice("Empty origin or destination")
      quota_service.increment_empty_service_use()
      return [None, None, None]

    orig_lat = plpy.execute("SELECT ST_Y('%s') AS lat" % origin)[0]['lat']
    orig_lon = plpy.execute("SELECT ST_X('%s') AS lon" % origin)[0]['lon']
    origin_coordinates = Coordinate(orig_lon, orig_lat)
    dest_lat = plpy.execute("SELECT ST_Y('%s') AS lat" % destination)[0]['lat']
    dest_lon = plpy.execute("SELECT ST_X('%s') AS lon" % destination)[0]['lon']
    dest_coordinates = Coordinate(dest_lon, dest_lat)

    resp = client.calculate_route_point_to_point(origin_coordinates, dest_coordinates, mode, options, units)

    if resp and resp.shape:
      shape_linestring = polyline_to_linestring(resp.shape)
      if shape_linestring:
        quota_service.increment_success_service_use()
        return [shape_linestring, resp.length, resp.duration]
      else:
        quota_service.increment_empty_service_use()
        return [None, None, None]
    else:
      quota_service.increment_empty_service_use()
      return [None, None, None]
  except BaseException as e:
    import sys, traceback
    type_, value_, traceback_ = sys.exc_info()
    quota_service.increment_failed_service_use()
    error_msg = 'There was an error trying to obtain route using mapzen provider: {0}'.format(e)
    plpy.notice(traceback.format_tb(traceback_))
    plpy.error(error_msg)
  finally:
    quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu SECURITY DEFINER;

CREATE OR REPLACE FUNCTION cdb_dataservices_server.cdb_route_point_to_point(
  username TEXT,
  orgname TEXT,
  origin geometry(Point, 4326),
  destination geometry(Point, 4326),
  mode TEXT,
  options text[] DEFAULT ARRAY[]::text[],
  units text DEFAULT 'kilometers')
RETURNS cdb_dataservices_server.simple_route AS $$
  plpy.execute("SELECT cdb_dataservices_server._connect_to_redis('{0}')".format(username))
  redis_conn = GD["redis_connection_{0}".format(username)]['redis_metrics_connection']
  plpy.execute("SELECT cdb_dataservices_server._get_routing_config({0}, {1})".format(plpy.quote_nullable(username), plpy.quote_nullable(orgname)))
  user_routing_config = GD["user_routing_config_{0}".format(username)]

  mapzen_plan = plpy.prepare("SELECT * FROM cdb_dataservices_server._cdb_mapzen_route_point_to_point($1, $2, $3, $4, $5, $6, $7) as route;", ["text", "text", "geometry(Point, 4326)", "geometry(Point, 4326)", "text", "text[]", "text"])
  result = plpy.execute(mapzen_plan, [username, orgname, origin, destination, mode, options, units])
  return [result[0]['shape'],result[0]['length'], result[0]['duration']]
$$ LANGUAGE plpythonu;


text:
package com.navercorp.pinpoint.plugin.common.servlet.util;

import com.navercorp.pinpoint.bootstrap.plugin.request.RequestAdaptor;
import com.navercorp.pinpoint.bootstrap.util.NetworkUtils;
import com.navercorp.pinpoint.common.plugin.util.HostAndPort;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Woonduk Kang(emeroad)
 */
public class HttpServletRequestAdaptor implements RequestAdaptor<HttpServletRequest> {

    public HttpServletRequestAdaptor() {
    }

    @Override
    public String getHeader(HttpServletRequest request, String name) {
        return request.getHeader(name);
    }

    @Override
    public String getRpcName(HttpServletRequest request) {
        return request.getRequestURI();
    }

    @Override
    public String getEndPoint(HttpServletRequest request) {
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        return HostAndPort.toHostAndPortString(serverName, serverPort);
    }

    @Override
    public String getRemoteAddress(HttpServletRequest request) {
        return request.getRemoteAddr();
    }

    @Override
    public String getAcceptorHost(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        final String acceptorHost = url != null ? NetworkUtils.getHostFromURL(url.toString()) : null;
        return acceptorHost;
    }
}


text: Stuff from the ruby course at Sofia University