text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Perfiles extends CI_Controller {

	public function index(){

        $config['base_url'] = base_url() . 'Perfiles/index/';
        $config['total_rows'] = $this->PerfilesModel->countPerfil();
        $config['per_page'] = 10;
        $config['uri_segment'] = 3;
        $config['num_links'] = 5;
		$config['reuse_query_string'] = TRUE;
		$config['page_query_string'] = TRUE;
		$config['query_string_segment'] = 'page';
        $config['prev_link'] = 'chevron_left';
        $config['prev_tag_open'] = '
';
        $config['prev_tag_close'] = '
';
        $config['next_link'] = 'chevron_right';
        $config['next_tag_open'] = '
';
        $config['next_tag_close'] = '
';
        $config['full_tag_open'] = '
';
        $config['full_tag_close'] = '
';
        $config['num_tag_open'] = '
';
        $config['num_tag_close'] = '
';
        $config['cur_tag_open'] = '
';
        $config['cur_tag_close'] = '
';

        $this->pagination->initialize($config);
        $result = $this->PerfilesModel->getAllPerfil($config['per_page']);

        $data['consulta'] = $result;
        $data['pagination'] = $this->pagination->create_links();

		$empresa_id = $this->PerfilesModel->getIDMaestro('Empresas');
		$depto_id = $this->PerfilesModel->getIDMaestro('Departamentos');
		$data['depto'] = $this->PerfilesModel->getDepto($depto_id['Id_Cat_Prim']);
		$data['empresa'] = $this->PerfilesModel->getEmpresa($empresa_id['Id_Cat_Prim']);

        $this->load->view('templates/header.php');
        $this->load->view('perfiles/perfiles.php', $data);
        $this->load->view('templates/footer.php');
	}

	public function contenido_busqueda_perfiles(){
		$descripcion = $this->input->post("descripcion");

		$config['base_url'] = base_url() . 'Perfiles/index/';
        $config['total_rows'] = $this->PerfilesModel->countPerfil();
        $config['per_page'] = 10;
        $config['uri_segment'] = 3;
        $config['num_links'] = 5;
		$config['reuse_query_string'] = TRUE;
		$config['page_query_string'] = TRUE;
		$config['query_string_segment'] = 'page';
        $config['prev_link'] = 'chevron_left';
        $config['prev_tag_open'] = '
';
        $config['prev_tag_close'] = '
';
        $config['next_link'] = 'chevron_right';
        $config['next_tag_open'] = '
';
        $config['next_tag_close'] = '
';
        $config['full_tag_open'] = '
';
        $config['full_tag_close'] = '
';
        $config['num_tag_open'] = '
';
        $config['num_tag_close'] = '
';
        $config['cur_tag_open'] = '
';
        $config['cur_tag_close'] = '
';

        $this->pagination->initialize($config);
        $result = $this->PerfilesModel->getAllPerfilBuscador($config['per_page'], $descripcion);

        $data['consulta'] = $result;
        $data['pagination'] = $this->pagination->create_links();

		$empresa_id = $this->PerfilesModel->getIDMaestro('Empresas');
		$depto_id = $this->PerfilesModel->getIDMaestro('Departamentos');
		$depto = $this->PerfilesModel->getDepto($depto_id['Id_Cat_Prim']);
		$empresa = $this->PerfilesModel->getEmpresa($empresa_id['Id_Cat_Prim']);

		echo '

												<a href="<?= base_url() ?>Perfiles/index/?order=Descripcion&by=DESC">arrow_drop_down
												Descripcion
												<a href="<?= base_url() ?>Perfiles/index/?order=Descripcion&by=ASC">arrow_drop_up

											Departamento
											Empresa

												Actions

									';

									foreach ($result->result() as $row) {
									$reload = "'".base_url()."Perfiles/delPerfil/".$row->Id_Perfil."'";
									echo '

											'. $row->Descripcion .'
											'. $depto[$row->Id_Cat_Departamento] .'
											'. $empresa[$row->Id_Cat_Empresa] .'

													Id_Perfil.'" class="btn-flat btn-small waves-effect">
														create

													Descripcion.'?")) { window.location.href = '.$reload.' } event.returnValue = false; return false;" class="btn-flat btn-small waves-effect btnDelete">
														delete

									';

									}
									echo '

								';
                                echo $this->pagination->create_links();

	}

	public function newPerfil(){
        $this->load->view('templates/header.php');

        $this->form_validation->set_error_delimiters('
', '
');
        $this->form_validation->set_rules('Descripcion', 'Descripcion', 'required',
			array(
					'required'	=> 'do_not_disturb_on Se requiere %s.'
			)
		);

        $this->form_validation->set_rules('Id_Cat_Empresa', 'Empresa', 'required',
			array(
					'required'	=> 'do_not_disturb_on Se requiere %s.'
			)
		);
        $this->form_validation->set_rules('Id_Cat_Departamento', 'Departamento', 'required',
			array(
					'required'	=> 'do_not_disturb_on Se requiere %s.'
			)
		);

        if ($this->form_validation->run() == TRUE) {
            if ($this->input->method() == 'post'){
                $data = array(
					'Descripcion'	=>  $this->input->post('Descripcion'),
					'Id_Cat_Departamento'	=>  $this->input->post('Id_Cat_Departamento'),
					'Id_Cat_Empresa'	=>  $this->input->post('Id_Cat_Empresa')
                );
                $error = $this->PerfilesModel->addPerfil($data);
                if ($error['code'] === 0){
                    $this->session->set_flashdata('msg', '
done_all Perfil registrado correctamente!
');
                    redirect(base_url(). 'Perfiles/');
                }else{
                    $this->session->set_flashdata('msg', '
do_not_disturb_on Error al registrar el Perfil!
');
                }
			}
		}

		$empresa_id = $this->PerfilesModel->getIDMaestro('Empresas');
		$depto_id = $this->PerfilesModel->getIDMaestro('Departamentos');
		$data['depto'] = $this->PerfilesModel->getDepto($depto_id['Id_Cat_Prim']);
		$data['empresa'] = $this->PerfilesModel->getEmpresa($empresa_id['Id_Cat_Prim']);

		$this->load->view('perfiles/newPerfil.php', $data);
        $this->load->view('templates/footer.php');
	}

	public function editPerfil($id){
        $this->load->view('templates/header.php');

        $this->form_validation->set_error_delimiters('
', '
');
        $this->form_validation->set_rules('Descripcion', 'Descripcion', 'required',
			array(
					'required'	=> 'do_not_disturb_on Se requiere %s.'
			)
		);

        $this->form_validation->set_rules('Id_Cat_Empresa', 'Empresa', 'required',
			array(
					'required'	=> 'do_not_disturb_on Se requiere %s.'
			)
		);
        $this->form_validation->set_rules('Id_Cat_Departamento', 'Departamento', 'required',
			array(
					'required'	=> 'do_not_disturb_on Se requiere %s.'
			)
		);

        if ($this->form_validation->run() == TRUE) {
            if ($this->input->method() == 'post'){
                $data = array(
					'Descripcion'	=>  $this->input->post('Descripcion'),
					'Id_Cat_Departamento'	=>  $this->input->post('Id_Cat_Departamento'),
					'Id_Cat_Empresa'	=>  $this->input->post('Id_Cat_Empresa')
                );
                $error = $this->PerfilesModel->updatePerfil($id, $data);
                if ($error['code'] === 0){
                    $this->session->set_flashdata('msg', '
done_all Perfil registrado correctamente!
');
                    redirect(base_url(). 'Perfiles/');
                }else{
                    $this->session->set_flashdata('msg', '
do_not_disturb_on Error al registrar el Perfil!
');
                }
			}
		}

		$empresa_id = $this->PerfilesModel->getIDMaestro('Empresas');
		$depto_id = $this->PerfilesModel->getIDMaestro('Departamentos');
		$data['depto'] = $this->PerfilesModel->getDepto($depto_id['Id_Cat_Prim']);
		$data['empresa'] = $this->PerfilesModel->getEmpresa($empresa_id['Id_Cat_Prim']);

		$data['edicion'] = $this->PerfilesModel->getByIdPerfil($id);

		$this->load->view('perfiles/editPerfil.php', $data);
        $this->load->view('templates/footer.php');
	}

	public function delPerfil($id = NULL){
        $this->PerfilesModel->deletePerfil($id);
        $this->session->set_flashdata('msg', '
done_all Perfil borrado correctamente!
');
        redirect(base_url(). 'Perfiles/');
    }

	public function MenuPerfil(){
		$data['perfiles'] = $this->PerfilesModel->getPerfiles();
		$data['menus'] = $this->PerfilesModel->getMenusPerfiles();
        $this->load->view('templates/header.php');
        $this->load->view('perfiles/menuPerfil.php', $data);
        $this->load->view('templates/footer.php');
	}

	public function ColaboradorPerfil(){
        $config['base_url'] = base_url() . 'Perfiles/ColaboradorPerfil/';
        $config['total_rows'] = $this->PerfilesModel->countColaboradorPerfil();
        $config['per_page'] = 10;
        $config['uri_segment'] = 3;
        $config['num_links'] = 5;
        $config['prev_link'] = 'chevron_left';
        $config['prev_tag_open'] = '
';
        $config['prev_tag_close'] = '
';
        $config['next_link'] = 'chevron_right';
        $config['next_tag_open'] = '
';
        $config['next_tag_close'] = '
';
        $config['full_tag_open'] = '
';
        $config['full_tag_close'] = '
';
        $config['num_tag_open'] = '
';
        $config['num_tag_close'] = '
';
        $config['cur_tag_open'] = '
';
        $config['cur_tag_close'] = '
';

        $this->pagination->initialize($config);
        $result = $this->PerfilesModel->getAllColaboradorPerfil($config['per_page']);

		$data['perfiles'] = $this->PerfilesModel->getPerfil();
		$data['colaborador'] = $this->PerfilesModel->getColaborador();
		$data['pagination'] = $this->pagination->create_links();
        $data['consulta'] = $result;

        $this->load->view('templates/header.php');
        $this->load->view('perfiles/colaboradorPerfil.php', $data);
        $this->load->view('templates/footer.php');
	}

	public function newColaboradorPerfil(){
        $this->load->view('templates/header.php');

        $this->form_validation->set_error_delimiters('
', '
');
        $this->form_validation->set_rules('Id_Colaborador', 'Colaborador', 'required',
			array(
					'required'	=> 'do_not_disturb_on Se requiere %s.'
			)
		);
        $this->form_validation->set_rules('Id_Perfil', 'Perfil', 'required',
			array(
					'required'	=> 'do_not_disturb_on Se requiere %s.'
			)
		);
        $this->form_validation->set_rules('Activo', 'Activo', 'required',
			array(
					'required'	=> 'do_not_disturb_on Se requiere %s.'
			)
		);

        if ($this->form_validation->run() == TRUE) {
            if ($this->input->method() == 'post'){
                $data = array(
					'Id_Colaborador'	=>  $this->input->post('Id_Colaborador'),
                    'Id_Perfil'	=>  $this->input->post('Id_Perfil'),
					'Activo'	=>  $this->input->post('Activo')
                );
                $error = $this->PerfilesModel->addColaboradorPerfil($data);
                if ($error['code'] === 0){
                    $this->session->set_flashdata('msg', '
done_allAsignacion Colaborador > Perfil registrado correctamente!
');
                    redirect(base_url(). 'Perfiles/ColaboradorPerfil');
                }else{
                    $this->session->set_flashdata('msg', '
do_not_disturb_on Error al registrar la Asignacion Colaborador > Perfil!
');
                }
			}
		}
		$data['perfiles'] = $this->PerfilesModel->getPerfil();
		$data['colaborador'] = $this->PerfilesModel->getColaborador();
		$this->load->view('perfiles/newColaboradorPerfil.php', $data);
        $this->load->view('templates/footer.php');
	}

	public function editColaboradorPerfil($id){
        $this->load->view('templates/header.php');

        $this->form_validation->set_error_delimiters('
', '
');
        $this->form_validation->set_rules('Id_Colaborador', 'Colaborador', 'required',
			array(
					'required'	=> 'do_not_disturb_on Se requiere %s.'
			)
		);
        $this->form_validation->set_rules('Id_Perfil', 'Perfil', 'required',
			array(
					'required'	=> 'do_not_disturb_on Se requiere %s.'
			)
		);
        $this->form_validation->set_rules('Activo', 'Activo', 'required',
			array(
					'required'	=> 'do_not_disturb_on Se requiere %s.'
			)
		);

        if ($this->form_validation->run() == TRUE) {
            if ($this->input->method() == 'post'){
                $data = array(
					'Id_Colaborador'	=>  $this->input->post('Id_Colaborador'),
                    'Id_Perfil'	=>  $this->input->post('Id_Perfil'),
					'Activo'	=>  $this->input->post('Activo')
                );
                $error = $this->PerfilesModel->updateColaboradorPerfil($id, $data);
                if ($error['code'] === 0){
                    $this->session->set_flashdata('msg', '
done_allEditar Colaborador > Perfil registrado correctamente!
');
                    redirect(base_url(). 'Perfiles/ColaboradorPerfil');
                }else{
                    $this->session->set_flashdata('msg', '
do_not_disturb_on Error al registrar la Editar Colaborador > Perfil!
');
                }
			}
		}
		$data['perfiles'] = $this->PerfilesModel->getPerfil();
		$data['colaborador'] = $this->PerfilesModel->getColaborador();
		$data['edicion'] = $this->PerfilesModel->getByIdColaboradorPerfil($id);

		$this->load->view('perfiles/editColaboradorPerfil.php', $data);
        $this->load->view('templates/footer.php');
	}

	public function delColaboradorPerfil($id = NULL){
        $this->PerfilesModel->deleteColaboradorPerfil($id);
        $this->session->set_flashdata('msg', '
done_all Eliminar Colaborador > Perfil borrado correctamente!
');
        redirect(base_url(). 'Perfiles/ColaboradorPerfil');
    }

	public function getConfigPerfil(){
        if ($this->input->method() == 'post'){

			$menus = array();
				$raiz = $this->PerfilesModel->getMenus();
				$level1 = $this->PerfilesModel->getSubMenus($raiz->Id_Cat_Prim);
				foreach ($level1->result() as $row1) {
					$nombre_level1 = $row1->Nombre;
					$menus[$row1->Id_Cat_Prim] = $nombre_level1;
					$level2 = $this->PerfilesModel->getSubMenus($row1->Id_Cat_Prim);
					foreach ($level2->result() as $row2) {
						$nombre_level2 = $row2->Nombre;
						$menus[$row2->Id_Cat_Prim] = $nombre_level1 . " »» " . $nombre_level2;
						$level3 = $this->PerfilesModel->getSubMenus($row2->Id_Cat_Prim);
						foreach ($level3->result() as $row3) {
							$nombre_level3 = $row3->Nombre;
							$menus[$row3->Id_Cat_Prim] = $nombre_level1 . " »» " . $nombre_level2. " »» " . $nombre_level3;
						}
					}
				}

            #Recupera lo guardado
            $Id_Perfil = $this->input->post('Id_Perfil');
            $result = $this->PerfilesModel->getMenusSavePerfiles($Id_Perfil);

            foreach ($result->result() as $row){
                $select[] = array('Id_Cat_Prim' =>  $row->Id_Cat_Menu, 'Perfil' => ucwords($menus[$row->Id_Cat_Menu]));
            }

            if(isset($select)){
                echo json_encode($select);
            }
        }
	}

    public function savePerfil(){
        if ($this->input->method() == 'post'){
            $perfil = $this->input->post('perfil');
            $Id_Perfil = $this->input->post('Id_Perfil');

            #Borramos todo lo que existe
            $this->PerfilesModel->delConfigPerfil($Id_Perfil);

			if(count($perfil) > 0){
				foreach ($perfil as $valor) {
					$data[] = array(
						'Id_Perfil'   =>  $Id_Perfil,
						'Id_Cat_Menu'  =>  $valor
					);
				}
            #Guardamos todo lo nuevo
            $this->PerfilesModel->saveConfigPerfil($data);
			}
            echo "ok";
        }
    }

	public function loadSelectPerfil(){
		$raiz = $this->PerfilesModel->getMenus();
		$level1 = $this->PerfilesModel->getSubMenus($raiz->Id_Cat_Prim);
		foreach ($level1->result() as $row1) {
			$nombre_level1 = $row1->Nombre;
			echo '<option value="'. $row1->Id_Cat_Prim . '">'. $nombre_level1 . '</option>';
			$level2 = $this->PerfilesModel->getSubMenus($row1->Id_Cat_Prim);
			foreach ($level2->result() as $row2) {
				$nombre_level2 = $row2->Nombre;
				echo '<option value="' . $row2->Id_Cat_Prim .'">'. $nombre_level1 .' »» ' . $nombre_level2 .'</option>';
				$level3 = $this->PerfilesModel->getSubMenus($row2->Id_Cat_Prim);
				foreach ($level3->result() as $row3) {
					$nombre_level3 = $row3->Nombre;
					echo '<option value="' . $row3->Id_Cat_Prim . '">'. $nombre_level1 .' »» '. $nombre_level2 . '»»' . $nombre_level3 . '</option>';
				}
			}
		}
	}

}


text:
define([
  "../../extend",
  "../mExpression"
], function (extend, mExpression) {

  function String(_input, _pos, exp, operators) {
    // super class
    this.uber("STRING", 200, 1, _input, _pos);

    this.string = _input[this.pos].token;
    this.string = this.string.slice(1, this.string.length - 1);

    this.parent = exp;
    this.parent.args.push(this);
    this.args.push(this);

    this.pos++;
  }

  extend.call(String, mExpression);

  String.prototype.interpret = function (opts, callback) {

    var out = [ this.string.split("") ];
    callback(null, out);
  };

  return String;

});

redpajama_set_name: RedPajamaGithub


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.components.runtime;

import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.common.YaVersion;
import com.google.appinventor.components.runtime.collect.Lists;
import com.google.appinventor.components.runtime.errors.YailRuntimeError;
import com.google.appinventor.components.runtime.util.AsyncCallbackPair;
import com.google.appinventor.components.runtime.util.AsynchUtil;
import com.google.appinventor.components.runtime.util.GameInstance;
import com.google.appinventor.components.runtime.util.JsonUtil;
import com.google.appinventor.components.runtime.util.PlayerListDelta;
import com.google.appinventor.components.runtime.util.WebServiceUtil;
import com.google.appinventor.components.runtime.util.YailList;

import android.app.Activity;
import android.os.Handler;
import android.util.Log;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * GameClient provides a way for AppInventor applications to
 * communicate with online game servers. This allows users to create
 * games that are coordinated and managed in the cloud.
 *
 * Most communication is done by sending keyed messages back and
 * forth between the client and the server in the form of YailLists.
 * The server and game client can then switch on the keys and perform
 * more complex operations on the data. In addition, game servers can
 * implement a library of server commands that can perform complex
 * functions on the server and send back responses that are converted
 * into YailLists and sent back to the component. For more
 * information about server commands, consult the game server code
 * at http://code.google.com/p/app-inventor-for-android/
 *
 * Games instances are uniquely determined by a game id and an
 * instance id. In general, each App Inventor program should have
 * its own game id. Then, when running different instances of that
 * program, new instance ides should be used. Players are
 * represented uniquely by the email address registered to their
 * phones.
 *
 * All call functions perform POSTs to a web server. Upon successful
 * completion of these POST requests, FunctionCompleted will be
 * triggered with the function name as an argument. If the post
 * fails, WebServiceError will trigger with the function name and the
 * error message as arguments. These calls allow for application
 * creators to deal with web service failures and keep track of the
 * success or failure of their operations. The only exception to this
 * is when the return value from the server has the incorrect game id
 * or instance id. In this case, the response is completely ignored
 * and neither of these events will trigger.
 *
 *
 */
@DesignerComponent(version = YaVersion.GAMECLIENT_COMPONENT_VERSION,
    description = "Provides a way for applications to communicate with online game servers",
    category = ComponentCategory.INTERNAL, // moved to internal until fully tested
    nonVisible = true,
    iconName = "images/gameClient.png")
@SimpleObject
@UsesPermissions(
    permissionNames = "android.permission.INTERNET, " +
                "com.google.android.googleapps.permission.GOOGLE_AUTH")
public class GameClient extends AndroidNonvisibleComponent
    implements Component, OnResumeListener, OnStopListener {

  private static final String LOG_TAG = "GameClient";

  // Parameter keys
  private static final String GAME_ID_KEY = "gid";
  private static final String INSTANCE_ID_KEY = "iid";
  private static final String PLAYER_ID_KEY = "pid";
  private static final String INVITEE_KEY = "inv";
  private static final String LEADER_KEY = "leader";
  private static final String COUNT_KEY = "count";
  private static final String TYPE_KEY = "type";
  private static final String INSTANCE_PUBLIC_KEY = "makepublic";
  private static final String MESSAGE_RECIPIENTS_KEY = "mrec";
  private static final String MESSAGE_CONTENT_KEY = "contents";
  private static final String MESSAGE_TIME_KEY = "mtime";
  private static final String MESSAGE_SENDER_KEY = "msender";
  private static final String COMMAND_TYPE_KEY = "command";
  private static final String COMMAND_ARGUMENTS_KEY = "args";
  private static final String SERVER_RETURN_VALUE_KEY = "response";
  private static final String MESSAGES_LIST_KEY = "messages";
  private static final String ERROR_RESPONSE_KEY = "e";
  private static final String PUBLIC_LIST_KEY = "public";
  private static final String JOINED_LIST_KEY = "joined";
  private static final String INVITED_LIST_KEY = "invited";
  private static final String PLAYERS_LIST_KEY = "players";

  // Command keys
  private static final String GET_INSTANCE_LISTS_COMMAND = "getinstancelists";
  private static final String GET_MESSAGES_COMMAND = "messages";
  private static final String INVITE_COMMAND = "invite";
  private static final String JOIN_INSTANCE_COMMAND = "joininstance";
  private static final String LEAVE_INSTANCE_COMMAND = "leaveinstance";
  private static final String NEW_INSTANCE_COMMAND = "newinstance";
  private static final String NEW_MESSAGE_COMMAND = "newmessage";
  private static final String SERVER_COMMAND = "servercommand";
  private static final String SET_LEADER_COMMAND = "setleader";

  // URL for accessing the game server
  private String serviceUrl;
  private String gameId;
  private GameInstance instance;
  private Handler androidUIHandler;
  private Activity activityContext;

  private String userEmailAddress = "";

  // Game instances in the current GameId that this player has joined
  private List<String> joinedInstances;
  // Game instances to which this player has been invited
  private List<String> invitedInstances;
  // Game instances which have been made public.
  private List<String> publicInstances;

  /**
   * Creates a new GameClient component.
   *
   * @param container the Form that this component is contained in.
   */
  public GameClient(ComponentContainer container) {
    super(container.$form());
    // Note that although this is creating a new Handler there is
    // only one UI thread in an Android app and posting to this
    // handler queues up a Runnable for execution on that thread.
    androidUIHandler = new Handler();
    activityContext = container.$context();
    form.registerForOnResume(this);
    form.registerForOnStop(this);
    gameId = "";
    instance = new GameInstance("");
    joinedInstances = Lists.newArrayList();
    invitedInstances = Lists.newArrayList();
    publicInstances = Lists.newArrayList();
    serviceUrl = "http://appinvgameserver.appspot.com";

    // This needs to be done in a separate thread since it uses
    // a blocking service to complete and will cause the UI to hang
    // if it happens in the constructor.
    /*
     * Remove this code until we fix LoginServiceUtil to work in later
     * versions of the android SDK.
    AsynchUtil.runAsynchronously(new Runnable() {
      @Override
      public void run() {
        userEmailAddress = LoginServiceUtil.getPhoneEmailAddress(activityContext);
        if (!userEmailAddress.equals("")) {
          UserEmailAddressSet(userEmailAddress);
        }
      }
    });
    */
  }

  //----------------------------------------------------------------
  // Properties

  /**
   * Returns a string indicating the game name for this application.
   * The same game ID can have one or more game instances.
   */
  @SimpleProperty(
      description = "The game name for this application. " +
      "The same game ID can have one or more game instances.",
      category = PropertyCategory.BEHAVIOR)
  public String GameId() {
    return gameId;
  }

  /**
   * Specifies a string indicating the family of the current game
   * instance.  The same game ID can have one or more game instance
   * IDs.
   */
  // Only exposed in the designer to enforce that each GameClient
  // instance should be made for a single GameId.
  @DesignerProperty(
      editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
      defaultValue = "")
  public void GameId(String id) {
    this.gameId = id;
  }

  /**
   * Returns the game instance id.  Taken together, the game ID and
   * the instance ID uniquely identify the game.
   */
  @SimpleProperty(
      description = "The game instance id.  Taken together," +
      "the game ID and the instance ID uniquely identify the game.",
      category = PropertyCategory.BEHAVIOR)
  public String InstanceId() {
    return instance.getInstanceId();
  }

  /**
   * Returns the set of game instances to which this player has been
   * invited but has not yet joined.  To ensure current values are
   * returned, first invoke {@link #GetInstanceLists}.
   */
  @SimpleProperty(
      description = "The set of game instances to which this player has been " +
                    "invited but has not yet joined.  To ensure current values are " +
                    "returned, first invoke GetInstanceLists.",
      category = PropertyCategory.BEHAVIOR)
  public List<String> InvitedInstances() {
    return invitedInstances;
  }

  /**
   * Returns the set of game instances in which this player is
   * participating.  To ensure current values are returned, first
   * invoke {@link #GetInstanceLists}.
   */
  @SimpleProperty(
      description = "The set of game instances in which this player is " +
      "participating.  To ensure current values are returned, first " +
      "invoke GetInstanceLists.",
      category = PropertyCategory.BEHAVIOR)
  public List<String> JoinedInstances() {
    return joinedInstances;
  }

  /**
   * Returns the game's leader. At any time, each game instance has
   * only one leader, but the leader may change with time.
   * Initially, the leader is the game instance creator. Application
   * writers determine special properties of the leader. The leader
   * value is updated each time a successful communication is made
   * with the server.
   */
  @SimpleProperty(
      description = "The game's leader. At any time, each game instance has " +
      "only one leader, but the leader may change with time.  " +
      "Initially, the leader is the game instance creator. Application " +
      "writers determine special properties of the leader. The leader " +
      "value is updated each time a successful communication is made " +
      "with the server.",
      category = PropertyCategory.BEHAVIOR)
  public String Leader() {
    return instance.getLeader();
  }

  /**
   * Returns the current set of players for this game instance. Each
   * player is designated by an email address, which is a string. The
   * list of players is updated each time a successful communication
   * is made with the game server.
   */
  @SimpleProperty(
      description = "The current set of players for this game instance. Each " +
      "player is designated by an email address, which is a string. The " +
      "list of players is updated each time a successful communication " +
      "is made with the game server.",
      category = PropertyCategory.BEHAVIOR)
  public List<String> Players() {
    return instance.getPlayers();
  }

  /**
   * Returns the set of game instances that have been marked public.
   * To ensure current values are returned, first
   * invoke {@link #GetInstanceLists}.
   */
  @SimpleProperty(
      description = "The set of game instances that have been marked public. " +
      "To ensure current values are returned, first " +
      "invoke {@link #GetInstanceLists}. ",
      category = PropertyCategory.BEHAVIOR)
  public List<String> PublicInstances() {
    return publicInstances;
  }

  /**
   * The URL of the game server.
   */
  @SimpleProperty(
      description = "The URL of the game server.",
      category = PropertyCategory.BEHAVIOR)
  public String ServiceUrl() {
    return serviceUrl;
  }

  /**
   * Set the URL of the game server.
   *
   * @param url The URL (include initial http://).
   */
  @DesignerProperty(
      editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
      defaultValue = "http://appinvgameserver.appspot.com")
  @SimpleProperty(userVisible = false)
  public void ServiceURL(String url){
    if (url.endsWith("/")) {
      this.serviceUrl = url.substring(0, url.length() - 1);
    } else {
      this.serviceUrl = url;
    }
  }

  /**
   * Returns the registered email address that is being used as the
   * player id for this game client.
   */
  @SimpleProperty(
      description = "The email address that is being used as the " +
                    "player id for this game client.   At present, users " +
                    "must set this manually in oder to join a game.  But " +
                    "this property will change in the future so that is set " +
      "automatically, and users will not be able to change it.",
      category = PropertyCategory.BEHAVIOR)

  public String UserEmailAddress() {
    if (userEmailAddress.equals("")) {
      Info("User email address is empty.");
    }
    return userEmailAddress;
  }

  /**
   * Changes the player of this game by changing the email address
   * used to communicate with the server.
   *
   * This should only be used during development. Games should not
   * allow players to set their own email address.
   *
   * @param emailAddress The email address to set the current player
   * id to.
   */
  @SimpleProperty
  public void UserEmailAddress(String emailAddress) {
    userEmailAddress = emailAddress;
    UserEmailAddressSet(emailAddress);
  }

  //----------------------------------------------------------------
  // Event Handlers

  /**
   * Indicates that a server request from a function call has
   * completed. This can be used to control a polling loop or
   * otherwise respond to server request completions.
   *
   * @param functionName The name of the App Inventor function that
   * finished.
   */
  @SimpleEvent(description = "Indicates that a function call completed.")
  public void FunctionCompleted(final String functionName) {
    androidUIHandler.post(new Runnable() {
      public void run() {
        Log.d(LOG_TAG, "Request completed: " + functionName);
        EventDispatcher.dispatchEvent(GameClient.this, "FunctionCompleted", functionName);
      }});
  }

  /**
   * Ensures that the GameId was set by the game creator.
   */
  public void Initialize() {
    Log.d(LOG_TAG, "Initialize");
    if (gameId.equals("")) {
      throw new YailRuntimeError("Game Id must not be empty.", "GameClient Configuration Error.");
    }
  }

  /**
   * Indicates that a GetMessages call received a message. This could
   * be invoked multiple times for a single call to GetMessages.
   *
   * @param type The type of the message received.
   * @param contents The message's contents. Consists of a list
   * nested to arbitrary depth that includes string, boolean and
   * number values.
   */
  @SimpleEvent(description = "Indicates that a new message has " +
                "been received.")
  public void GotMessage(final String type, final String sender, final List<Object> contents) {
    Log.d(LOG_TAG, "Got message of type " + type);
    androidUIHandler.post(new Runnable() {
      public void run() {
        EventDispatcher.dispatchEvent(GameClient.this, "GotMessage", type, sender, contents);
      }});
  }

  /**
   * Indicates that InstanceId has changed due to the creation of a
   * new instance or setting the InstanceId.
   *
   * @param instanceId The id of the instance the player is now in.
   */
  @SimpleEvent(description = "Indicates that the InstanceId " +
                "property has changed as a result of calling " +
                "MakeNewInstance or SetInstance.")
  public void InstanceIdChanged(final String instanceId) {
    Log.d(LOG_TAG, "Instance id changed to " + instanceId);
    androidUIHandler.post(new Runnable() {
      public void run() {
        EventDispatcher.dispatchEvent(GameClient.this, "InstanceIdChanged", instanceId);
      }});
  }

  /**
   * Indicates a user has been invited to this game instance by
   * another player.
   *
   * @param instanceId The id of the new game instance.
   */
  @SimpleEvent(
      description = "Indicates that a user has been invited to " +
                "this game instance.")
  public void Invited(final String instanceId) {
    Log.d(LOG_TAG, "Player invited to " + instanceId);
    androidUIHandler.post(new Runnable() {
      public void run() {
        EventDispatcher.dispatchEvent(GameClient.this, "Invited", instanceId);
      }});
  }

  /**
   * Indicates this game instance has a new leader. This could happen
   * in response to a call to SetLeader or by the side effects of a
   * server command performed by any player in the game.
   *
   * Since the current leader is sent back with every server
   * response, NewLeader can trigger after making any server call.
   *
   * @param playerId The email address of the new leader.
   */
  @SimpleEvent(description = "Indicates that this game has a new " +
                "leader as specified through SetLeader")
  public void NewLeader(final String playerId) {
    androidUIHandler.post(new Runnable() {
      public void run() {
        Log.d(LOG_TAG, "Leader change to " + playerId);
        EventDispatcher.dispatchEvent(GameClient.this, "NewLeader", playerId);
      }});
  }

  /**
   * Indicates this game instance was created as specified via
   * MakeNewInstance. The creating player is automatically the leader
   * of the instance and the InstanceId property has already been set
   * to this new instance.
   *
   * @param instanceId The id of the newly created game instance.
   */
  @SimpleEvent(description = "Indicates that a new instance was " +
                "successfully created after calling MakeNewInstance.")
  public void NewInstanceMade(final String instanceId) {
    androidUIHandler.post(new Runnable() {
      public void run() {
        Log.d(LOG_TAG, "New instance made: " + instanceId);
        EventDispatcher.dispatchEvent(GameClient.this, "NewInstanceMade", instanceId);
      }});
  }

  /**
   * Indicates that a player has joined this game instance.
   *
   * @param playerId The email address of the new player.
   */
  @SimpleEvent(description = "Indicates that a new player has " +
                "joined this game instance.")
  public void PlayerJoined(final String playerId) {
    androidUIHandler.post(new Runnable() {
      public void run() {
        if (!playerId.equals(UserEmailAddress())) {
          Log.d(LOG_TAG, "Player joined: " + playerId);
          EventDispatcher.dispatchEvent(GameClient.this, "PlayerJoined", playerId);
        }
      }});
  }

  /**
   * Indicates that a player has left this game instance.
   *
   * @param playerId The email address of the player that left.
   */
  @SimpleEvent(description = "Indicates that a player has left " +
                "this game instance.")
  public void PlayerLeft(final String playerId) {
    androidUIHandler.post(new Runnable() {
      public void run() {
        Log.d(LOG_TAG, "Player left: " + playerId);
        EventDispatcher.dispatchEvent(GameClient.this, "PlayerLeft", playerId);
      }});
  }

  /**
   * Indicates that an attempt to complete a server command failed on
   * the server.
   * @param command The command requested.
   * @param arguments The arguments sent to the command.
   */
  @SimpleEvent(
      description = "Indicates that a server command failed.")
  public void ServerCommandFailure(final String command, final YailList arguments) {
    androidUIHandler.post(new Runnable() {
      public void run() {
        Log.d(LOG_TAG, "Server command failed: " + command);
        EventDispatcher.dispatchEvent(GameClient.this, "ServerCommandFailure", command, arguments);
      }});
  }

  /**
   * Indicates that a ServerCommand completed.
   *
   * @param command The key for the command that resulted in this
   * response.
   * @param response The server response. This consists of a list
   * nested to arbitrary depth that includes string, boolean and
   * number values.
   */
  @SimpleEvent(description = "Indicates that a server command " +
                "returned successfully.")
  public void ServerCommandSuccess(final String command, final List<Object> response) {
    Log.d(LOG_TAG, command + " server command returned.");
    androidUIHandler.post(new Runnable() {
      public void run() {
        EventDispatcher.dispatchEvent(GameClient.this,
            "ServerCommandSuccess", command, response);
      }});
  }

  /**
   * Indicates that the user email address property has been
   * successfully set. This event should be used to initialize
   * any web service functions.
   *
   * This separate event was required because the email address was
   * unable to be first fetched from the the UI thread without
   * causing programs to hang. GameClient will now start fetching
   * the user email address in its constructor and trigger this event
   * when it finishes.
   */
  @SimpleEvent(description = "Indicates that the user email " +
                "address has been set.")
  public void UserEmailAddressSet(final String emailAddress) {
    Log.d(LOG_TAG, "Email address set.");
    androidUIHandler.post(new Runnable() {
      public void run() {
        EventDispatcher.dispatchEvent(GameClient.this, "UserEmailAddressSet", emailAddress);
      }});
  }

  //----------------------------------------------------------------
  // Message events

  /**
   * Indicates that something has occurred which the player should be
   * somehow informed of.
   *
   * @param message the message.
   */
  @SimpleEvent(description = "Indicates that something has " +
                "occurred which the player should know about.")
  public void Info(final String message) {
    Log.d(LOG_TAG, "Info: " + message);
    androidUIHandler.post(new Runnable() {
      public void run() {
        EventDispatcher.dispatchEvent(GameClient.this, "Info", message);
      }});

  }

  /**
   * Indicates that the attempt to communicate with the web service
   * resulted in an error.
   *
   * @param functionName The name of the function call that caused this
   * error.
   * @param message the error message
   */
  @SimpleEvent(description = "Indicates that an error occurred " +
                "while communicating with the web server.")
  public void WebServiceError(final String functionName, final String message) {
    Log.e(LOG_TAG, "WebServiceError: " + message);
    androidUIHandler.post(new Runnable() {
      public void run() {
        EventDispatcher.dispatchEvent(GameClient.this, "WebServiceError", functionName, message);
      }});
  }

  //----------------------------------------------------------------
  // Functions

  /**
   * Updates the current InstancesJoined and InstancesInvited lists.
   *
   * If the player has been invited to new instances an Invited
   * event will be raised for each new instance.
   */
  @SimpleFunction(description = "Updates the InstancesJoined and " +
                "InstancesInvited lists. This procedure can be called " +
                "before setting the InstanceId.")
  public void GetInstanceLists() {
    AsynchUtil.runAsynchronously(new Runnable() {
        public void run() { postGetInstanceLists(); }});
  }

  private void postGetInstanceLists() {
    AsyncCallbackPair<JSONObject> readMessagesCallback = new AsyncCallbackPair<JSONObject>(){
      public void onSuccess(final JSONObject response) {
        processInstanceLists(response);
        FunctionCompleted("GetInstanceLists");
      }
      public void onFailure(final String message) {
        WebServiceError("GetInstanceLists", "Failed to get up to date instance lists.");
      }
    };

    postCommandToGameServer(GET_INSTANCE_LISTS_COMMAND,
        Lists.<NameValuePair>newArrayList(
            new BasicNameValuePair(GAME_ID_KEY, GameId()),
            new BasicNameValuePair(INSTANCE_ID_KEY, InstanceId()),
            new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress())),
        readMessagesCallback);
  }

  private void processInstanceLists(JSONObject instanceLists){
    try {
      joinedInstances = JsonUtil.getStringListFromJsonArray(instanceLists.
          getJSONArray(JOINED_LIST_KEY));

      publicInstances = JsonUtil.getStringListFromJsonArray(instanceLists.
          getJSONArray(PUBLIC_LIST_KEY));

      List<String> receivedInstancesInvited = JsonUtil.getStringListFromJsonArray(instanceLists.
          getJSONArray(INVITED_LIST_KEY));

      if (!receivedInstancesInvited.equals(InvitedInstances())) {
        List<String> oldList = invitedInstances;
        invitedInstances = receivedInstancesInvited;
        List<String> newInvites = new ArrayList<String>(receivedInstancesInvited);
        newInvites.removeAll(oldList);

        for (final String instanceInvited : newInvites) {
          Invited(instanceInvited);
        }
      }

    } catch (JSONException e) {
      Log.w(LOG_TAG, e);
      Info("Instance lists failed to parse.");
    }
  }

  /**
   * Retrieves messages of the specified type.
   *
   * Requests that only messages which have not been seen during
   * the current session are returned. Messages will be processed
   * in chronological order with the oldest first, however, only
   * the count newest messages will be retrieved. This means that
   * one could "miss out" on some messages if they request less than
   * the number of messages created since the last request for
   * that message type.
   *
   * Setting type to the empty string will fetch all message types.
   * Even though those message types were not specifically requested,
   * their most recent message time will be updated. This keeps
   * players from receiving the same message again if they later
   * request the specific message type.
   *
   * Note that the message receive times are not updated until after
   * the messages are actually received. Thus, if multiple message
   * requests are made before the previous ones return, they could
   * send stale time values and thus receive the same messages more
   * than once. To avoid this, application creators should wait for
   * the get messages function to return before calling it again.
   *
   * @param type The type of message to retrieve. If the empty string
   * is used as the message type then all message types will be
   * requested.
   * @param count The maximum number of messages to retrieve. This
   * should be an integer from 1 to 1000.
   */
  @SimpleFunction(
      description = "Retrieves messages of the specified type.")
  public void GetMessages(final String type, final int count) {
    AsynchUtil.runAsynchronously(new Runnable() {
      public void run() { postGetMessages(type, count); }});
  }

  private void postGetMessages(final String requestedType, final int count) {
    AsyncCallbackPair<JSONObject> myCallback = new AsyncCallbackPair<JSONObject>() {
      public void onSuccess(final JSONObject result) {
        try {
          int count = result.getInt(COUNT_KEY);
          JSONArray messages = result.getJSONArray(MESSAGES_LIST_KEY);
          for (int i = 0; i < count; i++) {
            JSONObject message = messages.getJSONObject(i);
            String type = message.getString(TYPE_KEY);
            String sender = message.getString(MESSAGE_SENDER_KEY);
            String time = message.getString(MESSAGE_TIME_KEY);
            List<Object> contents = JsonUtil.getListFromJsonArray(message.
                getJSONArray(MESSAGE_CONTENT_KEY), true);
            // Assumes that the server is going to return messages in
            // chronological order.
            if (requestedType.equals("")) {
              instance.putMessageTime(requestedType, time);
            }
            instance.putMessageTime(type, time);
            GotMessage(type, sender, contents);
          }
        } catch (JSONException e) {
          Log.w(LOG_TAG, e);
          Info("Failed to parse messages response.");
        }
        FunctionCompleted("GetMessages");
      }

      public void onFailure(String message) {
        WebServiceError("GetMessages", message);
      }
    };

    if (InstanceId().equals("")) {
      Info("You must join an instance before attempting to fetch messages.");
      return;
    }

    postCommandToGameServer(GET_MESSAGES_COMMAND,
        Lists.<NameValuePair>newArrayList(
            new BasicNameValuePair(GAME_ID_KEY, GameId()),
            new BasicNameValuePair(INSTANCE_ID_KEY, InstanceId()),
            new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress()),
            new BasicNameValuePair(COUNT_KEY, Integer.toString(count)),
            new BasicNameValuePair(MESSAGE_TIME_KEY, instance.getMessageTime(requestedType)),
            new BasicNameValuePair(TYPE_KEY, requestedType)),
        myCallback);
  }

  /**
   * Invites a player to this game instance.
   *
   * Players implicitly accept invitations when they join games by
   * setting the instance id in their GameClient.
   *
   * Invitations remain active as long as the game instance exists.
   *
   * @param playerEmail a string containing the email address of the
   * player to become leader. The email should be in one of the
   * following formats:<br>"Name O. Person
   * &ltname.o.person@gmail.com&gt"<br>"name.o.person@gmail.com".
   */
  @SimpleFunction(
      description = "Invites a player to this game instance.")
  public void Invite(final String playerEmail) {
    AsynchUtil.runAsynchronously(new Runnable() {
      public void run() { postInvite(playerEmail); }});
  }

  private void postInvite(final String inviteeEmail) {
    AsyncCallbackPair<JSONObject> inviteCallback = new AsyncCallbackPair<JSONObject>(){
      public void onSuccess(final JSONObject response) {
        try {
          String invitedPlayer = response.getString(INVITEE_KEY);

          if (invitedPlayer.equals("")) {
            Info(invitedPlayer + " was already invited.");
          } else {
            Info("Successfully invited " + invitedPlayer + ".");
          }
        } catch (JSONException e) {
          Log.w(LOG_TAG, e);
          Info("Failed to parse invite player response.");
        }
        FunctionCompleted("Invite");
      }
      public void onFailure(final String message) {
        WebServiceError("Invite", message);
      }
    };

    if (InstanceId().equals("")) {
      Info("You must have joined an instance before you can invite new players.");
      return;
    }

    postCommandToGameServer(INVITE_COMMAND,
        Lists.<NameValuePair>newArrayList(
            new BasicNameValuePair(GAME_ID_KEY, GameId()),
            new BasicNameValuePair(INSTANCE_ID_KEY, InstanceId()),
            new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress()),
            new BasicNameValuePair(INVITEE_KEY, inviteeEmail)),
        inviteCallback);
  }

  /**
   * Requests to leave the current instance. If the player is the
   * current leader, the lead will be passed to another player.
   *
   * If there are no other players left in the instance after the
   * current player leaves, the instance will become unjoinable.
   *
   * Upon successful completion of this command, the instance
   * lists will be updated and InstanceId will be set back to the
   * empty string.
   *
   * Note that while this call does clear the leader and player
   * lists, no NewLeader or PlayerLeft events are raised.
   */
  @SimpleFunction(description = "Leaves the current instance.")
  public void LeaveInstance() {
    AsynchUtil.runAsynchronously(new Runnable() {
      public void run() {
        postLeaveInstance();
      }
    });
  }

  private void postLeaveInstance() {
    AsyncCallbackPair<JSONObject> setInstanceCallback = new AsyncCallbackPair<JSONObject>(){
      public void onSuccess(final JSONObject response) {
        SetInstance("");
        processInstanceLists(response);
        FunctionCompleted("LeaveInstance");
      }
      public void onFailure(final String message) {
        WebServiceError("LeaveInstance", message);
      }
    };

    postCommandToGameServer(LEAVE_INSTANCE_COMMAND,
        Lists.<NameValuePair>newArrayList(
            new BasicNameValuePair(GAME_ID_KEY, GameId()),
            new BasicNameValuePair(INSTANCE_ID_KEY, InstanceId()),
            new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress())),
            setInstanceCallback);
  }

  /**
   * Creates a new game instance.  The instance has a unique
   * instanceId, and the leader is the player who created it. The
   * player that creates the game automatically joins it without
   * being sent an invitation.
   *
   * The actual instance id could differ from the instanceId
   * specified because the game server will enforce uniqueness. The
   * actual instanceId will be provided to AppInventor when a
   * NewInstanceMade event triggers upon successful completion of
   * this server request.
   *
   * @param instanceId A string to use as for the instance
   * id. If no other instance exists with this id, the new instance
   * will have this id. However, since the id must be unique, if
   * another instance exists with the same one, then a number
   * will be appended to the end of this prefix.
   * @param makePublic A boolean indicating whether or not the
   * instance should be publicly viewable and able to be joined by
   * anyone.
   */
  @SimpleFunction(description = "Asks the server to create a new " +
                "instance of this game.")
  public void MakeNewInstance(final String instanceId, final boolean makePublic) {
    AsynchUtil.runAsynchronously(new Runnable() {
      public void run() { postMakeNewInstance(instanceId, makePublic); }});
  }

  private void postMakeNewInstance(final String requestedInstanceId, final Boolean makePublic) {
    AsyncCallbackPair<JSONObject> makeNewGameCallback = new AsyncCallbackPair<JSONObject>(){
      public void onSuccess(final JSONObject response) {
        processInstanceLists(response);
        NewInstanceMade(InstanceId());
        FunctionCompleted("MakeNewInstance");
      }
      public void onFailure(final String message) {
        WebServiceError("MakeNewInstance", message);
      }
    };

    postCommandToGameServer(NEW_INSTANCE_COMMAND,
        Lists.<NameValuePair>newArrayList(
            new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress()),
            new BasicNameValuePair(GAME_ID_KEY, GameId()),
            new BasicNameValuePair(INSTANCE_ID_KEY, requestedInstanceId),
            new BasicNameValuePair(INSTANCE_PUBLIC_KEY, makePublic.toString())),
            makeNewGameCallback, true);
  }

  /**
   * Creates a new message and sends it to the stated recipients.
   *
   * @param type A "key" for the message. This identifies the type of
   * message so that when other players receive the message they know
   * how to properly handle it.
   * @param recipients If set to an empty list, the server will send
   * this message with a blank set of recipients, meaning that all
   * players in the instance are able to retrieve it. To limit the
   * message receipt to a single person or a group of people,
   * recipients should be a list of the email addresses of the people
   * meant to receive the message. Each email should be in one of the
   * following formats:<br>
   * "Name O. Person &ltname.o.person@gmail.com&gt"<br>
   * "name.o.person@gmail.com"
   * @param contents the contents of the message. This can be any
   * AppInventor data value.
   */
  @SimpleFunction(description = "Sends a keyed message to all " +
                "recipients in the recipients list. The message will " +
                "consist of the contents list.")
  public void SendMessage(final String type, final YailList recipients, final YailList contents) {
    AsynchUtil.runAsynchronously(new Runnable() {
      public void run() { postNewMessage(type, recipients, contents); }});
  }

  private void postNewMessage(final String type, YailList recipients, YailList contents){
    AsyncCallbackPair<JSONObject> myCallback = new AsyncCallbackPair<JSONObject>(){
      public void onSuccess(final JSONObject response) {
        FunctionCompleted("SendMessage");
      }
      public void onFailure(final String message) {
        WebServiceError("SendMessage", message);
      }
    };

    if (InstanceId().equals("")) {
      Info("You must have joined an instance before you can send messages.");
      return;
    }

    postCommandToGameServer(NEW_MESSAGE_COMMAND,
        Lists.<NameValuePair>newArrayList(
            new BasicNameValuePair(GAME_ID_KEY, GameId()),
            new BasicNameValuePair(INSTANCE_ID_KEY, InstanceId()),
            new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress()),
            new BasicNameValuePair(TYPE_KEY, type),
            new BasicNameValuePair(MESSAGE_RECIPIENTS_KEY, recipients.toJSONString()),
            new BasicNameValuePair(MESSAGE_CONTENT_KEY, contents.toJSONString()),
            new BasicNameValuePair(MESSAGE_TIME_KEY, instance.getMessageTime(type))),
        myCallback);
  }

  /**
   * Submits a command to the game server. Server commands are
   * custom actions that are performed on the server. The arguments
   * required and return value of a server command depend on its
   * implementation.
   *
   * For more information about server commands, consult the game
   * server code at:
   * http://code.google.com/p/app-inventor-for-android/
   *
   * @param command The name of the server command.
   * @param arguments The arguments to pass to the server to specify
   * how to execute the command.
   */
  @SimpleFunction(description = "Sends the specified command to " +
                "the game server.")
  public void ServerCommand(final String command, final YailList arguments) {
    AsynchUtil.runAsynchronously(new Runnable() {
      public void run() { postServerCommand(command, arguments); }});
  }

  private void postServerCommand(final String command, final YailList arguments){
    AsyncCallbackPair<JSONObject> myCallback = new AsyncCallbackPair<JSONObject>() {
      public void onSuccess(final JSONObject result) {
        try {
          ServerCommandSuccess(command, JsonUtil.getListFromJsonArray(result.
              getJSONArray(MESSAGE_CONTENT_KEY), true));
        } catch (JSONException e) {
          Log.w(LOG_TAG, e);
          Info("Server command response failed to parse.");
        }
        FunctionCompleted("ServerCommand");
      }

      public void onFailure(String message) {
        ServerCommandFailure(command, arguments);
        WebServiceError("ServerCommand", message);
      }
    };

    Log.d(LOG_TAG, "Going to post " + command + " with args " + arguments);
    postCommandToGameServer(SERVER_COMMAND,
        Lists.<NameValuePair>newArrayList(
            new BasicNameValuePair(GAME_ID_KEY, GameId()),
            new BasicNameValuePair(INSTANCE_ID_KEY, InstanceId()),
            new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress()),
            new BasicNameValuePair(COMMAND_TYPE_KEY, command),
            new BasicNameValuePair(COMMAND_ARGUMENTS_KEY, arguments.toJSONString())),
        myCallback);
  }

  /**
   * Specifies the game instance id.  Taken together, the game ID and
   * the instance ID uniquely identify the game.
   *
   * @param instanceId the name of the game instance to join.
   */
  @SimpleFunction(description = "Sets InstanceId and joins the " +
                "specified instance.")
  public void SetInstance(final String instanceId) {
    AsynchUtil.runAsynchronously(new Runnable() {
      public void run() {
        if (instanceId.equals("")) {
          Log.d(LOG_TAG, "Instance id set to empty string.");
          if (!InstanceId().equals("")) {
            instance = new GameInstance("");
            InstanceIdChanged("");
            FunctionCompleted("SetInstance");
          }
        } else {
          postSetInstance(instanceId);
        }
      }
    });
  }

  private void postSetInstance(String instanceId) {
    AsyncCallbackPair<JSONObject> setInstanceCallback = new AsyncCallbackPair<JSONObject>(){
      public void onSuccess(final JSONObject response) {
        processInstanceLists(response);
        FunctionCompleted("SetInstance");
      }
      public void onFailure(final String message) {
        WebServiceError("SetInstance", message);
      }
    };

    postCommandToGameServer(JOIN_INSTANCE_COMMAND,
        Lists.<NameValuePair>newArrayList(
            new BasicNameValuePair(GAME_ID_KEY, GameId()),
            new BasicNameValuePair(INSTANCE_ID_KEY, instanceId),
            new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress())),
            setInstanceCallback, true);
  }

  /**
   * Specifies the game's leader. At any time, each game instance
   * has only one leader, but the leader may change over time.
   * Initially, the leader is the game instance creator. Application
   * inventors determine special properties of the leader.
   *
   * The leader can only be set by the current leader of the game.
   *
   * @param playerEmail a string containing the email address of the
   * player to become leader. The email should be in one of the
   * following formats:
   * <br>"Name O. Person &ltname.o.person@gmail.com&gt"
   * <br>"name.o.person@gmail.com".
   */
  @SimpleFunction(description = "Tells the server to set the " +
                "leader to playerId. Only the current leader may " +
                "successfully set a new leader.")
  public void SetLeader(final String playerEmail) {
    AsynchUtil.runAsynchronously(new Runnable() {
      public void run() { postSetLeader(playerEmail); }});
  }

  private void postSetLeader(final String newLeader) {
    AsyncCallbackPair<JSONObject> setLeaderCallback = new AsyncCallbackPair<JSONObject>(){
      public void onSuccess(final JSONObject response) {
        FunctionCompleted("SetLeader");
      }
      public void onFailure(final String message) {
        WebServiceError("SetLeader", message);
      }
    };

    if (InstanceId().equals("")) {
      Info("You must join an instance before attempting to set a leader.");
      return;
    }

    postCommandToGameServer(SET_LEADER_COMMAND,
        Lists.<NameValuePair>newArrayList(
            new BasicNameValuePair(GAME_ID_KEY, GameId()),
            new BasicNameValuePair(INSTANCE_ID_KEY, InstanceId()),
            new BasicNameValuePair(PLAYER_ID_KEY, UserEmailAddress()),
            new BasicNameValuePair(LEADER_KEY, newLeader)),
            setLeaderCallback);
  }

  //----------------------------------------------------------------
  // Activity Lifecycle Management

  /**
   * Called automatically by the operating system.
   *
   * Currently does nothing.
   */
  public void onResume() {
    Log.d(LOG_TAG, "Activity Resumed.");
  }

  /**
   * Called automatically by the operating system.
   *
   * Currently does nothing.
   */
  public void onStop() {
    Log.d(LOG_TAG, "Activity Stopped.");
  }

  //----------------------------------------------------------------
  // Utility Methods

  private void postCommandToGameServer(final String commandName,
      List<NameValuePair> params, final AsyncCallbackPair<JSONObject> callback) {
    postCommandToGameServer(commandName, params, callback, false);
  }

  private void postCommandToGameServer(final String commandName,
      final List<NameValuePair> params, final AsyncCallbackPair<JSONObject> callback,
      final boolean allowInstanceIdChange) {
    AsyncCallbackPair<JSONObject> thisCallback = new AsyncCallbackPair<JSONObject>() {
      public void onSuccess(JSONObject responseObject) {
        Log.d(LOG_TAG, "Received response for " + commandName + ": " + responseObject.toString());

        try {
          if (responseObject.getBoolean(ERROR_RESPONSE_KEY)) {
            callback.onFailure(responseObject.getString(SERVER_RETURN_VALUE_KEY));
          } else {
            String responseGameId = responseObject.getString(GAME_ID_KEY);
            if (!responseGameId.equals(GameId())) {
              Info("Incorrect game id in response: + " + responseGameId + ".");
              return;
            }
            String responseInstanceId = responseObject.getString(INSTANCE_ID_KEY);
            if (responseInstanceId.equals("")) {
              callback.onSuccess(responseObject.getJSONObject(SERVER_RETURN_VALUE_KEY));
              return;
            }

            if (responseInstanceId.equals(InstanceId())) {
              updateInstanceInfo(responseObject);
            } else {
              if (allowInstanceIdChange || InstanceId().equals("")) {
                instance = new GameInstance(responseInstanceId);
                updateInstanceInfo(responseObject);
                InstanceIdChanged(responseInstanceId);
              } else {
                Info("Ignored server response to " + commandName + " for incorrect instance " +
                    responseInstanceId + ".");
                return;
              }
            }
            callback.onSuccess(responseObject.getJSONObject(SERVER_RETURN_VALUE_KEY));
          }
        } catch (JSONException e) {
          Log.w(LOG_TAG, e);
          callback.onFailure("Failed to parse JSON response to command " + commandName);
        }
      }
      public void onFailure(String failureMessage) {
        Log.d(LOG_TAG, "Posting to server failed for " + commandName + " with arguments " +
            params + "\n Failure message: " +  failureMessage);
        callback.onFailure(failureMessage);
      }
    };

    WebServiceUtil.getInstance().postCommandReturningObject(ServiceUrl(), commandName, params,
        thisCallback);
  }

  private void updateInstanceInfo(JSONObject responseObject) throws JSONException {
    boolean newLeader = false;
    String leader = responseObject.getString(LEADER_KEY);
    List<String> receivedPlayers = JsonUtil.getStringListFromJsonArray(responseObject.
        getJSONArray(PLAYERS_LIST_KEY));

    if (!Leader().equals(leader)) {
      instance.setLeader(leader);
      newLeader = true;
    }

    PlayerListDelta playersDelta = instance.setPlayers(receivedPlayers);
    if (playersDelta != PlayerListDelta.NO_CHANGE) {
      for (final String player : playersDelta.getPlayersRemoved()) {
        PlayerLeft(player);
      }
      for (final String player : playersDelta.getPlayersAdded()) {
        PlayerJoined(player);
      }
    }

    if (newLeader) {
      NewLeader(Leader());
    }
  }
}


text:
@extends('layouts.master')

@section('title')
    {{ trans('user::users.title.users') }}
@endsection
@section('subTitle')
    {{trans('core::elements.action.edit resource', ['name'=>trans('user::users.title.user')])}}
@endsection

@section('content')
    <form class="ui form" role="form" method="POST" action="{{route('backend::user.user.update', $user->id)}}">
        <input type="hidden" name="_method" value="PUT">
        {!! csrf_field() !!}

            {{ trans('user::users.tabs.user') }}
            {{ trans('user::users.tabs.profile') }}
            {{ trans('user::users.tabs.roles') }}
            {{ trans('user::users.tabs.reset password') }}

            @include('user::backend.users.partials.userTab')

            @include('user::backend.users.partials.profileTab')

            @include('user::backend.users.partials.rolesTab')

            @include('user::backend.users.partials.resetPasswordTab')

                {{ trans('core::elements.button.cancel') }}

            <button class="ui primary right floated button" type="submit">
                {{ trans('core::elements.button.update') }}
            </button>

    </form>

@endsection

@section('javascript')

@endsection


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Whole Cell Simulation: src/+edu/+stanford/+covert/+cell/+sim/+state/Stimulus.m Source File</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

Whole Cell Simulation

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

src/+edu/+stanford/+covert/+cell/+sim/+state/Stimulus.m

Go to the documentation of this file.

00001 %Stimulus
00002 %
00003 % Author: Jonathan Karr, jkarr@stanford.edu
00004 % Affiliation: Covert Lab, Department of Bioengineering, Stanford University
00005 % Last Updated: 1/5/2011
00006 classdef Stimulus < edu.stanford.covert.cell.sim.CellState
00007     %Constants
00008     properties (Constant)
00009         optionNames             = {   %names of properties that are options
00010             'verbosity';
00011             'seed';
00012             };
00013         fixedConstantNames      = {}; %names of process properties that are considered fixed constants
00014         fittedConstantNames     = {}; %names of process properties that are considered fitted constants, and should be stored with the simulation as such
00015         stateNames              = {   %names of properties which are part of the simulation's state
00016             'values'};
00017         dependentStateNames     = {}; %names of properties which can be calculated from the simulation's state
00018     end
00019
00020     %constants
00021     properties
00022         wholeCellModelIDs
00023         names
00024         setValues
00025
00026         compartment
00027     end
00028
00029     %state
00030     properties
00031         values
00032     end
00033
00034     %alternative interface to state
00035     properties (Constant)
00036         dryWeight = 0
00037     end
00038
00039     %constructor
00040     methods
00041         function this = Stimulus(wholeCellModelID, name)
00042             this = this@edu.stanford.covert.cell.sim.CellState(wholeCellModelID, name);
00043         end
00044     end
00045
00046     methods
00047         function storeObjectReferences(this, simulation)
00048             this.compartment = simulation.compartment;
00049         end
00050
00051         function initializeConstants(this, knowledgeBase, simulation)
00052             import edu.stanford.covert.cell.sim.constant.Condition;
00053
00054             this.initializeConstants@edu.stanford.covert.cell.sim.CellState(knowledgeBase, simulation);
00055
00056             this.wholeCellModelIDs  = {knowledgeBase.stimulis.wholeCellModelID}';
00057             this.names  = {knowledgeBase.stimulis.name}';
00058             this.setValues = zeros(0, 6);
00059
00060             for i = 1:knowledgeBase.numStimulis
00061                 value = zeros(length(knowledgeBase.stimulis(i).compartments), 6);
00062                 value(:, Condition.objectIndexs)      = knowledgeBase.stimulis(i).idx;
00063                 value(:, Condition.compartmentIndexs) = [knowledgeBase.stimulis(i).compartments.idx];
00064                 value(:, Condition.valueIndexs)       = knowledgeBase.stimulis(i).values;
00065                 value(:, Condition.initialTimeIndexs) = knowledgeBase.stimulis(i).initialTimes;
00066                 value(:, Condition.finalTimeIndexs)   = knowledgeBase.stimulis(i).finalTimes;
00067                 value(:, Condition.objectCompartmentIndexs) = sub2ind(...
00068                     [knowledgeBase.numStimulis knowledgeBase.numCompartments],...
00069                     value(:, Condition.objectIndexs),...
00070                     value(:, Condition.compartmentIndexs));
00071
00072                 this.setValues = [this.setValues; value];
00073             end
00074         end
00075
00076         %allocate memory for state
00077         function allocateMemory(this, numTimePoints)
00078             this.values = zeros([numel(this.wholeCellModelIDs), this.compartment.count, numTimePoints]);
00079         end
00080
00081         %initialize state
00082         function initialize(this)
00083             this.allocateMemory(1);
00084         end
00085     end
00086
00087     %helper methods
00088     methods
00089         function value = getIndexs(this, wholeCellModelIDs)
00090             [~, value] = ismember(wholeCellModelIDs, this.wholeCellModelIDs);
00091         end
00092     end
00093 end

 All Classes Files Functions Variables

Stimulus.m

Generated on Wed Feb 8 2012 21:42:32 for Whole Cell Simulation by

     1.7.6.1


text:
template <typename R>
struct range_reference {
	typedef typename boost::range_iterator<R>::type iter;
	typedef typename iter::reference type;
};

template <typename... Rs>
struct value_type {
	typedef std::tuple<
		typename range_reference<Rs>::type...
	> type;
};

template <size_t N>
using const_int = std::integral_constant<size_t, N>;

template <typename... Rs>
class cartesian_iterator : public boost::iterator_facade<
	cartesian_iterator<Rs...>,  // pass self per CRTP
	typename value_type<Rs...>::type,  // value_type
	boost::forward_traversal_tag,  // iterator category
	typename value_type<Rs...>::type  // reference -- same as value_type!
>
{
	std::tuple<typename boost::range_iterator<Rs>::type... > iters;
	std::tuple<Rs&...> ranges;

public:
	cartesian_iterator() {}

	cartesian_iterator(Rs&... rs) : ranges(rs...), iters(boost::begin(rs)...)
	{
	}

	cartesian_iterator(Rs&... rs, int) :
		ranges(rs...),
		iters(boost::end(rs)...)
	{
	}

	void increment() {
		increment(const_int<sizeof...(Rs) - 1>());
	}

	bool equal(cartesian_iterator const& other ) const { return iters == other.iters; }

	typename value_type<Rs...>::type dereference() const {
		return dereference(tuple_indices(iters));
	}

private:
	template <size_t N>
	bool increment(const_int<N>) {
		if( ++(std::get<N>(iters)) == boost::end(std::get<N>(ranges)) ) {
			if( !increment(const_int<N-1>()) )
				return false;
			std::get<N>(iters) = boost::begin(std::get<N>(ranges));
		}
		return true;
	}

	bool increment(const_int<0>) {
		return ++(std::get<0>(iters)) != boost::end(std::get<0>(ranges));
	}

	template <size_t... Indices>
	typename value_type<Rs...>::type dereference(seq<Indices...>) const {
		typedef typename value_type<Rs...>::type result_t;
		return result_t(*std::get<Indices>(iters)...);
	}
};

template <typename... Rs>
using cartesian_range = boost::iterator_range<cartesian_iterator<Rs...>>;

template <typename... Rs>
typename cartesian_range<Rs...>::type cartesian(Rs&... rs) {
	typedef cartesian_iterator<Rs...> iter_t;
	return cartesian_range<Rs...>(iter_t(rs...), iter_t(rs..., 0));
}


text:
package org.elasticsearch.search.aggregations;

import org.elasticsearch.common.CheckedBiConsumer;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentParserUtils;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken;

public abstract class ParsedMultiBucketAggregation<B extends ParsedMultiBucketAggregation.Bucket>
        extends ParsedAggregation implements MultiBucketsAggregation {

    protected final List<B> buckets = new ArrayList<>();
    protected boolean keyed = false;

    @Override
    protected XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
        if (keyed) {
            builder.startObject(CommonFields.BUCKETS.getPreferredName());
        } else {
            builder.startArray(CommonFields.BUCKETS.getPreferredName());
        }
        for (B bucket : buckets) {
            bucket.toXContent(builder, params);
        }
        if (keyed) {
            builder.endObject();
        } else {
            builder.endArray();
        }
        return builder;
    }

    protected static void declareMultiBucketAggregationFields(final ObjectParser<? extends ParsedMultiBucketAggregation, Void> objectParser,
                                                  final CheckedFunction<XContentParser, ParsedBucket, IOException> bucketParser,
                                                  final CheckedFunction<XContentParser, ParsedBucket, IOException> keyedBucketParser) {
        declareAggregationFields(objectParser);
        objectParser.declareField((parser, aggregation, context) -> {
            XContentParser.Token token = parser.currentToken();
            if (token == XContentParser.Token.START_OBJECT) {
                aggregation.keyed = true;
                while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
                    aggregation.buckets.add(keyedBucketParser.apply(parser));
                }
            } else if (token == XContentParser.Token.START_ARRAY) {
                aggregation.keyed = false;
                while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
                    aggregation.buckets.add(bucketParser.apply(parser));
                }
            }
        }, CommonFields.BUCKETS, ObjectParser.ValueType.OBJECT_ARRAY);
    }

    public abstract static class ParsedBucket implements MultiBucketsAggregation.Bucket {

        private Aggregations aggregations;
        private String keyAsString;
        private long docCount;
        private boolean keyed;

        protected void setKeyAsString(String keyAsString) {
            this.keyAsString = keyAsString;
        }

        @Override
        public String getKeyAsString() {
            return keyAsString;
        }

        protected void setDocCount(long docCount) {
            this.docCount = docCount;
        }

        @Override
        public long getDocCount() {
            return docCount;
        }

        public void setKeyed(boolean keyed) {
            this.keyed = keyed;
        }

        protected boolean isKeyed() {
            return keyed;
        }

        protected void setAggregations(Aggregations aggregations) {
            this.aggregations = aggregations;
        }

        @Override
        public Aggregations getAggregations() {
            return aggregations;
        }

        @Override
        public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
            if (keyed) {
                // Subclasses can override the getKeyAsString method to handle specific cases like
                // keyed bucket with RAW doc value format where the key_as_string field is not printed
                // out but we still need to have a string version of the key to use as the bucket's name.
                builder.startObject(getKeyAsString());
            } else {
                builder.startObject();
            }
            if (keyAsString != null) {
                builder.field(CommonFields.KEY_AS_STRING.getPreferredName(), getKeyAsString());
            }
            keyToXContent(builder);
            builder.field(CommonFields.DOC_COUNT.getPreferredName(), docCount);
            aggregations.toXContentInternal(builder, params);
            builder.endObject();
            return builder;
        }

        protected XContentBuilder keyToXContent(XContentBuilder builder) throws IOException {
            return builder.field(CommonFields.KEY.getPreferredName(), getKey());
        }

        protected static <B extends ParsedBucket> B parseXContent(final XContentParser parser,
                                                                  final boolean keyed,
                                                                  final Supplier<B> bucketSupplier,
                                                                  final CheckedBiConsumer<XContentParser, B, IOException> keyConsumer)
                                                                        throws IOException {
            final B bucket = bucketSupplier.get();
            bucket.setKeyed(keyed);
            XContentParser.Token token = parser.currentToken();
            String currentFieldName = parser.currentName();
            if (keyed) {
                ensureExpectedToken(XContentParser.Token.FIELD_NAME, token, parser::getTokenLocation);
                ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
            }

            List<Aggregation> aggregations = new ArrayList<>();
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                } else if (token.isValue()) {
                    if (CommonFields.KEY_AS_STRING.getPreferredName().equals(currentFieldName)) {
                        bucket.setKeyAsString(parser.text());
                    } else if (CommonFields.KEY.getPreferredName().equals(currentFieldName)) {
                        keyConsumer.accept(parser, bucket);
                    } else if (CommonFields.DOC_COUNT.getPreferredName().equals(currentFieldName)) {
                        bucket.setDocCount(parser.longValue());
                    }
                } else if (token == XContentParser.Token.START_OBJECT) {
                    aggregations.add(XContentParserUtils.parseTypedKeysObject(parser, Aggregation.TYPED_KEYS_DELIMITER, Aggregation.class));
                }
            }
            bucket.setAggregations(new Aggregations(aggregations));
            return bucket;
        }
    }
}


text:
.navbar .nav > li > .dropdown-menu:after {
    left: 83px;  /*change to your liking*/
}

.navbar .nav > li > .dropdown-menu:before {
    left: 83px;  /*keep values in after and before same*/
}

.dropdown-menu.right > li > a {
    text-align:right;
}

.dropdown-menu.center > li > a {
    text-align:center;
}

#loader_modal{
    background-color:rgba(0,0,0,0.5);
}

#loader_modal .modal-dialog{
    width:168px;
}

#loader_modal .modal-dialog .modal-content{
    /*background-color:rgba(255,255,255,0.5);*/
}

#loader_modal .modal-dialog .modal-content .modal-body{
    text-align:center;
}

td.paused-status{
    color:maroon;
}

td.active-status{
    color:green;
}

#main-navigation ul.nav.navbar-right li.divider{
    height: 1px;
    border-top: 1px solid rgba(0,0,0,0.5);
    border-bottom: 1px solid rgba(255,255,255,0.1);
}

.visible-but-hide{
    width:0px!important;
    height:0px!important;
    border:none!important;
    margin:0px!important;
    padding:0px!important;
    line-height: 0px!important;
    outline: none!important;
    overflow:hidden!important;
    position: absolute!important;
    background-color: transparent!important;
    top:-1px!important;
    left:-1px!important;
}

ul.nav-links{
    margin:0px;
    padding:10px 5px;
}

ul.nav-links li{
    list-style: none;
    padding:0px 10px;
    color:#cccccc;
    border-right:1px solid #cccccc;
    display: inline-block;
    margin:1px 0px;
}

ul.nav-links li:last-child{
    border-right:none;
}

ul.nav-links li:after{
    /*content: " | ";*/
}


text:
[![Build Status](https://secure.travis-ci.org/crystalcommerce/doctor-swagger.png)](http://travis-ci.org/crystalcommerce/doctor-swagger)

A DSL for generating Swagger schemas.

## Installation

Add this line to your application's Gemfile:

    gem 'doctor-swagger'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install doctor-swagger

## Usage

See the spec file.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## License

DoctorSwagger is released under the [MIT
License](http://opensource.org/licenses/MIT).


text:
#pragma once

#include "Eigen/Core"
#include "Eigen/Sparse"

namespace Eigen::Recursive
{
#define OLD_MS
template <typename T, bool = internal::is_arithmetic<T>::value>
struct BaseScalar
{
    using type = typename BaseScalar<typename T::Scalar>::type;
};
template <typename T>
struct BaseScalar<T, true>
{
    using type = T;
};

#ifndef OLD_MS

template <typename MatrixType>
struct MatrixScalar : public MatrixType
{
   public:
    using M           = MatrixType;
    using PlainObject = MatrixScalar<MatrixType>;

    MatrixScalar() = default;
    MatrixScalar(const MatrixType& a) : MatrixType(a) {}

    /**
     * This ctor is a bit questionable.
     *
     * It only exists because Eigen often uses the assignment
     * Scalar sum = Scalar(0);
     *
     * So the better solution would be to change this line into something more expessive for example:
     * Scalar sum = neutral_element_plus<Scalar>();
     *
     * But, since we don't want to change the complete source code we leave this here for now.
     */
    explicit MatrixScalar(int) { this->setZero(); }
    //    void operator=(int) { this->setZero(); }

    template <typename T, typename G>
    MatrixScalar(const Product<T, G>& a) : MatrixType(a)
    {
    }

    //    template <typename T>
    //    MatrixScalar(const Inverse<T>& a) : MatrixType(a)
    //    {
    //    }

    template <typename T, typename G, typename H>
    MatrixScalar(const CwiseBinaryOp<T, G, H>& a) : MatrixType(a)
    {
    }

    template <typename T, typename G>
    MatrixScalar(const CwiseUnaryOp<T, G>& a) : MatrixType(a)
    {
    }

    // This sadly doesn't work
    //    template <typename T>
    //    MatrixScalar(const MatrixBase<T>& a) : MatrixType(a)
    //    {
    //    }

    MatrixType& get() { return *this; }
    const MatrixType& get() const { return *this; }
};

#else
template <typename MatrixType>
struct MatrixScalar
{
    using M          = MatrixType;
    using Scalar     = typename MatrixType::Scalar;
    using ScalarType = MatrixScalar<MatrixType>;

    using BaseScalarType = typename BaseScalar<MatrixType>::type;
    using TransposeBase  = typename MatrixType::TransposeReturnType::NestedExpression;

    MatrixType data;

    EIGEN_ALWAYS_INLINE MatrixScalar() = default;

    // This constructor may seem a bit strange, but assigning anything different from a zero to a matrix is not well
    // defined. We also can't remove this constructor because some eigen functions use Scalar(0). Therefore we need
    // a constructor from a single (actual) scalar value.
    EIGEN_ALWAYS_INLINE MatrixScalar(BaseScalarType v)
    {
        data.setZero();
        //        data.setConstant(v);
    }
    //    EIGEN_ALWAYS_INLINE MatrixScalar(int v) { data.setZero(); }

    EIGEN_ALWAYS_INLINE MatrixScalar(const MatrixType& v) : data(v) {}

    //    template <typename T>
    //    EIGEN_ALWAYS_INLINE MatrixScalar(const MatrixBase<T>& v) : data(v)
    //    {
    //    }

    EIGEN_ALWAYS_INLINE MatrixScalar& operator=(const MatrixType& v)
    {
        data = v;
        return *this;
    }

    EIGEN_ALWAYS_INLINE Scalar& operator()(int i, int j) { return data(i, j); }
    EIGEN_ALWAYS_INLINE const Scalar& operator()(int i, int j) const { return data(i, j); }

    EIGEN_ALWAYS_INLINE MatrixScalar<TransposeBase> transpose() const { return {data.transpose()}; }

    EIGEN_ALWAYS_INLINE ScalarType operator-() const { return {-data}; }
    EIGEN_ALWAYS_INLINE ScalarType operator+(const ScalarType& other) const { return {data + other.data}; }
    EIGEN_ALWAYS_INLINE ScalarType operator-(const ScalarType& other) const { return {data - other.data}; }
    EIGEN_ALWAYS_INLINE ScalarType operator*(const ScalarType& other) const { return {data * other.data}; }
    //    ScalarType operator-(const ScalarType& other) const
    //    {
    //        std::cout << "-2" << std::endl;
    //        return {data - other.data};
    //    }

    template <typename G>
    EIGEN_ALWAYS_INLINE void operator+=(const MatrixScalar<G>& other)
    {
        data += other.data;
    }

    template <typename G>
    EIGEN_ALWAYS_INLINE bool operator==(const MatrixScalar<G>& other)
    {
        return data == other.data;
    }

    template <typename G>
    EIGEN_ALWAYS_INLINE void operator-=(const MatrixScalar<G>& other)
    {
        data -= other.data;
    }

    EIGEN_ALWAYS_INLINE void operator-=(const ScalarType& other) { data -= other.data; }

    // general matrix product
    template <typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
    EIGEN_ALWAYS_INLINE auto operator*(
        const MatrixScalar<Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>>& other) const
    {
        using ReturnType = Eigen::Matrix<_Scalar, MatrixType::RowsAtCompileTime, _Cols, _Options>;
        return MatrixScalar<ReturnType>(data * other.data);
    }

    //    template <typename T>
    //    auto operator*(const T& other) const
    //    {
    //        auto res = (data * other.data).evaluate();
    //        return MatrixScalar<decltype(res)>(res);
    //    }

    EIGEN_ALWAYS_INLINE MatrixType& get() { return data; }
    EIGEN_ALWAYS_INLINE const MatrixType& get() const { return data; }
};

// scalar product

#endif

template <typename T>
EIGEN_ALWAYS_INLINE auto makeMatrixScalar(const T& v)
{
    return MatrixScalar<T>(v);
}

template <typename T>
struct RemoveMatrixScalarImpl
{
    EIGEN_ALWAYS_INLINE static T& get(T& A) { return A; }
    EIGEN_ALWAYS_INLINE static const T& get(const T& A) { return A; }
};

template <typename G>
struct RemoveMatrixScalarImpl<MatrixScalar<G>>
{
    EIGEN_ALWAYS_INLINE static G& get(MatrixScalar<G>& A) { return A.get(); }
    EIGEN_ALWAYS_INLINE static const G& get(const MatrixScalar<G>& A) { return A.get(); }
};

template <typename T>
EIGEN_ALWAYS_INLINE auto& removeMatrixScalar(T& A)
{
    return RemoveMatrixScalarImpl<T>::get(A);
}

template <typename T>
EIGEN_ALWAYS_INLINE auto& removeMatrixScalar(const T& A)
{
    return RemoveMatrixScalarImpl<T>::get(A);
}

}  // namespace Eigen::Recursive

namespace Eigen
{
// template <typename T, typename BinaryOp>
// struct ScalarBinaryOpTraits<double, Recursive::MatrixScalar<T>, BinaryOp>
//{
//    typedef Recursive::MatrixScalar<T> ReturnType;
//};

// template <typename T, typename BinaryOp>
// struct ScalarBinaryOpTraits<Recursive::MatrixScalar<T>, double, BinaryOp>
//{
//    typedef Recursive::MatrixScalar<T> ReturnType;
//};

#ifndef OLD_MS
template <typename T, typename BinaryOp>
struct ScalarBinaryOpTraits<Recursive::MatrixScalar<T>, Recursive::MatrixScalar<T>, BinaryOp>
{
    typedef Recursive::MatrixScalar<T> ReturnType;
};

template <typename LHS, typename RHS, typename BinaryOp>
struct ScalarBinaryOpTraits<Recursive::MatrixScalar<LHS>, Recursive::MatrixScalar<RHS>, BinaryOp>
{
    enum
    {
        n = LHS::RowsAtCompileTime,
        m = RHS::ColsAtCompileTime,
        // Use Storage options of RHS type (might not be the best)
        options = RHS::Options
    };

    using ScalarType = typename ScalarBinaryOpTraits<typename LHS::Scalar, typename RHS::Scalar, BinaryOp>::ReturnType;
    using MatrixType = Matrix<ScalarType, n, m, options>;
    typedef Recursive::MatrixScalar<MatrixType> ReturnType;
};

template <typename LHS, typename T, typename BinaryOp>
struct ScalarBinaryOpTraits<Recursive::MatrixScalar<LHS>, MatrixBase<T>, BinaryOp>
{
    using ReturnType = int;
};

template <typename LHS, typename T, typename BinaryOp>
struct ScalarBinaryOpTraits<MatrixBase<T>, Recursive::MatrixScalar<LHS>, BinaryOp>
{
    using ReturnType = int;
};

#else
template <typename T, typename BinaryOp>
struct ScalarBinaryOpTraits<Recursive::MatrixScalar<T>, Recursive::MatrixScalar<T>, BinaryOp>
{
    typedef Recursive::MatrixScalar<T> ReturnType;
};
template <typename LHS, typename RHS, typename BinaryOp>
struct ScalarBinaryOpTraits<Recursive::MatrixScalar<LHS>, Recursive::MatrixScalar<RHS>, BinaryOp>
{
    enum
    {
        n = LHS::RowsAtCompileTime,
        m = RHS::ColsAtCompileTime,
        // Use Storage options of RHS type (might not be the best)
        options = RHS::Options
    };

    using ScalarType = typename ScalarBinaryOpTraits<typename LHS::Scalar, typename RHS::Scalar, BinaryOp>::ReturnType;
    using MatrixType = Matrix<ScalarType, n, m, options>;
    typedef Recursive::MatrixScalar<MatrixType> ReturnType;
};

#endif
}  // namespace Eigen
namespace Eigen
{
template <typename _Scalar>
auto operator*(typename Recursive::BaseScalar<_Scalar>::type lhs, const Recursive::MatrixScalar<_Scalar>& rhs)
{
    using MatrixType  = Recursive::MatrixScalar<_Scalar>;
    MatrixType result = (lhs * rhs.get()).eval();
    return result;
}

template <typename _Scalar>
auto operator*(const Recursive::MatrixScalar<_Scalar>& lhs, typename Recursive::BaseScalar<_Scalar>::type rhs)
{
    using MatrixType  = Recursive::MatrixScalar<_Scalar>;
    MatrixType result = (lhs.get() * rhs).eval();
    return result;
}

/**
 * This the actual recursive scalar multiplication. B = A * x
 * with B and A being recursive types and x an actual scalar (double,float,...)
 *
 * Eigen's default scalar multiplication doens't work because Matrix::Scalar are still matrices
 * in recursive types.
 *
 * Unfortunately I didn't find a way to return a "scalar product" expression object, so this
 * might create an unnessecary temporary.
 */
template <typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
auto operator*(typename Recursive::BaseScalar<_Scalar>::type lhs,
               const Matrix<Recursive::MatrixScalar<_Scalar>, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& rhs)
{
    using MatrixType = Matrix<Recursive::MatrixScalar<_Scalar>, _Rows, _Cols, _Options, _MaxRows, _MaxCols>;
    MatrixType result;
    result.resize(rhs.rows(), rhs.cols());
    for (int i = 0; i < rhs.rows(); ++i)
    {
        for (int j = 0; j < rhs.cols(); ++j)
        {
            result(i, j) = lhs * removeMatrixScalar(rhs(i, j));
        }
    }
    return result;
}
template <typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
auto operator*(const Eigen::Matrix<Recursive::MatrixScalar<_Scalar>, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& lhs,
               typename Recursive::BaseScalar<_Scalar>::type rhs)
{
    using MatrixType = Eigen::Matrix<Recursive::MatrixScalar<_Scalar>, _Rows, _Cols, _Options, _MaxRows, _MaxCols>;
    MatrixType result;
    result.resize(lhs.rows(), lhs.cols());
    for (int i = 0; i < lhs.rows(); ++i)
    {
        for (int j = 0; j < lhs.cols(); ++j)
        {
            result(i, j) = lhs(i, j) * rhs;
        }
    }
    return result;
}

template <typename _Scalar, int _Options>
auto operator*(typename Recursive::BaseScalar<_Scalar>::type lhs,
               const SparseMatrix<Recursive::MatrixScalar<_Scalar>, _Options>& rhs)
{
    using MatrixType  = SparseMatrix<Recursive::MatrixScalar<_Scalar>, _Options>;
    MatrixType result = rhs;

    for (int i = 0; i < result.outerSize(); ++i)
    {
        for (typename MatrixType::InnerIterator it(result, i); it; ++it)
        {
            it.valueRef() = lhs * it.value();
        }
    }
    result.markAsRValue();
    return result;
}
template <typename _Scalar, int _Options>
auto operator*(const SparseMatrix<Recursive::MatrixScalar<_Scalar>, _Options>& lhs,
               typename Recursive::BaseScalar<_Scalar>::type rhs)
{
    using MatrixType  = SparseMatrix<Recursive::MatrixScalar<_Scalar>, _Options>;
    MatrixType result = lhs;

    for (int i = 0; i < result.outerSize(); ++i)
    {
        for (typename MatrixType::InnerIterator it(result, i); it; ++it)
        {
            it.valueRef() = it.value() * rhs;
        }
    }
    result.markAsRValue();
    return result;
}

}  // namespace Eigen


text:
package com.globalforge.infix;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.globalforge.infix.api.InfixActions;
import com.google.common.collect.ListMultimap;

public class TestFunction {
   static final String sampleMessage =
      "8=FIX.4.4" + '\u0001' + "9=1000" + '\u0001' + "35=D" + '\u0001' + "55=BRK/A" + '\u0001'
         + "56=BRK A" + '\u0001' + "57=BRK/A/B" + '\u0001' + "10=004";

   @BeforeClass
   public static void setUpBeforeClass() throws Exception {
   }

   @Test
   public void testSplit0() {
      try {
         String sampleRule = "split(&55, \"/\", &55, &65)";
         InfixActions rules = new InfixActions(sampleRule);
         String result = rules.transformFIXMsg(sampleMessage);
         ListMultimap<String, String> resultStore = StaticTestingUtils.parseMessage(result);
         Assert.assertEquals(resultStore.get("55").get(0), "BRK");
         Assert.assertEquals(resultStore.get("65").get(0), "A");
      } catch (Exception e) {
         e.printStackTrace();
         Assert.fail();
      }
   }

   @Test
   public void testSplit1() {
      try {
         String sampleRule = "split(&56, \" \", &55, &65)";
         InfixActions rules = new InfixActions(sampleRule);
         String result = rules.transformFIXMsg(sampleMessage);
         ListMultimap<String, String> resultStore = StaticTestingUtils.parseMessage(result);
         Assert.assertEquals(resultStore.get("55").get(0), "BRK");
         Assert.assertEquals(resultStore.get("65").get(0), "A");
      } catch (Exception e) {
         e.printStackTrace();
         Assert.fail();
      }
   }

   @Test
   public void testSplit2() {
      try {
         String sampleRule = "split(&57, \"/\", &58, &59, &61)";
         InfixActions rules = new InfixActions(sampleRule);
         String result = rules.transformFIXMsg(sampleMessage);
         ListMultimap<String, String> resultStore = StaticTestingUtils.parseMessage(result);
         Assert.assertEquals(resultStore.get("58").get(0), "BRK");
         Assert.assertEquals(resultStore.get("59").get(0), "A");
         Assert.assertEquals(resultStore.get("61").get(0), "B");
      } catch (Exception e) {
         e.printStackTrace();
         Assert.fail();
      }
   }

   @Test
   public void testSplit3() {
      try {
         String sampleRule = "split(&57, \"/\", &58, &59)";
         InfixActions rules = new InfixActions(sampleRule);
         String result = rules.transformFIXMsg(sampleMessage);
         ListMultimap<String, String> resultStore = StaticTestingUtils.parseMessage(result);
         Assert.assertEquals(resultStore.get("58").get(0), "BRK");
         Assert.assertEquals(resultStore.get("59").get(0), "A");
      } catch (Exception e) {
         e.printStackTrace();
         Assert.fail();
      }
   }

   @Test
   public void testSplit4() {
      try {
         String sampleRule = "split(&56, \" \", &55, &65, &85)";
         InfixActions rules = new InfixActions(sampleRule);
         String result = rules.transformFIXMsg(sampleMessage);
         ListMultimap<String, String> resultStore = StaticTestingUtils.parseMessage(result);
         Assert.assertEquals(resultStore.get("55").get(0), "BRK");
         Assert.assertEquals(resultStore.get("65").get(0), "A");
      } catch (Exception e) {
         e.printStackTrace();
         Assert.fail();
      }
   }

   @Test
   public void testSplit5() {
      try {
         String sampleRule = "split(&56, \" \", &55)";
         InfixActions rules = new InfixActions(sampleRule);
         String result = rules.transformFIXMsg(sampleMessage);
         ListMultimap<String, String> resultStore = StaticTestingUtils.parseMessage(result);
         Assert.assertEquals(resultStore.get("55").get(0), "BRK");
         Assert.assertTrue(resultStore.get("65").isEmpty());
      } catch (Exception e) {
         e.printStackTrace();
         Assert.fail();
      }
   }

   @Test
   public void testSplit6() {
      try {
         String sampleRule = "&42=split(&56, \" \", &55)";
         InfixActions rules = new InfixActions(sampleRule);
         String result = rules.transformFIXMsg(sampleMessage);
         ListMultimap<String, String> resultStore = StaticTestingUtils.parseMessage(result);
         Assert.assertEquals(resultStore.get("55").get(0), "BRK");
         Assert.assertTrue(resultStore.get("65").isEmpty());
         // split() doesn't return anything
         Assert.assertTrue(resultStore.get("42").isEmpty());
      } catch (Exception e) {
         e.printStackTrace();
         Assert.fail();
      }
   }
}


text:
<resources>
    <string name="app_name">Hello VR World</string>
</resources>


text:
$(".slider_area_gradient" ).click(function(evt) {
	var x = Math.min(Math.max(evt.pageX - $(this).offset().left, 0), 255);

	createGradientSlider(x, 'ffffff', 'gradient');

	updateTexture();
	//alert( "Position: " + x );
});

$(".slider_area_gradient").droppable({
	out: function (event, ui) {
		//document.write($(ui.draggable).position().left);
		if ($(ui.draggable).position().left < 250)
			$(ui.draggable).remove();
    }
});

createGradientSlider(0, 'e6d7c3', 'gradient');
createGradientSlider(96, '262626', 'gradient');
createGradientSlider(178, '665e52', 'gradient');

function updateGradient(canvas, size){
	var colors = [];

	$(".slider_gradient").each(function( index ) {
		var pos = $(this).css("left");
		pos = pos.substring(0, pos.length - 2);
		var percentage = Math.min(parseFloat(pos) - 5, 255) / 2.56;

		colors.push([rgb2hex($(this).css("background-color")), percentage]);
	});

	var gradient_text = 'linear-gradient(to right';
	colors.forEach(function(col) {
		gradient_text += ', ' + col[0] + ' ' + Math.max(col[1],0) + '%';
	});
	$(".gradient_gradient_preview").css('background', gradient_text); // W3C

	gradient_type = $("select#gradient_type option:selected").val();
	//document.write(gradient_type);
	setGradientColors(canvas, size, colors, gradient_type);
}