text:
<a type="button" class="btn btn-warning btn-lg" href="<?php echo base_url("users/edit/".$this->session->userdata('id_user')."");?>">Editar Perfil Información sobre el Perfil

        <?php
          print_r($perfil_data);
          //echo json_encode($perfil_data, JSON_PRETTY_PRINT);
        ?>

        Mis Actividades
        [ <?php echo $this->session->userdata('username');?> ]

Pago de Regalías (Membresías)

Ver Terminos y Condiciones del tipo de Membresía

Añadir Cuenta Bancaria

Añadir Cuenta PayPal

Variables de la COOKIE

      <?php $galleta = $this->input->cookie('ci_session');
        echo $galleta;
      ?>

Variables de la SESION

      <?php foreach ($all_userdata as $key => $value) {
      # code...
      echo $key.' = ';
      echo $value.'
';
    } ?>


text:
(function() {
    var __loader = (function() {

        /**
         *
         * @param configuration
         * @returns {*}
         */
        var normalizeConfig = function normalizeConfig(configuration) {
            if (configuration == null) {
                configuration = {};
            }

            var defaultConfig = {
                columns: {
                    type: 'object',
                    default: []
                },
                height: {
                    type: 'number',
                    default: 240
                },
                filterControl: {
                    type: 'boolean',
                    default: false
                },
                paginationControl: {
                    type: 'boolean',
                    default: false
                },
                lengthControl: {
                    type: 'boolean',
                    default: false
                },
                tableInfo: {
                    type: 'boolean',
                    default: false
                },
                selectable: {
                    type: 'boolean',
                    default: true
                },
                maxRowsSelected: {
                    type: 'number',
                    default: 1
                },
                minRowsSelected: {
                    type: 'number',
                    default: 0
                },
                initialSelectedRows: {
                    type: 'number',
                    default: 0
                },
                updateContexts: {
                    type: 'object',
                    default: null
                },
                keepSelectedByProperty: {
                    type: 'string',
                    default: ""
                },
                orderByColumn: {
                    type: 'object',
                    default: []
                },
                showHeader: {
                    type: 'boolean',
                    default: true
                },
                swapOnMaxim: {
                    type: 'boolean',
                    default: false
                },
                scrollButtons: {
                    type: 'boolean',
                    default: true
                }
            };

            for(var confName in defaultConfig) {
                var conf = defaultConfig[confName];
                if (typeof configuration[confName] != conf['type']) {
                    configuration[confName] = conf['default'];
                }
            }

            return configuration;
        };

        /* Table constructor
         *   element: the DOM element that will contain the rangeNv
         *   data: the resources array. It should contain only a resource, or at least the same resources with different
         *      parameters.
         *   contextId: optional.
         *   configuration: additional table configuration:
         *      {
         *       ~ height: number - Height of the widget.
         *       ~ filterControl: boolean - Whether to display the search filter control or not.
         *       ~ paginationControl: boolean - Whether to display the pagination control or not.
         *       ~ lengthControl: boolean - Whether to display a selector with the number of rows to show or not.
         *       ~ tableInfo: boolean - Whether to show extra info about the table or not.
         *       ~ selectable: boolean - If true, the rows of this table can be selected. When selected, the contexts are
         *          are updated with the data updateContexts indicates.
         *       ~ maxRowsSelected: number - Maximum number of rows that can be selected at the same time. Default: 1.
         *       ~ minRowsSelected: number - Minimum number of rows that must be selected at the same time. Default: 0.
         *       ~ initialSelectedRows: number - Number of rows that must be selected at the beginning. Default: 0.
         *       ~ orderByColumn: array - Must be an array of arrays, each inner array comprised of two elements: Column
         *          index to order upon and direction so order to apply (asc or desc).
         *       ~ alwaysOneSelected: boolean - Whether to set only one always selected item, changing element with simple click.
         *       ~ keepSelectedByProperty: string - Property used to remember the selected rows.
         *       ~ updateContexts: array - Array of objects that configure how to update the contexts. It must contain an id with
         *          the id of the context and a filter array with the data to send through the context update.
         *          Each filter must contain a 'property' property with the name of the property of the data retrieved from
         *          the framework and can optionally add an 'as' property to indicate the name that it must have in the
         *          object that will be sent through the updateContext.
         *          Format:
         *          {
         *               id: <String>,
         *               filter: [
         *                   {
         *                       property: <String>,
         *                       as: <String> //optional
         *                   }
         *               ]
         *          }
         *          Example (listing all the repositories):
         *          {
         *               id: "repoContext",
         *               filter: [
         *                   {
         *                       property: "repositoryid",
         *                       as: "rid"
         *                   }
         *               ]
         *          }
         *       ~ columns: array - Array of objects with the configuration of all the columns to display in the table.
         *          Column object contains a 'label' and a 'property' or a link. Additionally it can contain a 'width' that
         *          may take any CSS value (3em, 20px, 10%, etc). Please note that pixel perfect column width is virtually
         *          impossible to achieve in tables with dynamic content.
         *          In case of a property, it is the name of the property of the data retrieved from the framework that
         *          must be displayed in that column.
         *          In case of a link, it displays a link to change to other dashboard. A link is an object with multiple
         *          properties: a 'href' with the name of the dashboard to go to, an 'icon' (class of the icon to display),
         *          an 'img' whose value indicates the property that contains the url of the image to be displayed
         *          or a 'label' (text) to display, and an 'env' that configures the environment info to send to the
         *          new dashboard. The 'env' property is an array of objects that contains a 'property' and an optional 'as'.
         *          Format:
         *          {
         *               label: <String>,
         *               property: <String>
         *           },
         *           {
         *              label: "Show",
         *               link: {
         *                   icon: <String>, //or label: <String> or img: <String>
         *                   href: <String>,
         *                   env: [
         *                       {
         *                           property: <String>,
         *                           as: <String>
         *                       }
         *                   ]
         *               }
         *          }, ...
         *          Example (listing all the repositories and changing to the dashboard of the selected repository):
         *          {
         *               label: "Name",
         *               property: "name"
         *           },
         *           {
         *              label: "Go to",
         *               link: {
         *                   icon: "fa fa-share-square-o",
         *                   href: "repository-dashboard",
         *                   env: [
         *                       {
         *                           property: "repositoryid",
         *                           as: "rid"
         *                       }
         *                   ]
         *               }
         *          }
         *      }
         */
        var Table = function Table(element, metrics, contextId, configuration) {

            if(!framework.isReady()) {
                console.error("Table object could not be created because framework is not loaded.");
                return;
            }

            this.element = $(element); //Store as jquery object
            this.data = null;
            this.tableDom = null;
            this.table = null;
            this.selected = [];
            this.deleted = false;

            // Extending widget
            framework.widgets.CommonWidget.call(this, false, this.element.get(0));

            // Configuration
            this.configuration = normalizeConfig(configuration);

            this.observeCallback = this.commonObserveCallback.bind(this);

            framework.data.observe(metrics, this.observeCallback , contextId);

        };

        Table.prototype = new framework.widgets.CommonWidget(true);

        /**
         *
         * @param framework_data
         */
        Table.prototype.updateData = function(framework_data) {

            // Has been destroyed
            if(this.deleted)
                return;

            var creating = false; //Is it the creation of the dable

            if(this.tableDom == null) {

                creating = true;

                //Create the html for the table
                this.element.append('

');
                this.tableDom = this.element.children("table");
                this.tableDom.get(0).style.maxHeight = this.configuration.height + "px";

                // Add buttons to scroll up and down in the table
                if (this.configuration.scrollButtons) {

                    var upScrollButton = $('

');
                    var downScrollButton = $('

');

                    this.element.append(upScrollButton);
                    this.element.append(downScrollButton);

                    upScrollButton.click(function () {
                        this.element.find('.scroll-table').animate({
                            scrollTop: '-=100'
                        }, 200);
                    }.bind(this));

                    downScrollButton.click(function () {
                        this.element.find('.scroll-table').animate({
                            scrollTop: '+=100'
                        }, 200);
                    }.bind(this));

                }

                //Add click listener for links
                this.tableDom.on( 'click', '.dashboardLink', this, dashboardLinkClickHandler);

                //Handle clicks in rows to select them or not
                if(this.configuration.selectable) {
                    this.tableDom.on('click', 'tbody tr', this, rowClickHandler);
                }

                // Add mouseWeel event controller
                function preventDefault(e) {
                    e = e || window.event;
                    if (e.preventDefault) {
                        e.preventDefault();
                    } else {
                        e.returnValue = false;
                    }
                }

                //Firefox
                $(this.tableDom).bind('DOMMouseScroll', function(e){
                    if(e.originalEvent.detail/120 > 0) {
                        //scroll down
                        this.element.find('.scroll-table').animate({
                            scrollTop: '+=60'
                        }, 5);
                    }else {
                        //scroll up
                        this.element.find('.scroll-table').animate({
                            scrollTop: '-=60'
                        }, 5);
                    }

                    e.stopPropagation();
                    preventDefault(e);
                    return false;
                }.bind(this));

                //IE, Opera, Safari
                $(this.tableDom).bind('mousewheel', function(e){
                    if(e.originalEvent.wheelDelta/120 < 0) {
                        //scroll down
                        this.element.find('.scroll-table').animate({
                            scrollTop: '+=60'
                        }, 5);
                    }else {
                        //scroll up
                        this.element.find('.scroll-table').animate({
                            scrollTop: '-=60'
                        }, 5);
                    }

                    e.stopPropagation();
                    preventDefault(e);
                    return false;
                }.bind(this));
            }

            var normalizedData = getNormalizedData.call(this,framework_data);

            var head = this.tableDom.find("thead tr");
            head.empty();

            //Fill the header columns
            if(this.configuration.showHeader) {
                for(var i in this.configuration.columns) {
                    head.append("" + this.configuration.columns[i]['label'] + "	")
                }
            } else {
                this.tableDom.find("thead").hide();
            }

            //Create dom configuration string
            var dom = "";
            if(this.configuration.filterControl) dom += '<"table-search"f>';
            if(this.configuration.lengthControl) dom += 'l';
            dom += '<"scroll-table"t>';
            if(this.configuration.tableInfo) dom += 'i';
            if(this.configuration.paginationControl) dom += 'p';

            // Get columns
            var columns = [];
            for(var i in this.configuration.columns) {

                var columnConfig = this.configuration.columns[i];
                var column = null;

                if(columnConfig['property'] != null) { //Is a property
                    column = { data: columnConfig['property'] };

                } else if(columnConfig['link'] != null && columnConfig['link']['href'] != null) { //Is a link
                    var _data = columnConfig['link'];
                    column = {
                        data: function(){ return _data; },
                        orderable: false,
                        searchable: false,
                        render: columnIconRenderer
                    };

                } else if(columnConfig['img'] != null) { //Is an image
                    var _data = {img: columnConfig['img']};
                    column = {
                        data: function(){ return _data; },
                        orderable: false,
                        searchable: false,
                        render: columnIconRenderer
                    };
                } else if(columnConfig['icon'] != null) { //Is an icon
                    var _data = {icon: columnConfig['icon']};
                    column = {
                        data: function(){ return _data; },
                        orderable: false,
                        searchable: false,
                        render: columnIconRenderer
                    }
                }

                //If it has the required properties
                if(column != null) {

                    if(columnConfig['width'] != null) {
                        column['width'] = columnConfig['width'];
                    }

                    columns.push(column);
                }

            }

            //Destroy the table it already exists
            if(this.table != null) {
                this.table.destroy();
            }

            //DataTable object
            var conf = {
                data: normalizedData,
                dom: dom,
                columns: columns,
                "oLanguage": {
                    "sSearch": "",
                    "sSearchPlaceholder": "Search..."
                },
                "paging": this.configuration.paginationControl
            };
            if(this.configuration.orderByColumn instanceof Array) {
                conf['order'] = this.configuration.orderByColumn;
            }
            this.table = this.tableDom.DataTable(conf);

            // Add scroll-table height
            this.element.find('.scroll-table')[0].style.height = (this.configuration.height - 43) + 'px';

            //Previously selected rows
            if(this.configuration.selectable && this.configuration.keepSelectedByProperty !== "" && this.selected.length > 0) {
                var newSelectedList = [];
                this.table.$('tr').each(function(rowIndex, row) {

                    var rowdata = this.table.row($(row)).data();
                    var selectByData = rowdata[this.configuration.keepSelectedByProperty];

                    //If it was previously selected, select it
                    var index = this.selected.indexOf(selectByData);
                    if(index > -1) {
                        // Previousl selected row
                        $(row).addClass('selected');
                        newSelectedList.push(selectByData);
                    }

                }.bind(this));
                this.selected = newSelectedList;
                var auxDif = this.configuration.minRowsSelected - this.selected.length;
                if (auxDif > 0) {
                    this.table.$('tr:not(.selected)').slice(0, auxDif).each(function(rowIndex, row) {
                        $(row).addClass('selected');
                        if(this.configuration.keepSelectedByProperty !== "") {
                            this.selected.push(this.table.row(rowIndex).data()[this.configuration.keepSelectedByProperty]);
                        }
                    }.bind(this));
                }
            }
            if(creating && this.configuration.selectable && this.configuration.initialSelectedRows > 0) {

                //Select the first n rows
                this.table.$('tr:not(.selected)').slice(0, this.configuration.initialSelectedRows).each(function(rowIndex, row) {
                    $(row).addClass('selected');
                    if(this.configuration.keepSelectedByProperty !== "") {
                        this.selected.push(this.table.row(rowIndex).data()[this.configuration.keepSelectedByProperty]);
                    }
                }.bind(this));

            }

            //Update the contexts with the new selected rows
            updateContexts.call(this);

        };

        /**
         * Deletes the widget.
         */
        Table.prototype.delete = function() {

            //Stop observing for data changes
            framework.data.stopObserve(this.observeCallback);

            if(this.tableDom != null) {
                //Remove event listeners
                this.tableDom.off();

                //Destroy DataTable
                this.table.destroy();

                //Clear DOM
                this.tableDom.empty();
            }

            //Remove all DOM the elements added to element
            this.element.empty();

            this.tableDom = null;
            this.table = null;

            //Update status
            this.deleted = true;

        };

        // PRIVATE METHODS - - - - - - - - - - - - - - - - - - - - - -

        /**
         * Renderer for columns that contain links.
         * @param linkInfo Info about the link. Must contain an icon property (with the class of the icon to display)
         *           or a label property (with the text to display).
         *           See https://datatables.net/reference/option/columns.render#function
         * @param type See https://datatables.net/reference/option/columns.render#function
         * @param rowData See https://datatables.net/reference/option/columns.render#function
         * @returns {*}
         */
        var columnIconRenderer = function columnIconRenderer(linkInfo, type, rowData) {

            if ( type === 'display' ) {

                var col;
                if (linkInfo['icon'] != null) { //It is an icon
                    col = '

';
                } else if (linkInfo['img'] != null) { //It is an image
                    col = '

';
                }else { //Just a label
                    col = '
' + linkInfo['label'] + '
';
                }
                return col;

            }

            return linkInfo;

        };

        /**
         * Function that handles the click in a dashboard link.
         * @param e
         */
        var dashboardLinkClickHandler = function dashboardLinkClickHandler(e) {

            e.stopImmediatePropagation(); // stop the row selection when clicking on an icon

            var widget = e.data;
            var cell = $(this).parent();

            var linkInfo = widget.table.cell(cell).data();
            var rowData = widget.table.row(cell.parent()).data();

            //If link information is not set, do not try to change to a dashboard
            if(linkInfo['href'] == null || typeof linkInfo['href'] !== 'string' || linkInfo['href'].length === 0) {
                return;
            }

            //Generate the env
            var env = null;
            if (linkInfo['env'] != null) {
                env = generateEnv(linkInfo['env'], rowData);
            }

            //Change the dashboard
            framework.dashboard.changeTo(linkInfo['href'], env);

        };

        /**
         * Function that handles clicks in rows. When selecting a row it may be necessary to update contexts.
         * @param e
         */
        var rowClickHandler = function rowClickHandler(e) {
            e.stopImmediatePropagation();

            var widget = e.data;
            var rowdata = widget.table.row($(this)).data();
            var selectByData = null;

            if(widget.configuration.keepSelectedByProperty !== "") {
                selectByData = rowdata[widget.configuration.keepSelectedByProperty];
            }

            if ( $(this).hasClass('selected') ) { //It is already selected

                //Select it if the maximum of selected rows has not been achieved
                if(widget.table.$('tr.selected').length > widget.configuration.minRowsSelected) {
                    $(this).removeClass('selected');

                    //Remove from the keep selected array
                    if(selectByData != null) {
                        var index = widget.selected.indexOf(selectByData);
                        if(index >= 0) {
                            widget.selected.splice(index, 1);
                        }
                    }
                }

            } else { //Not selected
                if (widget.configuration.alwaysOneSelected && widget.configuration.maxRowsSelected === 1 && widget.table.$('tr.selected').length === 1) {

                    //Remove from the keep selected array
                    getLastSelectedRow.call(widget).removeClass('selected');
                    widget.selected.pop();
                }

                //Select it if the maximum of selected rows has not been achieved
                if(widget.configuration.maxRowsSelected > widget.table.$('tr.selected').length) {
                    $(this).addClass('selected');
                    //Add to the keep selected array
                    if(selectByData != null) {
                        widget.selected.push(selectByData);
                    }
                }
            }

            // Update contexts with the selected rows
            updateContexts.call(widget);

        };

        var getLastSelectedRow = function getLastSelectedRow () {
            if (this.selected.length > 0) {
                var id = this.selected[this.selected.length -1];
            }
            var foundRow = null;
            this.table.$('tr').each(function(rowIndex, row) {
                var rowdata = this.table.row(rowIndex).data();
                var selectByData = rowdata[this.configuration.keepSelectedByProperty];

                if(selectByData == id) {
                    foundRow = row;
                    return false; // break the each loop
                }
            }.bind(this));
            return $(foundRow);
        };

        /**
         * Update the contexts with the selected rows
         */
        var updateContexts = function updateContexts(){

            // Update contexts
            var contexts = this.configuration.updateContexts;
            if(contexts != null) {

                for(var i in contexts) {
                    var context = contexts[i];

                    if(context['id'] != null) {

                        // Data to send through the context
                        var data = {};

                        // Filter the data to send through the context update
                        if(context['filter'] != null) {
                            for(var f = 0; f < context['filter'].length; ++f) {

                                var filter = context['filter'][f];
                                var property = filter['property'];
                                var as = filter['as'] || property;

                                if(data[as] == null) {
                                    data[as] = [];
                                }

                                //Selected items
                                var selected = this.table.$('tr.selected');

                                //Calculate the data to send for all the selected rows
                                for(var s = 0, len = selected.length; s < len; ++s) {

                                    var selectedData = this.table.row(selected[s]).data();
                                    var propertyValue = selectedData[property];

                                    if(property != null && typeof propertyValue !== 'undefined') {
                                        data[as].push(propertyValue);
                                    }

                                }
                            }

                        }

                        //Send the update context
                        framework.data.updateContext(context['id'], data);
                    }
                }
            }

        };

        /**
         * Generates an environment object containing all the information of the environment
         * @param envProperty The env configuration property
         * @param rowData Al, the data of the row.
         * @returns {{}}
         */
        var generateEnv = function generateEnv(envProperty, rowData) {

            var env = {};

            for(var e = 0; e < envProperty.length; ++e) {

                var envEntry = envProperty[e];
                var property, as, envValue;

                if(envEntry['property'] != null) {

                    property = envEntry['property'];
                    as = envEntry['as'] || property;
                    envValue = rowData[property];

                } else if(envEntry['currentEnv']) {

                    property = envEntry['currentEnv'];
                    as = envEntry['as'] || property;
                    envValue = framework.dashboard.getEnv()[property];

                }

                if(typeof envValue !== 'undefined') {
                    env[as] = envValue;
                }

            }

            return env;
        };

        /**
         * Gets a normalized array of data according to the chart expected input from the data returned by the framework.
         * @param framework_data
         * @returns {Array} Contains objects with 'label' and 'value'.
         */
        var getNormalizedData = function getNormalizedData(framework_data) {

            return this.extractAll(framework_data);

        };

        window.framework.widgets.Table = Table;
        return Table;

    });

    // AMD compliant
    if ( typeof define === "function" && define.amd) {
        define( [
            'sdh-framework/widgets/Common/common',
            'datatables',
            'css!./table.css',
            'css!datatables/media/css/jquery.dataTables.min'
        ], function () {
            return __loader();
        } );
    } else {
        __loader();
    }

})();

redpajama_set_name: RedPajamaGithub


text:
package gov.nih.nci.cabig.caaers.web.ae;

import gov.nih.nci.cabig.caaers.dao.EpochDao;
import gov.nih.nci.cabig.caaers.dao.ExpeditedAdverseEventReportDao;
import gov.nih.nci.cabig.caaers.dao.StudyDao;
import gov.nih.nci.cabig.caaers.web.WebTestCase;
import org.easymock.classextension.EasyMock;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.servlet.ModelAndView;

public class GenerateExpeditedPdfControllerTest extends WebTestCase {
    private GenerateExpeditedPdfController controller;
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;
    private ExpeditedAdverseEventReportDao aeReportDao;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        controller = new GenerateExpeditedPdfController();
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
        aeReportDao= EasyMock.createMock(ExpeditedAdverseEventReportDao.class);
        controller.setAeReportDao(aeReportDao);
    }

    public void testExportCustomPDF() throws Exception {
        request.setMethod("GET");
        request.setParameter("format", "customPDF");
        request.setParameter("aeReport", "5");
        request.setParameter("reportId", "6");

        try {
            replayMocks();
            ModelAndView mv = controller.handleRequest(request, response);
            verifyMocks();
        } catch (Exception e) {
        }
    }

     public void testExportImage() throws Exception {
        request.setMethod("GET");
        request.setParameter("format", "image");
        request.setParameter("aeReport", "5");
        request.setParameter("reportId", "6");

        try {
            replayMocks();
            ModelAndView mv = controller.handleRequest(request, response);
            verifyMocks();
        } catch (Exception e) {
        }
    }

}


text:
<?php

defined('_JEXEC') or die;

/**
 * Methods supporting a list of user records.
 *
 * @since  1.6
 */
class UsersModelUsers extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'name', 'a.name',
				'username', 'a.username',
				'email', 'a.email',
				'block', 'a.block',
				'sendEmail', 'a.sendEmail',
				'registerDate', 'a.registerDate',
				'lastvisitDate', 'a.lastvisitDate',
				'activation', 'a.activation',
				'active',
				'group_id',
				'range',
				'state',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		$app = JFactory::getApplication('administrator');

		// Adjust the context to support modal layouts.
		if ($layout = $app->input->get('layout', 'default', 'cmd'))
		{
			$this->context .= '.' . $layout;
		}

		// Load the filter state.
		$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		$active = $this->getUserStateFromRequest($this->context . '.filter.active', 'filter_active');
		$this->setState('filter.active', $active);

		$state = $this->getUserStateFromRequest($this->context . '.filter.state', 'filter_state');
		$this->setState('filter.state', $state);

		$groupId = $this->getUserStateFromRequest($this->context . '.filter.group_id', 'filter_group_id', null, 'int');
		$this->setState('filter.group_id', $groupId);

		$range = $this->getUserStateFromRequest($this->context . '.filter.range', 'filter_range');
		$this->setState('filter.range', $range);

		$groups = json_decode(base64_decode($app->input->get('groups', '', 'BASE64')));

		if (isset($groups))
		{
			JArrayHelper::toInteger($groups);
		}

		$this->setState('filter.groups', $groups);

		$excluded = json_decode(base64_decode($app->input->get('excluded', '', 'BASE64')));

		if (isset($excluded))
		{
			JArrayHelper::toInteger($excluded);
		}

		$this->setState('filter.excluded', $excluded);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_users');
		$this->setState('params', $params);

		// List state information.
		parent::populateState('a.name', 'asc');
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 *
	 * @since   1.6
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.active');
		$id .= ':' . $this->getState('filter.state');
		$id .= ':' . $this->getState('filter.group_id');
		$id .= ':' . $this->getState('filter.range');

		return parent::getStoreId($id);
	}

	/**
	 * Gets the list of users and adds expensive joins to the result set.
	 *
	 * @return  mixed  An array of data items on success, false on failure.
	 *
	 * @since   1.6
	 */
	public function getItems()
	{
		// Get a storage key.
		$store = $this->getStoreId();

		// Try to load the data from internal storage.
		if (empty($this->cache[$store]))
		{
			$groups  = $this->getState('filter.groups');
			$groupId = $this->getState('filter.group_id');

			if (isset($groups) && (empty($groups) || $groupId && !in_array($groupId, $groups)))
			{
				$items = array();
			}
			else
			{
				$items = parent::getItems();
			}

			// Bail out on an error or empty list.
			if (empty($items))
			{
				$this->cache[$store] = $items;

				return $items;
			}

			// Joining the groups with the main query is a performance hog.
			// Find the information only on the result set.

			// First pass: get list of the user id's and reset the counts.
			$userIds = array();

			foreach ($items as $item)
			{
				$userIds[] = (int) $item->id;
				$item->group_count = 0;
				$item->group_names = '';
				$item->note_count = 0;
			}

			// Get the counts from the database only for the users in the list.
			$db    = $this->getDbo();
			$query = $db->getQuery(true);

			// Join over the group mapping table.
			$query->select('map.user_id, COUNT(map.group_id) AS group_count')
				->from('#__user_usergroup_map AS map')
				->where('map.user_id IN (' . implode(',', $userIds) . ')')
				->group('map.user_id')
				// Join over the user groups table.
				->join('LEFT', '#__usergroups AS g2 ON g2.id = map.group_id');

			$db->setQuery($query);

			// Load the counts into an array indexed on the user id field.
			try
			{
				$userGroups = $db->loadObjectList('user_id');
			}
			catch (RuntimeException $e)
			{
				$this->setError($e->getMessage());

				return false;
			}

			$query->clear()
				->select('n.user_id, COUNT(n.id) As note_count')
				->from('#__user_notes AS n')
				->where('n.user_id IN (' . implode(',', $userIds) . ')')
				->where('n.state >= 0')
				->group('n.user_id');

			$db->setQuery($query);

			// Load the counts into an array indexed on the aro.value field (the user id).
			try
			{
				$userNotes = $db->loadObjectList('user_id');
			}
			catch (RuntimeException $e)
			{
				$this->setError($e->getMessage());

				return false;
			}

			// Second pass: collect the group counts into the master items array.
			foreach ($items as &$item)
			{
				if (isset($userGroups[$item->id]))
				{
					$item->group_count = $userGroups[$item->id]->group_count;

					// Group_concat in other databases is not supported
					$item->group_names = $this->_getUserDisplayedGroups($item->id);
				}

				if (isset($userNotes[$item->id]))
				{
					$item->note_count = $userNotes[$item->id]->note_count;
				}
			}

			// Add the items to the internal cache.
			$this->cache[$store] = $items;
		}

		return $this->cache[$store];
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db    = $this->getDbo();
		$query = $db->getQuery(true);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.*'
			)
		);

		$query->from($db->quoteName('#__users') . ' AS a');

		// If the model is set to check item state, add to the query.
		$state = $this->getState('filter.state');

		if (is_numeric($state))
		{
			$query->where('a.block = ' . (int) $state);
		}

		// If the model is set to check the activated state, add to the query.
		$active = $this->getState('filter.active');

		if (is_numeric($active))
		{
			if ($active == '0')
			{
				$query->where('a.activation IN (' . $db->quote('') . ', ' . $db->quote('0') . ')');
			}
			elseif ($active == '1')
			{
				$query->where($query->length('a.activation') . ' > 1');
			}
		}

		// Filter the items over the group id if set.
		$groupId = $this->getState('filter.group_id');
		$groups  = $this->getState('filter.groups');

		if ($groupId || isset($groups))
		{
			$query->join('LEFT', '#__user_usergroup_map AS map2 ON map2.user_id = a.id')
				->group(
					$db->quoteName(
						array(
							'a.id',
							'a.name',
							'a.username',
							'a.password',
							'a.block',
							'a.sendEmail',
							'a.registerDate',
							'a.lastvisitDate',
							'a.activation',
							'a.params',
							'a.email'
						)
					)
				);

			if ($groupId)
			{
				$query->where('map2.group_id = ' . (int) $groupId);
			}

			if (isset($groups))
			{
				$query->where('map2.group_id IN (' . implode(',', $groups) . ')');
			}
		}

		// Filter the items over the search string if set.
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where('a.id = ' . (int) substr($search, 3));
			}
			elseif (stripos($search, 'username:') === 0)
			{
				$search = $db->quote('%' . $db->escape(substr($search, 9), true) . '%');
				$query->where('a.username LIKE ' . $search);
			}
			else
			{
				// Escape the search token.
				$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));

				// Compile the different search clauses.
				$searches   = array();
				$searches[] = 'a.name LIKE ' . $search;
				$searches[] = 'a.username LIKE ' . $search;
				$searches[] = 'a.email LIKE ' . $search;

				// Add the clauses to the query.
				$query->where('(' . implode(' OR ', $searches) . ')');
			}
		}

		// Add filter for registration ranges select list
		$range = $this->getState('filter.range');

		// Apply the range filter.
		if ($range)
		{
			// Get UTC for now.
			$dNow   = new JDate;
			$dStart = clone $dNow;

			switch ($range)
			{
				case 'past_week':
					$dStart->modify('-7 day');
					break;

				case 'past_1month':
					$dStart->modify('-1 month');
					break;

				case 'past_3month':
					$dStart->modify('-3 month');
					break;

				case 'past_6month':
					$dStart->modify('-6 month');
					break;

				case 'post_year':
				case 'past_year':
					$dStart->modify('-1 year');
					break;

				case 'today':
					// Ranges that need to align with local 'days' need special treatment.
					$app    = JFactory::getApplication();
					$offset = $app->get('offset');

					// Reset the start time to be the beginning of today, local time.
					$dStart = new JDate('now', $offset);
					$dStart->setTime(0, 0, 0);

					// Now change the timezone back to UTC.
					$tz = new DateTimeZone('GMT');
					$dStart->setTimezone($tz);
					break;
			}

			if ($range == 'post_year')
			{
				$query->where(
					$db->qn('a.registerDate') . ' < ' . $db->quote($dStart->format('Y-m-d H:i:s'))
				);
			}
			else
			{
				$query->where(
					$db->qn('a.registerDate') . ' >= ' . $db->quote($dStart->format('Y-m-d H:i:s')) .
					' AND ' . $db->qn('a.registerDate') . ' <= ' . $db->quote($dNow->format('Y-m-d H:i:s'))
				);
			}
		}

		// Filter by excluded users
		$excluded = $this->getState('filter.excluded');

		if (!empty($excluded))
		{
			$query->where('id NOT IN (' . implode(',', $excluded) . ')');
		}

		// Add the list ordering clause.
		$query->order($db->qn($db->escape($this->getState('list.ordering', 'a.name'))) . ' ' . $db->escape($this->getState('list.direction', 'ASC')));

		return $query;
	}

	/**
	 * SQL server change
	 *
	 * @param   integer  $user_id  User identifier
	 *
	 * @return  string   Groups titles imploded :$
	 */
	protected function _getUserDisplayedGroups($user_id)
	{
		$db    = $this->getDbo();
		$query = $db->getQuery(true)
			->select($db->qn('title'))
			->from($db->qn('#__usergroups', 'ug'))
			->join('LEFT', $db->qn('#__user_usergroup_map', 'map') . ' ON (ug.id = map.group_id)')
			->where($db->qn('map.user_id') . ' = ' . (int) $user_id);

		try
		{
			$result = $db->setQuery($query)->loadColumn();
		}
		catch (RunTimeException $e)
		{
			$result = array();
		}

		return implode("\n", $result);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

namespace Network_Simulation
{
	public partial class NetworkTopology
	{
        /// <summary>
        /// Translating to the index number on our AdjacentMatrix structure with specific node ID.
        /// </summary>
        /// <param name="NodeID">The node ID that want to translating.</param>
        /// <returns>The index on our AdjacentMatrix structure.</returns>
        public int NodeID2Index(int NodeID)
        {
            if (m_src_nodes != null)
            {
                if (m_src_nodes.Count == 0)
                    throw new Exception("NodeID2Index() Fail: There is 0 node on the network.");

                if (!m_src_nodes.Exists(x => x.ID == NodeID))
                    throw new Exception(string.Format("NodeID2Index() Fail: There is no match NodeID: {0} on our structure.", NodeID));

                return m_src_nodes.FindIndex(x => x.ID == NodeID);
            }
            else
            {
                if (Nodes.Count == 0)
                    throw new Exception("NodeID2Index() Fail: There is 0 node on the network.");

                if (!Nodes.Exists(x => x.ID == NodeID))
                        throw new Exception(string.Format("NodeID2Index() Fail: There is no match NodeID: {0} on our structure.", NodeID));

                return Nodes.FindIndex(x => x.ID == NodeID);
            }
        }

        /// <summary>
        /// Translating to the node ID with specific index number on our AdjacentMatrix structure.
        /// </summary>
        /// <param name="NodeIndex">The index number.</param>
        /// <returns>The node ID.</returns>
        public int NodeIndex2ID(int NodeIndex)
        {
            if (m_src_nodes != null)
            {
                if (m_src_nodes.Count == 0)
                    throw new Exception("NodeIndex2ID() Fail: There is 0 node on the network.");

                if (NodeIndex >= m_src_nodes.Count || NodeIndex < 0)
                    throw new Exception(string.Format("NodeIndex2ID() Fail: Out of range on our structure of the index: {0}.", NodeIndex));

                return m_src_nodes[NodeIndex].ID;
            }
            else
            {
                if (Nodes.Count == 0)
                    throw new Exception("NodeIndex2ID() Fail: There is 0 node on the network.");

                if (NodeIndex >= Nodes.Count || NodeIndex < 0)
                    throw new Exception(string.Format("NodeIndex2ID() Fail: Out of range on our structure of the index: {0}.", NodeIndex));

                return Nodes[NodeIndex].ID;
            }
        }

        /// <summary>
        /// Using Floyd-Warshar algorithm computing shortest path.
        /// </summary>
        public void ComputingShortestPath()
        {
            DataUtility.Log("Computing shortest path...");

            // Create the space of adjacent matrix
            AdjacentMatrix = null;
            AdjacentMatrix = new Adjacency[Nodes.Count, Nodes.Count];

            foreach (var edge in Edges)
            {
                AdjacentMatrix[NodeID2Index(edge.Node1), NodeID2Index(edge.Node2)] = new Adjacency() { Delay = edge.Delay, Length = edge.Length };
                AdjacentMatrix[NodeID2Index(edge.Node2), NodeID2Index(edge.Node1)] = new Adjacency() { Delay = edge.Delay, Length = edge.Length };
            }

            // Floyd-Warshall algorithm
            for (int i = 0; i < Nodes.Count; i++)
            {
                for (int j = 0; j < Nodes.Count; j++)
                {
                    for (int k = j + 1; k < Nodes.Count; k++)
                    {
                        if ((AdjacentMatrix[j, k] == null && AdjacentMatrix[j, i] != null && AdjacentMatrix[i, k] != null) ||
                            (AdjacentMatrix[j, k] != null && AdjacentMatrix[j, i] != null && AdjacentMatrix[i, k] != null && AdjacentMatrix[j, k].Length > AdjacentMatrix[j, i].Length + AdjacentMatrix[i, k].Length))
                        {
                            if (AdjacentMatrix[k, j] == null)
                            {
                                AdjacentMatrix[k, j] = new Adjacency();
                                AdjacentMatrix[j, k] = new Adjacency();
                            }

                            AdjacentMatrix[k, j].Length = AdjacentMatrix[j, k].Length = AdjacentMatrix[j, i].Length + AdjacentMatrix[i, k].Length;
                            AdjacentMatrix[k, j].Delay = AdjacentMatrix[j, k].Delay = AdjacentMatrix[j, i].Delay + AdjacentMatrix[i, k].Delay;
                            AdjacentMatrix[k, j].Predecessor = AdjacentMatrix[j, k].Predecessor = i;
                        }
                    }
                }
            }

            for (int i = 0; i < Nodes.Count; i++)
            {
                for (int j = 0; j < Nodes.Count; j++)
                {
                    if (AdjacentMatrix[i, j] != null)
                        AdjacentMatrix[i, j].PathCount = GetShortestPath(Nodes[i].ID, Nodes[j].ID).Count;

                    if (AdjacentMatrix[j, i] != null)
                        AdjacentMatrix[j, i].PathCount = GetShortestPath(Nodes[j].ID, Nodes[i].ID).Count;
                }
            }

            DataUtility.Log("Done.\n", false);
        }

        public void ComputeNodeDistrib()
        {
            nodeIDPathDistrib = new Dictionary<int, int>();

            for (int i = 0; i < Nodes.Count; i++)
            {
                for (int j = 0; j < Nodes.Count; j++)
                {
                    foreach (int id in GetShortestPath(Nodes[i].ID, Nodes[j].ID))
                    {
                        if (nodeIDPathDistrib.ContainsKey(id))
                            nodeIDPathDistrib[id]++;
                        else
                            nodeIDPathDistrib.Add(id, 1);
                    }
                }
            }
        }

        /// <summary>
        /// Return the shortest path from source node to destination node.
        /// </summary>
        /// <param name="SourceNodeId">The source node id.</param>
        /// <param name="DestinationNodeId">The destination node id.</param>
        /// <returns>The sequence of the node id, which is shortest path.</returns>
        public List<int> GetShortestPath(int SourceNodeId, int DestinationNodeId)
        {
            if (Nodes.Count == 0)
                throw new Exception("Path() Fail: There are 0 nodes in the network.");

            List<int> path = new List<int>() { NodeID2Index(SourceNodeId), NodeID2Index(DestinationNodeId) };

            for (int i = 0; i < path.Count - 1; i++)
            {
                if (AdjacentMatrix[path[i], path[i + 1]] != null &&
                    AdjacentMatrix[path[i], path[i + 1]].Predecessor != -1)
                {
                    path.Insert(i + 1, AdjacentMatrix[path[i], path[i + 1]].Predecessor);
                    i--;
                }
            }

            for (int i = 0; i < path.Count; i++)
                path[i] = NodeIndex2ID(path[i]);

            return path;
        }

        public int GetShortestPathCount(int SourceNodeId, int DestinationNodeId)
        {
            Adjacency adjacency = AdjacentMatrix[NodeID2Index(SourceNodeId), NodeID2Index(DestinationNodeId)];

            if (adjacency == null)
                return 0;
            else
                return adjacency.PathCount;
        }

        public void ComputingAllEccentricity()
        {
            DataUtility.Log("Computing all eccentricity value...");

            foreach (var node in Nodes)
                node.Eccentricity = Eccentricity(node.ID);

            DataUtility.Log("Done.\n", false);
        }

        /// <summary>
        /// Return the eccentricity value of the specific node ID on the network topology.
        /// </summary>
        /// <param name="NodeID">The node ID on the network topology.</param>
        /// <returns>The eccentricity value for the node ID on the network topology.</returns>
        public int Eccentricity(int NodeID)
        {
            int result = int.MinValue;

            foreach (int id in Nodes.Where(n => n.ID != NodeID).Select(n => n.ID))
            {
                List<int> path = GetShortestPath(NodeID, id);
                int nowCount = 0;

                if (path.Except(Nodes.Select(n => n.ID)).Count() == 0)
                    nowCount = path.Count;

                if (result < nowCount)
                    result = nowCount;
            }

            return result;
        }

        public void ComputingAllDegree()
        {
            DataUtility.Log("Computing all degree value...");

            foreach (var node in Nodes)
                node.Degree = Degree(node.ID);

            DataUtility.Log("Done.\n", false);
        }

        /// <summary>
        /// Retrun the degree value of the specific node ID on the network topology.
        /// </summary>
        /// <param name="NodeID">The node ID on the network topology.</param>
        /// <returns>The degree value for the node ID on the network topology.</returns>
        public int Degree(int NodeID)
        {
            return Edges.Where(n => n.Node1 == NodeID || n.Node2 == NodeID).ToList().Count;
        }

        /// <summary>
        /// Computing the clustering coefficeint of the node id on the network topology.
        /// </summary>
        /// <param name="NodeID">The node id on the network topology.</param>
        /// <returns>The clustering coefficeint value.</returns>
        public double ClusteringCoefficient(int NodeID)
        {
            List<int> neighbor = GetNeighborNodeIDs(NodeID);
            List<Edge> neighbor_edge_connect_set = new List<Edge>();

            neighbor_edge_connect_set.AddRange(Edges.Where(e => neighbor.Contains(e.Node1) && neighbor.Contains(e.Node2)));

            double max_edges = (neighbor.Count * (neighbor.Count - 1)) / 2;
            double neighbor_edge_count = neighbor_edge_connect_set.Count;

            if (max_edges > 0)
                return neighbor_edge_count / max_edges;
            else
                return 0;
        }

        public double ClusteringCoefficient(NetworkTopology Scope, int NodeID)
        {
            List<int> neighbor = GetNeighborNodeIDs(NodeID);
            List<Edge> neighbor_edge_connect_set = new List<Edge>();

            neighbor_edge_connect_set.AddRange(Edges.Where(e =>
                                                    Scope.Nodes[0].ID == e.Node1 && neighbor.Contains(e.Node2) ||
                                                    Scope.Nodes[0].ID == e.Node2 && neighbor.Contains(e.Node1)
                                               ));

            double max_edges = (neighbor.Count * (neighbor.Count - 1)) / 2;
            double neighbor_edge_count = neighbor_edge_connect_set.Count;

            if (max_edges > 0)
                return neighbor_edge_count / max_edges;
            else
                return 0;
        }

        /// <summary>
        /// Getting the neighbor node IDs list for the specific node ID on the network topology.
        /// </summary>
        /// <param name="NodeID">The node Id on the network topology.</param>
        /// <returns>The list of neighbors ID which side on the specific node ID.</returns>
        public List<int> GetNeighborNodeIDs(int NodeID)
        {
            List<int> result = Edges.Where(n => n.Node1 == NodeID).Select(n => n.Node2).ToList();

            result.AddRange(Edges.Where(n => n.Node2 == NodeID).Select(n => n.Node1).ToList());

            return result;
        }

        /// <summary>
        /// Finding the center of node id on the network topology.
        /// </summary>
        /// <param name="centerID">The center node id will output.</param>
        /// <returns>Do the network topology can find the center node id.</returns>
        public bool FindCenterNodeID(out int centerID, out int minE, bool isNeedRecompute = false)
        {
            DataUtility.Log("Finding center node...");
            minE = int.MaxValue;
            int eccentricity;
            centerID = -1;

            foreach (var node in Nodes)
            {
                if (isNeedRecompute)
                    node.Eccentricity = Eccentricity(node.ID);

                eccentricity = node.Eccentricity;

                if (minE > eccentricity && eccentricity != int.MinValue)
                {
                    minE = eccentricity;
                    centerID = node.ID;
                }
                else if (minE == eccentricity)
                {
                    int tmpCenter = centerID;
                    if (Nodes.Find(n => n.ID == tmpCenter).Degree > Nodes.Find(n => n.ID == node.ID).Degree)
                        centerID = node.ID;
                }
            }

            DataUtility.Log("Done.\n", false);

            return centerID != -1;
        }

        /// <summary>
        /// Operator overloading(-, minus) that define the complement set between the two network topologies.
        /// </summary>
        /// <param name="left_n">The minuend of the network topology.</param>
        /// <param name="right_n">The subtrahend of the network topology.</param>
        /// <returns>The complement set between the two network topologies.</returns>
        public static NetworkTopology operator -(NetworkTopology left_n, NetworkTopology right_n)
        {
            NetworkTopology result = new NetworkTopology(left_n.m_src_nodes);

            result.m_diameter = left_n.Diameter;
            result.Nodes = left_n.Nodes.Except(right_n.Nodes).ToList();
            result.Edges = left_n.Edges.Except(right_n.Edges).ToList();
            foreach (var n in right_n.Nodes)
                result.Edges.RemoveAll(e => e.Node1 == n.ID || e.Node2 == n.ID);

            result.AdjacentMatrix = left_n.AdjacentMatrix;

            return result;
        }

        /// <summary>
        /// Setting up the drawing control that draw network topology on the specific control.
        /// </summary>
        /// <param name="ctrl">The control to draw the network.</param>
        public void SetupDrawingControl(Control ctrl)
        {
            if (m_is_setup_control)
                throw new Exception("SetupDrawingControl() Fail: The control have been setted.");

            m_is_setup_control = true;

            // Changing the cursor.
            ctrl.Cursor = Cursors.NoMove2D;

            // Enabling DoubleBuffered.
            typeof(Control).InvokeMember("DoubleBuffered",
                                BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
                                null, ctrl, new object[] { true });

            // Handling the MouseWheel event to zoom in or zoom out network topology.
            ctrl.MouseWheel += (s, e) =>
            {
                // zoom in
                if (e.Delta > 0)
                {
                    m_scale_x += 0.1f;
                    m_scale_y += 0.1f;
                    (s as Control).Invalidate();
                }
                // zoom out
                else
                {
                    m_scale_x = (m_scale_x - 0.1f) > 0.1 ? (m_scale_x - 0.1f) : 0.1f;
                    m_scale_y = (m_scale_y - 0.1f) > 0.1 ? (m_scale_y - 0.1f) : 0.1f;
                    (s as Control).Invalidate();
                }
            };

            // Handling the MouseEnter event to focus the specific control.
            ctrl.MouseEnter += (s, e) =>
            {
                (s as Control).Focus();
            };

            // Handling the MouseLeave event to lost focus the specific control.
            ctrl.MouseLeave += (s, e) =>
            {
                (s as Control).Focus();
            };

            // Handling the MouseDown event to move the network topology.
            ctrl.MouseDown += (s, e) =>
            {
                if (e.Button == System.Windows.Forms.MouseButtons.Left)
                {
                    m_pre_move_x = e.Location.X;
                    m_pre_move_y = e.Location.Y;
                    m_is_mouse_down = true;
                }
            };

            // Handling the MouseUp event to move the network topology.
            ctrl.MouseUp += (s, e) =>
            {
                if (e.Button == System.Windows.Forms.MouseButtons.Left)
                {
                    m_move_x += e.Location.X - m_pre_move_x;
                    m_move_y += e.Location.Y - m_pre_move_y;
                    m_pre_move_x = e.Location.X;
                    m_pre_move_y = e.Location.Y;
                    (s as Control).Invalidate();
                    m_is_mouse_down = false;
                }
            };

            // Handling the MouseMove event to move the network topology.
            ctrl.MouseMove += (s, e) =>
            {
                if (m_is_mouse_down)
                {
                    m_move_x += e.Location.X - m_pre_move_x;
                    m_move_y += e.Location.Y - m_pre_move_y;
                    m_pre_move_x = e.Location.X;
                    m_pre_move_y = e.Location.Y;
                    (s as Control).Invalidate();
                }
            };

            // Handling the Resize event to redraw the network topology.
            ctrl.Resize += (s, e) =>
            {
                (s as Control).Invalidate();
            };

            // Handling the Paint event to pain the network topology.
            ctrl.Paint += (s, e) =>
            {
                // Using the BufferedGraphics to draw the network topology.
                using (BufferedGraphics bg = BufferedGraphicsManager.Current.Allocate(e.Graphics, e.ClipRectangle))
                {
                    bg.Graphics.Clear(Color.Gray);
                    bg.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;

                    // Setting up the transform to move or scale the network topology.
                    bg.Graphics.TranslateTransform(m_move_x, m_move_y);
                    bg.Graphics.ScaleTransform(m_scale_x, m_scale_y);

                    // Drawing the edge of the network topology.
                    foreach (var edge in Edges)
                        drawEdge(bg.Graphics, edge);

                    // Drawing the node of the network topology.
                    foreach (var node in Nodes)
                        drawNode(bg.Graphics, node);

                    // Drawing the demonstration of the symbol.
                    bg.Graphics.ResetTransform();
                    bg.Graphics.ScaleTransform(0.8f, 0.8f);
                    drawDemonstration(bg.Graphics);

                    // Starting render the graph to specific graphics.
                    bg.Render();
                }
            };
        }

        /// <summary>
        /// Drawing node of the network topology.
        /// </summary>
        /// <param name="graph">The graphic to draw on.</param>
        /// <param name="node">The node to draw on.</param>
        private void drawNode(Graphics graph, Node node)
        {
            float x = (float)node.Xpos;
            float y = (float)node.Ypos;
            string str;
            Brush brush;

            switch (node.Tracer)
            {
                case TracerType.None:
                    brush = DRAW_NORMAL_BRUSH;
                    break;
                case TracerType.Filtering:
                    brush = DRAW_FILTERING_BRUSH;
                    break;
                case TracerType.Marking:
                    brush = DRAW_MARKING_BRUSH;
                    break;
                case TracerType.Tunneling:
                    brush = DRAW_TUNNELING_BRUSH;
                    break;
                default:
                    brush = Brushes.White;
                    break;
            }

            switch (node.Type)
            {
#if !DEBUG
                case NodeType.Normal:
                    str = string.Empty;
                    break;
                case NodeType.Attacker:
                    str = "A";
                    break;
                case NodeType.Victim:
                    str = "V";
                    break;
#endif
                default:
                    str = node.ID.ToString();;
                    break;
            }

            graph.FillEllipse(brush, x, y, 30, 30);
#if DEBUG
            graph.DrawString(str, new Font(DRAW_FONT_FAMILY, 12), Brushes.White, x + 15 - 11, y + 15 - 11);
#else
            graph.DrawString(str, new Font(DRAW_FONT_FAMILY, 12), Brushes.White, x + 15 - 8, y + 15 - 11);
#endif
        }

        /// <summary>
        /// Drawing edge of the network topology.
        /// </summary>
        /// <param name="graph">The graphic to draw on.</param>
        /// <param name="edge">The edge to draw on.</param>
        private void drawEdge(Graphics graph, Edge edge)
        {
            Node node1 = Nodes.Find(n => n.ID == edge.Node1);
            Node node2 = Nodes.Find(n => n.ID == edge.Node2);

            graph.DrawLine(Pens.Black, (float)node1.Xpos + 15, (float)node1.Ypos + 15, (float)node2.Xpos + 15, (float)node2.Ypos + 15);
        }

        /// <summary>
        /// Drawing demonstration of the symbol on the network topology.
        /// </summary>
        /// <param name="graph">The graphic to draw on.</param>
        private void drawDemonstration(Graphics graph)
        {
            float width = 200;
            float height = 220;
            float left_top_x = graph.VisibleClipBounds.Width - width;
            float left_top_y = graph.VisibleClipBounds.Height - height;
            float margin = 10;
            float padding = 10;
            float now_row_height = 0;
            Font font = new Font(DRAW_FONT_FAMILY, 12);

            graph.FillRectangle(Brushes.DimGray, left_top_x, left_top_y, width - margin, height - margin);

            graph.FillEllipse(DRAW_NORMAL_BRUSH, left_top_x + padding, left_top_y + padding + now_row_height, 30, 30);
            graph.DrawString("Normal Node", font, Brushes.White, left_top_x + padding + 40 + 15 - 11, left_top_y + padding + now_row_height + 15 - 11);

            now_row_height += 40;
            graph.FillEllipse(DRAW_FILTERING_BRUSH, left_top_x + padding, left_top_y + padding + now_row_height, 30, 30);
            graph.DrawString("Filtering Node", font, Brushes.White, left_top_x + padding + 40 + 15 - 11, left_top_y + padding + now_row_height + 15 - 11);

            now_row_height += 40;
            graph.FillEllipse(DRAW_MARKING_BRUSH, left_top_x + padding, left_top_y + padding + now_row_height, 30, 30);
            graph.DrawString("Marking Node", font, Brushes.White, left_top_x + padding + 40 + 15 - 11, left_top_y + padding + now_row_height + 15 - 11);

            now_row_height += 40;
            graph.FillEllipse(DRAW_TUNNELING_BRUSH, left_top_x + padding, left_top_y + padding + now_row_height, 30, 30);
            graph.DrawString("Tunneling Node", font, Brushes.White, left_top_x + padding + 40 + 15 - 11, left_top_y + padding + now_row_height + 15 - 11);

            now_row_height += 40;
            graph.DrawString("V: Victim; A: Attacker", font, Brushes.White, left_top_x + padding + 15 - 11, left_top_y + padding + now_row_height + 15 - 11);
        }

        /// Return the poisson random number.
        /// </summary>
        /// <param name="lambda">Lambda.</param>
        /// <returns>Random number.</returns>
        public long Poisson(double lambda)
        {
            Random rd = new Random();
            long k = 0;
            double L = Math.Exp(-lambda), p = 1;
            double r;

            do
            {
                ++k;
                r = rd.NextDouble();
                p *= r;
            } while (p > L);

            return k == 1 ? k : --k;
        }
	}
}


text:
package org.terasology.reflection.reflect;

import java.lang.reflect.Field;

/**
 * A factory providing reflection abilities, such as object construction and field access.
 *
 * @author Immortius
 */
public interface ReflectFactory {

    <T> ObjectConstructor<T> createConstructor(Class<T> type) throws NoSuchMethodException;

    <T> FieldAccessor<T, ?> createFieldAccessor(Class<T> ownerType, Field field) throws InaccessibleFieldException;

    <T, U> FieldAccessor<T, U> createFieldAccessor(Class<T> ownerType, Field field, Class<U> fieldType) throws InaccessibleFieldException;
}


text:
title: How to Pretend Typing Super Fast in RStudio
subtitle: A blog post written during my presentation at rstudio::conf 2018
date: '2018-02-02'
slug: typing-fast
disable_mathjax: true
---

Right now I'm giving a talk at the RStudio Conference in San Diego. In my talk, I told the audience that I was going to write a blog post at the podium during my presentation. I only had 20 minutes in total for my presentation. Apparently it was impossible to type out a nontrivial post. But I want to show them my workflow of writing and publishing blog posts, so I cheated using the **rstudioapi** package to automatically "type" the post in RStudio for me.

## The rstudioapi package

The key idea is to use the function `rstudioapi::insertText()` to insert text in the RStudio source editor, and the editor context can be obtained from `rstudioapi::getSourceEditorContext()`. The rest of things to do is a plain `for` loop, in which you insert characters one by one, and use `Sys.sleep()` to pause occasionally (and randomly), otherwise it will be obviously bogus.

Below is a prototype of the function to automatically "type" a character vector into your RStudio source editor:

```r
rstudio_type = function(x) {
  ctx = rstudioapi::getSourceEditorContext()
  x = paste(x, collapse = '\n')  # concatenate by \n
  x = unlist(strsplit(x, ''))    # split into individual characters
  for (i in x) {
    rstudioapi::insertText(text = i, id = ctx$id)
    Sys.sleep(rbeta(1, 1, 9)/10)  # make delay time right-skewed
  }
}
```

## xfun::rstudio_type()

I polished up the code and included it in the **xfun** package as the function `xfun::rstudio_type()`. I added a few arguments to the function to make it feel more like a real human typing. In particular, the `mistake` argument controls how frequently you make mistakes (insert random strings that will be deleted shortly). Currently you have to install the development version of **xfun** to use this function:

```r
remotes::install_github('yihui/xfun')
```

## How did it work when I gave the talk?

I typed `go` in my R console, and hoped nobody saw it. The object `go` was created from a delayed assignment:

```r
delayedAssign('go', {
  Sys.sleep(3)
  xfun::rstudio_type(
    readLines('content/en/2018-02-02-typing-fast.md'),
    pause = function() rbeta(1, 1, 9)/60, mistake = .001, save = .005
  )
})
```

You may ask why not define a normal function, like `go = function() { ... }`? I didn't want to type `go()` in my console, because that would look suspicious to the audience whose eyes are really good, and they might know I called a function to do something. If I just type `go`, even if they saw it, I don't think they would so quickly think of delayed assignments in R, and they might think I was trying to print a certain object in R, but didn't see its value for some reason after I press Enter.

**Update on 2018-03-04**: The video of the talk is freely available [on the RStudio website](https://www.rstudio.com/resources/videos/create-and-maintain-websites-with-r-markdown-and-blogdown/).

[![Create and maintain websites with R Markdown and blogdown – RStudio](https://embedwistia-a.akamaihd.net/deliveries/3a89d37534901d8aea63adaa722e644c547345ce.jpg?image_play_button_size=2x&image_crop_resized=960x540&image_play_button=1&image_play_button_color=4287c7e0)](https://www.rstudio.com/resources/videos/create-and-maintain-websites-with-r-markdown-and-blogdown/?wvideo=zvnt290yte)

## Appendix: Does `yolo: true` work in blogdown?

Brandon Hurr asked me this question [on Twitter](https://twitter.com/bhive01/status/958543255955693574) a couple of days ago. Well, `yolo: true` in the **xaringan** package is essentially the Mustache Karl picture inserted on random slides. I can certainly make it work for **blogdown** (i.e., insert Karl's picture randomly in your blog posts), but I'd prefer not to, since **xaringan** is pretty much a personal package, and **blogdown** is not. I don't wish to push it too far.

That said, you have full freedom on your personal blog, so let met tell you the secret weapon. There is an unexported function `yolo()` in **xaringan**, and you can call it in an R code chunk, e.g.,

````markdown
```{r}
xaringan:::yolo()
```
````

It should give you what you want:

![Moustache Karl (TM)](https://github.com/yihui/xaringan/releases/download/v0.0.2/karl-moustache.jpg)


text:
package ru.job4j.array;

import java.util.Arrays;

/**
* ArrayDuplicate class.
* @author Eugene Lazarev mailto(helycoptrenicht@rambler.ru)
* @since 29.03.2017
*/
public class ArrayDuplicate {
	/**
	* Method returns new array without duplicates.
	* @param array - source array
	* @return new array without duplicates
	*/
	public String[] remove(String[] array) {
		int lastUniqueIdx = 0;
		for (int cursor = 1; cursor < array.length; cursor++) {
			boolean unique = true;
			for (int j = cursor - 1; j >= 0; j--) {
				if (array[cursor].equals(array[j])) {
					unique = false;
					break;
				}
			}

			if (unique) {
				array[++lastUniqueIdx] = array[cursor];
			}
		}
		return Arrays.copyOf(array, lastUniqueIdx + 1);
	}
}


text: Any help or tips would be greatly appreciated.


text:
import Ember from 'ember';
import { assert } from "ember-data/-private/debug";
import {
  _bind,
  _guard,
  _objectIsAlive
} from "ember-data/-private/system/store/common";

import {
  normalizeResponseHelper
} from "ember-data/-private/system/store/serializer-response";

import {
  serializerForAdapter
} from "ember-data/-private/system/store/serializers";

var Promise = Ember.RSVP.Promise;

function payloadIsNotBlank(adapterPayload) {
  if (Ember.isArray(adapterPayload)) {
    return true;
  } else {
    return Object.keys(adapterPayload || {}).length;
  }
}

export function _find(adapter, store, typeClass, id, internalModel, options) {
  var snapshot = internalModel.createSnapshot(options);
  var promise = adapter.findRecord(store, typeClass, id, snapshot);
  var serializer = serializerForAdapter(store, adapter, internalModel.type.modelName);
  var label = "DS: Handle Adapter#findRecord of " + typeClass + " with id: " + id;

  promise = Promise.resolve(promise, label);
  promise = _guard(promise, _bind(_objectIsAlive, store));

  return promise.then(function(adapterPayload) {
    assert("You made a `findRecord` request for a " + typeClass.typeClassKey + " with id " + id + ", but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload));
    return store._adapterRun(function() {
      var payload = normalizeResponseHelper(serializer, store, typeClass, adapterPayload, id, 'findRecord');
      assert('Ember Data expected the primary data returned from a `findRecord` response to be an object but instead it found an array.', !Array.isArray(payload.data));
      //TODO Optimize
      var record = store.push(payload);
      return record._internalModel;
    });
  }, function(error) {
    internalModel.notFound();
    if (internalModel.isEmpty()) {
      internalModel.unloadRecord();
    }

    throw error;
  }, "DS: Extract payload of '" + typeClass + "'");
}

export function _findMany(adapter, store, typeClass, ids, internalModels) {
  let snapshots = Ember.A(internalModels).invoke('createSnapshot');
  let promise = adapter.findMany(store, typeClass, ids, snapshots);
  let serializer = serializerForAdapter(store, adapter, typeClass.modelName);
  let label = "DS: Handle Adapter#findMany of " + typeClass;

  if (promise === undefined) {
    throw new Error('adapter.findMany returned undefined, this was very likely a mistake');
  }

  promise = Promise.resolve(promise, label);
  promise = _guard(promise, _bind(_objectIsAlive, store));

  return promise.then(function(adapterPayload) {
    assert("You made a `findMany` request for a " + typeClass.typeClassKey + " with ids " + ids + ", but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload));
    return store._adapterRun(function() {
      let payload = normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, 'findMany');
      //TODO Optimize, no need to materialize here
      let records = store.push(payload);
      let internalModels = new Array(records.length);

      for (let i = 0; i < records.length; i++) {
        internalModels[i] = records[i]._internalModel;
      }

      return internalModels;
    });
  }, null, "DS: Extract payload of " + typeClass);
}

export function _findHasMany(adapter, store, internalModel, link, relationship) {
  var snapshot = internalModel.createSnapshot();
  var typeClass = store.modelFor(relationship.type);
  var promise = adapter.findHasMany(store, snapshot, link, relationship);
  var serializer = serializerForAdapter(store, adapter, relationship.type);
  var label = "DS: Handle Adapter#findHasMany of " + internalModel + " : " + relationship.type;

  promise = Promise.resolve(promise, label);
  promise = _guard(promise, _bind(_objectIsAlive, store));
  promise = _guard(promise, _bind(_objectIsAlive, internalModel));

  return promise.then(function(adapterPayload) {
    assert("You made a `findHasMany` request for a " + internalModel.modelName + "'s `" + relationship.key + "` relationship, using link " + link + ", but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload));
    return store._adapterRun(function() {
      var payload = normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, 'findHasMany');
      //TODO Use a non record creating push
      var records = store.push(payload);
      var recordArray = records.map((record) => record._internalModel);
      recordArray.meta = payload.meta;
      return recordArray;
    });
  }, null, "DS: Extract payload of " + internalModel + " : hasMany " + relationship.type);
}

export function _findBelongsTo(adapter, store, internalModel, link, relationship) {
  var snapshot = internalModel.createSnapshot();
  var typeClass = store.modelFor(relationship.type);
  var promise = adapter.findBelongsTo(store, snapshot, link, relationship);
  var serializer = serializerForAdapter(store, adapter, relationship.type);
  var label = "DS: Handle Adapter#findBelongsTo of " + internalModel + " : " + relationship.type;

  promise = Promise.resolve(promise, label);
  promise = _guard(promise, _bind(_objectIsAlive, store));
  promise = _guard(promise, _bind(_objectIsAlive, internalModel));

  return promise.then(function(adapterPayload) {
    return store._adapterRun(function() {
      var payload = normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, 'findBelongsTo');

      if (!payload.data) {
        return null;
      }

      //TODO Optimize
      var record = store.push(payload);
      return record._internalModel;
    });
  }, null, "DS: Extract payload of " + internalModel + " : " + relationship.type);
}

export function _findAll(adapter, store, typeClass, sinceToken, options) {
  var modelName = typeClass.modelName;
  var recordArray = store.peekAll(modelName);
  var snapshotArray = recordArray.createSnapshot(options);
  var promise = adapter.findAll(store, typeClass, sinceToken, snapshotArray);
  var serializer = serializerForAdapter(store, adapter, modelName);
  var label = "DS: Handle Adapter#findAll of " + typeClass;

  promise = Promise.resolve(promise, label);
  promise = _guard(promise, _bind(_objectIsAlive, store));

  return promise.then(function(adapterPayload) {
    assert("You made a `findAll` request for " + typeClass.typeClassKey + "records, but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload));
    store._adapterRun(function() {
      var payload = normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, 'findAll');
      //TODO Optimize
      store.push(payload);
    });

    store.didUpdateAll(typeClass);
    return store.peekAll(modelName);
  }, null, "DS: Extract payload of findAll " + typeClass);
}

export function _query(adapter, store, typeClass, query, recordArray) {
  var modelName = typeClass.modelName;
  var promise = adapter.query(store, typeClass, query, recordArray);

  var serializer = serializerForAdapter(store, adapter, modelName);
  var label = "DS: Handle Adapter#query of " + typeClass;

  promise = Promise.resolve(promise, label);
  promise = _guard(promise, _bind(_objectIsAlive, store));

  return promise.then(function(adapterPayload) {
    var records, payload;
    store._adapterRun(function() {
      payload = normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, 'query');
      //TODO Optimize
      records = store.push(payload);
    });

    assert('The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use `store.queryRecord` to query for a single record.', Ember.isArray(records));
    recordArray.loadRecords(records, payload);
    return recordArray;

  }, null, "DS: Extract payload of query " + typeClass);
}

export function _queryRecord(adapter, store, typeClass, query) {
  var modelName = typeClass.modelName;
  var promise = adapter.queryRecord(store, typeClass, query);
  var serializer = serializerForAdapter(store, adapter, modelName);
  var label = "DS: Handle Adapter#queryRecord of " + typeClass;

  promise = Promise.resolve(promise, label);
  promise = _guard(promise, _bind(_objectIsAlive, store));

  return promise.then(function(adapterPayload) {
    assert("You made a `queryRecord` request for " + typeClass.typeClassKey + "records, with query `" + query + "`, but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload));
    var record;
    store._adapterRun(function() {
      var payload = normalizeResponseHelper(serializer, store, typeClass, adapterPayload, null, 'queryRecord');
      assert('`store.queryRecord` expected the adapter to return one record but the response from the adapter was empty.', payload.data);
      //TODO Optimize
      record = store.push(payload);
    });

    return record;

  }, null, "DS: Extract payload of queryRecord " + typeClass);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<body>
	<version>1</version>
	<timestamp>0x598930d4</timestamp>
	<link_advice_flag>true</link_advice_flag>
	<current_settings>
		<option name="--opt_for_speed" value="  --opt_for_speed=1"/>
		<option name="--opt_level" value="  --opt_level=off"/>
		<option name="--symdebug:dwarf" value=""/>
	</current_settings>
	<advice diag_code="00000" advice_type="curr_setting" option="" value="">advice: Current optimization/debug settings:  --opt_level=off  --opt_for_speed=1    -g</advice>
	<advice diag_code="27007" advice_type="opt_setting" option="--opt_level" value="3" action="gotoBuildOption:--opt_level">advice #27007-D: Detecting compilation without optimization. Recommend setting --opt_level=3. NOTE: debug ability will decrease.</advice>
	<advice diag_code="27010" advice_type="build_run" option="" value="" action="runOptAssistant">advice #27010-D: Not all available code size is being used. Recommend running Optimization Assistant to find best speed vs size setting (--opt_for_speed). Double-click to start.</advice>
</body>


text:
package services

import (
	"io"
	"database/sql"
	"crypto/rand"
	"crypto/md5"
	_ "github.com/go-sql-driver/mysql"
	"encoding/base64"
	"encoding/hex"
	"github.com/astaxie/beego/logs"
)

// create mysql database and database user.
// grant user to database
// return databaseName, userName, userPassword, error.
func createDatabaseAndUser(conn, planValue string) (*string, *string, *string, error) {
	logs.Info("The plan value is ", planValue)
	//初始化mysql的链接串
	db, err := sql.Open("mysql", conn)

	if err != nil {
		return nil, nil, nil, err
	}
	//测试是否能联通
	err = db.Ping()

	if err != nil {
		return nil, nil, nil, err
	}

	defer db.Close()

	//不能以instancdID为数据库名字,需要创建一个不带-的数据库名
	dbname := "d" + getguid()[0:15]
	_, err = db.Query("CREATE DATABASE " + dbname + " DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci")

	if err != nil {
		return nil, nil, nil, err
	}

	newusername := getguid()[0:15]
	newpassword := getguid()[0:15]

	_, err = db.Query("GRANT ALL ON " + dbname + ".* TO '" + newusername + "'@'%' IDENTIFIED BY '" + newpassword + "'")

	if err != nil {
		return nil, nil, nil, err
	}

	return &dbname, &newusername, &newpassword, err
}

// delete oracle database and database user.
// unGrant user to database
// return error.
func deleteDatabaseAndUser(conn, database, username string) error {
	//初始化mysql的链接串
	db, err := sql.Open("mysql", conn)
	if err != nil {
		return err
	}
	//测试是否能联通
	err = db.Ping()

	if err != nil {
		return err
	}

	defer db.Close()

	//删除数据库
	_, err = db.Query("DROP DATABASE " + database)

	if err != nil {
		return err
	}

	//删除用户
	_, err = db.Query("DROP USER " + username)

	if err != nil {
		return err
	}
	return nil
}

func getguid() string {
	b := make([]byte, 48)

	if _, err := io.ReadFull(rand.Reader, b); err != nil {
		return ""
	}
	return getmd5string(base64.URLEncoding.EncodeToString(b))
}

func getmd5string(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="base.css">
    <link rel="stylesheet" href="index.css">
</head>
<body>
123456
<script src="a.js"></script>
<script src="b.js"></script>
</body>
</html>