text:
The entire app would be built on Angularjs and BuildFire. Here in angularjs we will follow MVVM design pattern. BuildFire provide us multiple method by which we can fetch and update information on server. Methods included are
* buildfire.messaging
* buildfire.datastore
* buildfire.imageLib
* buildfire.components
* buildfire.services
* buildfire.spinner

In addition of these we would explore some of the angularJs and jquery based. There are some animation need to perform on app. [Angular-Animate](https://docs.angularjs.org/api/ngAnimate) is the angularjs module that will help us on those animation. [Angular-Route](https://docs.angularjs.org/api/ngRoute/service/$route) is used to navigate to different view in app. [WooCommerce REST API](http://woothemes.github.io/woocommerce-rest-api-docs) allows WooCommerce data to be created, read, updated, and deleted using JSON format.

## 2. Standardization:

**Lazy Loading:** We will use [ngInfiniteScroll](https://github.com/sroze/ngInfiniteScroll) for lazy loading. We will fetch 10 items on every single hit.

**Caching:** Caching will be done by buildfire API mainly. It includes Image caching API buildfire.imageLib.

**Refreshing:** Refresh will be enabled for this plugin.

**Styling:** UI Design will be done using [BuildFire-Style-Helper-Documentation](https://github.com/BuildFire/sdk/wiki/BuildFire-Style-Helper-Documentation). It has pre build style classes that we can use to improve UX of the plugin.

### 3. DataBase Model:
Database model is not directly exposed to the user. BuildFire provides buildfire.datastore to fetch and update data on server. It is black box for user. Think of it like for every user there will be separate database. The database should be unique as appId,pluginId, instanceId, tag and obj. Here the composite key of appId and pluginId should be every single app.

Here for wooCommerce plugin there will be only one tag.
* wooCommerce
**{tagname: wooCommerceInfo}:**

```
{
   content: {
        "carouselImages": [],
        "description": '<p> <br></p>',
        "storeURL": "",
        "consumerKey": "",
        "consumerSecret": ""
   },
   design: {
       "sectionListLayout": "",
       "itemListLayout": "",
       "itemDetailsBgImage": ""
   },
   settings: {
        "currency": ""
   }
}

```


text:
<?php

namespace Realtor\DictionaryBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * AdvertisingSource
 *
 * @ORM\Table(
 *      name="advertising_source",
 *      options={
 *          "comment"="справочник источников рекламы"
 *      }
 * )
 * @ORM\Entity
 *
 * @ORM\HasLifecycleCallbacks()
 */
class AdvertisingSource
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="outer_id", type="integer", nullable=true)
     */
    private $outerId;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var boolean
     *
     * @ORM\Column(name="is_active", type="boolean", options={"default":true})
     */
    private $isActive = true;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime")
     */
    private $createdAt;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set outerId
     *
     * @param integer $outerId
     * @return AdvertisingSource
     */
    public function setOuterId($outerId)
    {
        $this->outerId = $outerId;

        return $this;
    }

    /**
     * Get outerId
     *
     * @return integer
     */
    public function getOuterId()
    {
        return $this->outerId;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return AdvertisingSource
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set isActive
     *
     * @param boolean $isActive
     * @return AdvertisingSource
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * Get isActive
     *
     * @return boolean
     */
    public function getIsActive()
    {
        return $this->isActive;
    }

    /**
     * @ORM\PrePersist
     */
    public function setDateValue()
    {
        $this->createdAt = new \DateTime();
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    public function __toString()
    {
        return ($this->getName()) ? (string)$this->getName() : 'Новый источник рекламы';
    }
}

redpajama_set_name: RedPajamaGithub


text:
function dev = deviance(mu, y)
% Calculate deviance in the same way as lassoglm
% dev = deviance(mu, y)
%
% mu is the predicted value between 0 and 1
% y is the actual value, either 0 or 1

% By Daniel Golden (dgolden1 at stanford dot edu) July 2012
% $Id: deviance.m 217 2013-03-11 19:42:19Z dgolden $

% copied from lassoglm.m line 822
% lassoglm.m is kind of confusing, so I don't know if this formula is totally right

N = 1; % Number of "trials"; this should be 1
dev = 2*N.*(y.*log((y+(y==0))./mu) + (1-y).*log((1-y+(y==1))./(1-mu)));


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

// System.String
struct String_t;
// System.Reflection.ConstructorInfo
struct ConstructorInfo_t3542137334;

#include "mscorlib_System_Object837106420.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// System.MonoTypeInfo
struct  MonoTypeInfo_t2715305664  : public Il2CppObject
{
public:
	// System.String System.MonoTypeInfo::full_name
	String_t* ___full_name_0;
	// System.Reflection.ConstructorInfo System.MonoTypeInfo::default_ctor
	ConstructorInfo_t3542137334 * ___default_ctor_1;

public:
	inline static int32_t get_offset_of_full_name_0() { return static_cast<int32_t>(offsetof(MonoTypeInfo_t2715305664, ___full_name_0)); }
	inline String_t* get_full_name_0() const { return ___full_name_0; }
	inline String_t** get_address_of_full_name_0() { return &___full_name_0; }
	inline void set_full_name_0(String_t* value)
	{
		___full_name_0 = value;
		Il2CppCodeGenWriteBarrier(&___full_name_0, value);
	}

	inline static int32_t get_offset_of_default_ctor_1() { return static_cast<int32_t>(offsetof(MonoTypeInfo_t2715305664, ___default_ctor_1)); }
	inline ConstructorInfo_t3542137334 * get_default_ctor_1() const { return ___default_ctor_1; }
	inline ConstructorInfo_t3542137334 ** get_address_of_default_ctor_1() { return &___default_ctor_1; }
	inline void set_default_ctor_1(ConstructorInfo_t3542137334 * value)
	{
		___default_ctor_1 = value;
		Il2CppCodeGenWriteBarrier(&___default_ctor_1, value);
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="%level" name="ModernMT" packages="">
    <Appenders>
        <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="%root/node.log"
                                 filePattern="%root/node.%i.log.gz">
            <PatternLayout>
                <Pattern>%d %-5level %c [%t] %msg%n%throwable</Pattern>
            </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="1GB"/>
            </Policies>
            <DefaultRolloverStrategy max="20"/>
        </RollingRandomAccessFile>
    </Appenders>
    <Loggers>
        <Root level="%level">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </Root>
    </Loggers>
</Configuration>


text:
package org.sesy.coco.datacollector;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.sesy.coco.datacollector.database.Entry;
import org.sesy.coco.datacollector.log.ConfigureLog4J;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.os.SystemClock;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.util.Log;

public class CellWorker extends Service{

	private TelephonyManager tm;
	private int scanCounter;
    private String radioType;
    private String networkType;
    private String mcc;
    private String mnc;
    private List<NeighboringCellInfo> neighboringCellInfoList;
    private List<Cell> cellInfoList;
    private int cellId, lac, psc, signalStrength;

    private CountDownTimer timer;
    //private int gt, ob;
	Logger log;

	public static Map<Integer,String> networkTypeStr;
    static {
        networkTypeStr = new HashMap<Integer,String>();
        networkTypeStr.put(TelephonyManager.NETWORK_TYPE_GPRS, "GPRS");
        networkTypeStr.put(TelephonyManager.NETWORK_TYPE_EDGE, "EDGE");
        networkTypeStr.put(TelephonyManager.NETWORK_TYPE_UMTS, "UMTS");
        networkTypeStr.put(TelephonyManager.NETWORK_TYPE_HSDPA, "HSDPA");
        networkTypeStr.put(TelephonyManager.NETWORK_TYPE_HSUPA, "HSUPA");
        networkTypeStr.put(TelephonyManager.NETWORK_TYPE_HSPA, "HSPA");
        networkTypeStr.put(15, "HSPAP");	//NETWORK_TYPE_HSPAP
        networkTypeStr.put(TelephonyManager.NETWORK_TYPE_CDMA, "CDMA");
        networkTypeStr.put(TelephonyManager.NETWORK_TYPE_EVDO_0, "EVDO_0");
        networkTypeStr.put(TelephonyManager.NETWORK_TYPE_EVDO_A, "EVDO_A");
        networkTypeStr.put(12, "EVDO_B");	//NETWORK_TYPE_EVDO_B
        networkTypeStr.put(TelephonyManager.NETWORK_TYPE_1xRTT, "1xRTT");
        networkTypeStr.put(14, "EHRPD");	//NETWORK_TYPE_EHRPD
        networkTypeStr.put(TelephonyManager.NETWORK_TYPE_IDEN, "IDEN");
        networkTypeStr.put(13, "LTE");	//NETWORK_TYPE_LTE
        networkTypeStr.put(TelephonyManager.NETWORK_TYPE_UNKNOWN, "UNKNOWN");
    }

    @Override
	public void onCreate(){
		super.onCreate();

		log = Logger.getLogger(CellWorker.class);
        ConfigureLog4J.configure(this);
        LogManager.getRootLogger().setLevel((Level)Level.DEBUG);

	}

    @Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		WorkerService.cellTask = true;
		//gt = intent.getIntExtra("gt", 0);
		//ob = intent.getIntExtra("ob", 0);

		WorkerService.cellList.clear();
		cellInfoList = new ArrayList<Cell>();
		scanCounter = 0;

		log.info("Subtask Cell");

		tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

		timer = new CountDownTimer(31*1000, 3000) {

			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				log.info("Cell scan finished");
				WorkerService.cellTaskDone = true;
				stopSelf();
			}

			@Override
			public void onTick(long millisUntilFinished) {
				// TODO Auto-generated method stub
				if(scanCounter >= 0 && scanCounter <= 9){
					getCellInfos();
					scanCounter++;
					log.info("Subtask Cell scan started "+scanCounter);
				}
			}

		};

		timer.start();
		log.info("Subtask Cell scan started "+scanCounter);

		return START_NOT_STICKY;
	}

	private void getCellInfos(){
		long ts = SystemClock.elapsedRealtime() - WorkerService.metaTS;
		List<NeighboringCellInfo> list = tm.getNeighboringCellInfo();
		if(!list.isEmpty()){
			for (NeighboringCellInfo i : list) {
				int rssi = 0;
				switch(getNetworkClass(i.getNetworkType())){
				case 1:
					rssi = -113 + 2*(i.getRssi());	//GSM(TS 27.007): dBm = 2*ASU - 113, ASU in the range of 0..31 and 99
					break;
				case 2:
					rssi = -116 + i.getRssi();	//UMTS(TS 25.125): dBm = ASU - 116, ASU in the range of -5..91
					break;
				default:
					rssi = i.getRssi();
				}
	            Cell cell = new Cell(i.getCid(), i.getLac(), i.getPsc(), rssi, networkTypeStr.get(i.getNetworkType()));
	            Entry eobj = new Entry();
				String fp = cell.toString();
				Log.i("Cell FP", "Subtask cell_fp: " + fp);
				//eobj.setOB(ob);
				eobj.setTS(ts);
				//eobj.setGT(gt);
				eobj.setMT(Constants.STATUS_SENSOR_CELL);
				eobj.setFP(fp);
		        WorkerService.cellList.add(eobj);
	        }
		}
    }

    private int getNetworkClass(int networkType) {
        switch (networkType) {
            case -1:
                return -1;	//NONE
            case TelephonyManager.NETWORK_TYPE_GPRS:
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return 1;	//GSM
            case TelephonyManager.NETWORK_TYPE_UMTS:
            case TelephonyManager.NETWORK_TYPE_HSPA:
            case TelephonyManager.NETWORK_TYPE_HSDPA:
            case TelephonyManager.NETWORK_TYPE_HSUPA:
            case TelephonyManager.NETWORK_TYPE_HSPAP:
            	return 2;	//UMTS
            case TelephonyManager.NETWORK_TYPE_LTE:
            	return 5;	//LTE
            case TelephonyManager.NETWORK_TYPE_CDMA:
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
            case TelephonyManager.NETWORK_TYPE_EVDO_B:
            case TelephonyManager.NETWORK_TYPE_1xRTT:
            case TelephonyManager.NETWORK_TYPE_EHRPD:
                return 3;	//CDMA
            case TelephonyManager.NETWORK_TYPE_IDEN:
                return 4;	//IDEN
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
            default:
                return 0;	//UNKNOWN
        }
    }

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

    private class Cell {
        private int cid;	// Cell ID
        private int lac;	// Location Area Code
        private int psc;
        //private int mcc;	// Mobile Country Code
        //private int mnc;	// Mobile Network Code
        private int rssi;	// Signal Strength in dBm
        private String radioType;	// GSM or CDMA
        //private String type;	// Neighbour 'n' or Connected 'c'

        public Cell(int cid, int lac, int psc, int rssi, String radioType){
        	this.cid = cid;
        	this.lac = lac;
        	this.psc = psc;
        	//this.mcc = mcc;
        	//this.mnc = mnc;
        	this.rssi = rssi;
        	this.radioType = radioType;
        	//this.type= type;
        }
        @Override
        public String toString(){
        	return cid+"#"+radioType+"#"+lac+"#"+psc+"#"+rssi;
        }
    }

    /*private class GSMCellInfo extends CellInfo {
        private int cellId;
        private int lac;
        private int mcc;
        private int mnc;
        private int psc;
        private int signalStrength;

        @Override
        public String toString(){
        	return cellId+"#"+lac+"#"+signalStrength+"#"+mcc+"#"+mnc+"#"+psc;
        }
    }

    private class CDMACellInfo extends CellInfo {
        private int cellId;
        private int networkId;
        private int systemId;
        private int longitude;
        private int latitude;
        private int signalStrength;

        @Override
        public String toString(){
        	return cellId+"#"+networkId+"#"+signalStrength+"#"+longitude+"#"+latitude+"#"+systemId;
        }
    }

    private class LTECellInfo extends CellInfo {
        private int cellId;
        private int tac;
        private int mcc;
        private int mnc;
        private int pci;
        private int signalStrength;

        @Override
        public String toString(){
        	return cellId+"#"+tac+"#"+signalStrength+"#"+mcc+"#"+mnc+"#"+pci;
        }
    }

    private class UMTSCellInfo extends CellInfo {
        private int cellId;
        private int lac;
        private int mcc;
        private int mnc;
        private int psc;
        private int signalStrength;

        @Override
        public String toString(){
        	return cellId+"#"+lac+"#"+signalStrength+"#"+mcc+"#"+mnc+"#"+psc;
        }
    }

    private class IDENCellInfo extends CellInfo {
        private int cellId;
        private int lac;
        private int mcc;
        private int mnc;
        private int psc;
        private int signalStrength;

        @Override
        public String toString(){
        	return cellId+"#"+lac+"#"+signalStrength+"#"+mcc+"#"+mnc+"#"+psc;
        }
    }*/

}


text:
.. _install_existing:

Existing Project
=========================

If you already have an existing project that you'd like to integrate DMP into, follow the directions in this section.

Ensure you have Python 3.4+ installed (``python3 --version``).  If you are using virtual environments, be sure to activate that first.

Install Django, Mako, and DMP
-----------------------------------

DMP works with Django 1.9+, including the 2.0 releases.

The following will install all three dependencies:

.. tabs::

   .. group-tab:: Linux/Mac

        .. code:: bash

            pip3 install --upgrade django-mako-plus

   .. group-tab:: Windows

        .. code:: powershell

            pip install --upgrade django-mako-plus

If you need to add DMP to an existing Django project, you have two options:

1. Convert your project to the DMP-style structure. This switches your project over to the layout of a DMP project.
2. Keep your existing Django-style structure with minimal changes.

This section describes Option 1, which gives you the full benefit of the automatic DMP routing and midleware. If you just need to render templates using the Mako language (e.g. Option 2), jump to :ref:install_as_renderer.

Edit Your ``settings.py`` File:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Add ``django_mako_plus`` to the end of your ``INSTALLED_APPS`` list:

.. code-block:: python

    INSTALLED_APPS = [
        ...
        'django_mako_plus',
    ]

Add ``django_mako_plus.RequestInitMiddleware`` to your ``MIDDLEWARE`` list:

.. code-block:: python

    MIDDLEWARE = [
        ...
        'django_mako_plus.RequestInitMiddleware',
        ...
    ]

Add a logger to help you debug (optional but highly recommended!):

.. code-block:: python

    DEBUG_PROPAGATE_EXCEPTIONS = DEBUG  # SECURITY WARNING: never set this True on a live site
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'dmp_simple': {
                'format': '%(levelname)s::DMP %(message)s'
            },
        },
        'handlers': {
            'dmp_console':{
                'level':'DEBUG',
                'class':'logging.StreamHandler',
                'formatter': 'dmp_simple'
            },
        },
        'loggers': {
            'django_mako_plus': {
                'handlers': ['dmp_console'],
                'level': 'DEBUG',
                'propagate': False,
            },
        },
    }

Add the Django-Mako-Plus engine to the ``TEMPLATES`` list. Note that a
standard Django project already has the ``TEMPLATES =`` line and the 'django' template backend.  You probably just need to add the ``django_mako_plus`` dictionary below.

.. code-block:: python

    TEMPLATES = [
        {
            'NAME': 'django_mako_plus',
            'BACKEND': 'django_mako_plus.MakoTemplates',
            'OPTIONS': {
                # see the DMP documentation, "configuration options" page for available options
            },
        },
        {
            'NAME': 'django',
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            ...
        },
    ]

Add the following to serve your static files. Note that a standard Django project already has the first ``STATIC_URL =`` line.

.. code-block:: python

    STATIC_URL = '/static/'   # you probably already have this
    STATICFILES_DIRS = (
        # SECURITY WARNING: this next line must be commented out at deployment
        BASE_DIR,
    )
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

Clean out all the cached template files. This should be done **anytime you make a DMP change in settings.py**:

.. tabs::

   .. group-tab:: Linux/Mac

        .. code-block:: bash

            python3 manage.py dmp_cleanup

   .. group-tab:: Windows

        .. code-block:: powershell

            python manage.py dmp_cleanup

Enable the Django-Mako-Plus Router
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Add the Django-Mako-Plus router in your ``urls.py`` file (the default admin is also included here for completeness).

.. code-block:: python

    from django.conf.urls import url, include

    urlpatterns = [
        url('', include('django_mako_plus.urls')),
    ]

Create a DMP-Style App
-----------------------------------

Change to your project directory in the terminal/console, then create a new Django-Mako-Plus app with the following:

.. tabs::

   .. group-tab:: Linux/Mac

        .. code-block:: bash

            python3 manage.py dmp_startapp homepage

   .. group-tab:: Windows

        .. code-block:: powershell

            python manage.py dmp_startapp homepage

**After** the new ``homepage`` app is created, add your new app to the ``INSTALLED_APPS`` list in ``settings.py``:

Create a DMP-Style App
----------------------------------

Create a new Django-Mako-Plus app with the following:

.. tabs::

   .. group-tab:: Linux/Mac

        .. code:: bash

            python3 manage.py dmp_startapp homepage

   .. group-tab:: Windows

        .. code:: powershell

            python manage.py dmp_startapp homepage

**After** the new ``homepage`` app is created, open ``mysite/settings.py`` in your favorite editor and add to the ``INSTALLED_APPS`` list:

.. code:: python

    INSTALLED_APPS = [
        ...
        'homepage',
    ]

Congratulations. You're ready to go!

Load it Up!
----------------------------------

Start your web server with the following:

.. tabs::

   .. group-tab:: Linux/Mac

        .. code:: bash

            python3 manage.py runserver

   .. group-tab:: Windows

        .. code:: powershell

            python manage.py runserver

If you get a message about unapplied migrations, ignore it for now and continue.

Open your web browser to http://localhost:8000/. You should see a message welcoming you to the homepage app.

Once everything is working, skip ahead to the :ref:`tutorial`.

Subdirectory: /mysite/
-----------------------------------

This section is for those that need Django is a subdirectory, such as ``/mysite``. If your Django installation is at the root of your domain, skip this section.

In other words, suppose your Django site isn't the only thing on your server. Instead of the normal url pattern, ``http://www.yourdomain.com/``, your Django installation is at ``http://www.yourdomain.com/mysite/``. All apps are contained within this ``mysite/`` directory.

This is accomplished in the normal Django way. Adjust your ``urls.py`` file to include the prefix:

.. code:: python

    url('^mysite/', include('django_mako_plus.urls')),


text:
package com.heroyang.method;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.apache.commons.lang.StringUtils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONMapper {
	private static final JSONMapper DEFAULT_INSTANCE = new JSONMapper();

    private static ObjectMapper mapper;

    public JSONMapper() {
        mapper = new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        // 设置输入时忽略JSON字符串中存在而Java对象实际没有的属性
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
            false);
        mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES,
            false);
    }

    public static JSONMapper get() {
        return DEFAULT_INSTANCE;
    }

    /**
     * 如果JSON字符串为Null或"null"字符串,返回Null. 如果JSON字符串为"[]",返回空集合.
     * 如需读取集合如List/Map,且不是List<String>这种简单类型时使用如下语句: List<MyBean> beanList =
     * mapper.getMapper().readValue(listString, new
     * TypeReference<List<MyBean>>() {});
     */
    public <T> T fromJSON(String jsonString, Class<T> clazz) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }

        try {
            return mapper.readValue(jsonString, clazz);
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }

    public <T> T fromJSON(String jsonString, TypeReference<T> tf) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }

        try {
            return mapper.readValue(jsonString, tf);
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 如果对象为Null,返回"null". 如果集合为空集合,返回"[]".
     */
    public static String toJSON(Object object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (Throwable e) {
            return null;
        }
    }

    /**
     * 设置转换日期类型的format pattern,如果不设置默认打印Timestamp毫秒数.
     */
    public void setDateFormat(String pattern) {
        if (StringUtils.isNotBlank(pattern)) {
            DateFormat df = new SimpleDateFormat(pattern);
            mapper.setDateFormat(df);
        }
    }

    public void setDateFormat(DateFormat df) {
        if (null != df) {
            mapper.setDateFormat(df);
        }
    }

    /**
     * 取出Mapper做进一步的设置或使用其他序列化API.
     */
    public ObjectMapper getMapper() {
        return mapper;
    }

}


text:
#region MIT.
//
// Gorgon.
// Copyright (C) 2014 Michael Winsor
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Created: Monday, November 03, 2014 8:32:52 PM
//
#endregion

using System;
using System.Windows.Forms;
using Gorgon.Examples;
using Gorgon.UI;

namespace Graphics.Examples
{
    /// <summary>
    /// This is an example to show a developer how to create their own image codec for loading/saving images.
    ///
    /// A custom image codec may be implemented as a plug in that can be loaded dynamically, or statically within an application.  This example
    /// will focus on using a plug in to create a fairly useless image codec that will save only the red, green, blue and alpha channels as one
    /// channel per pixel.  That is, the first pixel will be the red channel, the second will be the green, etc...
    ///
    /// This application will be the UI for the image codec plug in and will do nothing more than load a DDS image, save it in our custom format
    /// and then load it as a texture for display in the window.
    /// </summary>
    internal static class Program
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        [STAThread]
        private static void Main()
        {
            try
            {
#if NET6_0_OR_GREATER
                Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
#endif
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                GorgonApplication.Run(new Form());
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
            }
        }
    }
}


text:
package Paws::MachineLearning::Evaluation;
  use Moose;
  has ComputeTime => (is => 'ro', isa => 'Int');
  has CreatedAt => (is => 'ro', isa => 'Str');
  has CreatedByIamUser => (is => 'ro', isa => 'Str');
  has EvaluationDataSourceId => (is => 'ro', isa => 'Str');
  has EvaluationId => (is => 'ro', isa => 'Str');
  has FinishedAt => (is => 'ro', isa => 'Str');
  has InputDataLocationS3 => (is => 'ro', isa => 'Str');
  has LastUpdatedAt => (is => 'ro', isa => 'Str');
  has Message => (is => 'ro', isa => 'Str');
  has MLModelId => (is => 'ro', isa => 'Str');
  has Name => (is => 'ro', isa => 'Str');
  has PerformanceMetrics => (is => 'ro', isa => 'Paws::MachineLearning::PerformanceMetrics');
  has StartedAt => (is => 'ro', isa => 'Str');
  has Status => (is => 'ro', isa => 'Str');
1;

### main pod documentation begin ###

=head1 NAME

Paws::MachineLearning::Evaluation

=head1 USAGE

This class represents one of two things:

=head3 Arguments in a call to a service

Use the attributes of this class as arguments to methods. You shouldn't make instances of this class.
Each attribute should be used as a named argument in the calls that expect this type of object.

As an example, if Att1 is expected to be a Paws::MachineLearning::Evaluation object:

  $service_obj->Method(Att1 => { ComputeTime => $value, ..., Status => $value  });

=head3 Results returned from an API call

Use accessors for each attribute. If Att1 is expected to be an Paws::MachineLearning::Evaluation object:

  $result = $service_obj->Method(...);
  $result->Att1->ComputeTime

=head1 DESCRIPTION

Represents the output of C<GetEvaluation> operation.

The content consists of the detailed metadata and data file information
and the current status of the C<Evaluation>.

=head1 ATTRIBUTES

=head2 ComputeTime => Int

=head2 CreatedAt => Str

  The time that the C<Evaluation> was created. The time is expressed in
epoch time.

=head2 CreatedByIamUser => Str

  The AWS user account that invoked the evaluation. The account type can
be either an AWS root account or an AWS Identity and Access Management
(IAM) user account.

=head2 EvaluationDataSourceId => Str

  The ID of the C<DataSource> that is used to evaluate the C<MLModel>.

=head2 EvaluationId => Str

  The ID that is assigned to the C<Evaluation> at creation.

=head2 FinishedAt => Str

=head2 InputDataLocationS3 => Str

  The location and name of the data in Amazon Simple Storage Server
(Amazon S3) that is used in the evaluation.

=head2 LastUpdatedAt => Str

  The time of the most recent edit to the C<Evaluation>. The time is
expressed in epoch time.

=head2 Message => Str

  A description of the most recent details about evaluating the
C<MLModel>.

=head2 MLModelId => Str

  The ID of the C<MLModel> that is the focus of the evaluation.

=head2 Name => Str

  A user-supplied name or description of the C<Evaluation>.

=head2 PerformanceMetrics => L<Paws::MachineLearning::PerformanceMetrics>

  Measurements of how well the C<MLModel> performed, using observations
referenced by the C<DataSource>. One of the following metrics is
returned, based on the type of the C<MLModel>:

=over

=item *

BinaryAUC: A binary C<MLModel> uses the Area Under the Curve (AUC)
technique to measure performance.

=item *

RegressionRMSE: A regression C<MLModel> uses the Root Mean Square Error
(RMSE) technique to measure performance. RMSE measures the difference
between predicted and actual values for a single variable.

=item *

MulticlassAvgFScore: A multiclass C<MLModel> uses the F1 score
technique to measure performance.

=back

For more information about performance metrics, please see the Amazon
Machine Learning Developer Guide.

=head2 StartedAt => Str

=head2 Status => Str

  The status of the evaluation. This element can have one of the
following values:

=over

=item * C<PENDING> - Amazon Machine Learning (Amazon ML) submitted a
request to evaluate an C<MLModel>.

=item * C<INPROGRESS> - The evaluation is underway.

=item * C<FAILED> - The request to evaluate an C<MLModel> did not run
to completion. It is not usable.

=item * C<COMPLETED> - The evaluation process completed successfully.

=item * C<DELETED> - The C<Evaluation> is marked as deleted. It is not
usable.

=back

=head1 SEE ALSO

This class forms part of L<Paws>, describing an object used in L<Paws::MachineLearning>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
// The MIT License (MIT)
//
// Copyright (c) 2021 Henk-Jan Lebbink
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

namespace AsmTools
{
    using System;

    [Flags]
    public enum AssemblerEnum
    {
        UNKNOWN = 0,
        MASM = 1 << 0,
        NASM_INTEL = 1 << 1,
        NASM_ATT = 1 << 2,
        ALL = NASM_INTEL | NASM_ATT | MASM,
        AUTO_DETECT = 1 << 3,
    }

    public static partial class AsmSourceTools
    {
        public static AssemblerEnum ParseAssembler(string str, bool strIsCapitals)
        {
            if (string.IsNullOrEmpty(str))
            {
                return AssemblerEnum.UNKNOWN;
            }
            AssemblerEnum result = AssemblerEnum.UNKNOWN;

            foreach (string str2 in ToCapitals(str, strIsCapitals).Split(','))
            {
                switch (str2.Trim())
                {
                    case "MASM": result |= AssemblerEnum.MASM; break;
                    case "NASM": result |= AssemblerEnum.NASM_INTEL; break;
                }
            }
            return result;
        }
    }
}


text:
package com.me.touchfootball2.gameplay;

import com.me.touchfootball2.gameplay.Player.Behavior;

public interface Action
{
	Behavior selectAction();
}


text:
import angular from 'angular';
import SERVICES_FILTER_MODULE from '../../../services/filter/filter-module';
import SERVICES_STATE_MODULE from '../../../services/state/state-module';

import FilterMonitor from './filter-monitor-directive';

const MODULE_NAME = 'data-prep.filter-monitor';

/**
 * @ngdoc object
 * @name data-prep.filter-monitor
 * @description This module contains the controller and directives to manage the filter list
 * @requires data-prep.services.filter
 * @requires data-prep.services.state
 */
angular.module(MODULE_NAME,
	[
		SERVICES_FILTER_MODULE,
		SERVICES_STATE_MODULE,
	])
    .directive('filterMonitor', FilterMonitor);

export default MODULE_NAME;


text:
(function(tinymce) {
	// Shorten names
	var Event = tinymce.dom.Event,
		isIE = tinymce.isIE,
		isGecko = tinymce.isGecko,
		isOpera = tinymce.isOpera,
		each = tinymce.each,
		extend = tinymce.extend,
		TRUE = true,
		FALSE = false;

	function cloneFormats(node) {
		var clone, temp, inner;

		do {
			if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(node.nodeName)) {
				if (clone) {
					temp = node.cloneNode(false);
					temp.appendChild(clone);
					clone = temp;
				} else {
					clone = inner = node.cloneNode(false);
				}

				clone.removeAttribute('id');
			}
		} while (node = node.parentNode);

		if (clone)
			return {wrapper : clone, inner : inner};
	};

	// Checks if the selection/caret is at the end of the specified block element
	function isAtEnd(rng, par) {
		var rng2 = par.ownerDocument.createRange();

		rng2.setStart(rng.endContainer, rng.endOffset);
		rng2.setEndAfter(par);

		// Get number of characters to the right of the cursor if it's zero then we are at the end and need to merge the next block element
		return rng2.cloneContents().textContent.length == 0;
	};

	function splitList(selection, dom, li) {
		var listBlock, block;

		if (dom.isEmpty(li)) {
			listBlock = dom.getParent(li, 'ul,ol');

			if (!dom.getParent(listBlock.parentNode, 'ul,ol')) {
				dom.split(listBlock, li);
				block = dom.create('p', 0, '
');
				dom.replace(block, li);
				selection.select(block, 1);
			}

			return FALSE;
		}

		return TRUE;
	};

	/**
	 * This is a internal class and no method in this class should be called directly form the out side.
	 */
	tinymce.create('tinymce.ForceBlocks', {
		ForceBlocks : function(ed) {
			var t = this, s = ed.settings, elm;

			t.editor = ed;
			t.dom = ed.dom;
			elm = (s.forced_root_block || 'p').toLowerCase();
			s.element = elm.toUpperCase();

			ed.onPreInit.add(t.setup, t);
		},

		setup : function() {
			var t = this, ed = t.editor, s = ed.settings, dom = ed.dom, selection = ed.selection, blockElements = ed.schema.getBlockElements();

			// Force root blocks
			if (s.forced_root_block) {
				function addRootBlocks() {
					var node = selection.getStart(), rootNode = ed.getBody(), rng, startContainer, startOffset, endContainer, endOffset, rootBlockNode, tempNode, offset = -0xFFFFFF;

					if (!node || node.nodeType !== 1)
						return;

					// Check if node is wrapped in block
					while (node != rootNode) {
						if (blockElements[node.nodeName])
							return;

						node = node.parentNode;
					}

					// Get current selection
					rng = selection.getRng();
					if (rng.setStart) {
						startContainer = rng.startContainer;
						startOffset = rng.startOffset;
						endContainer = rng.endContainer;
						endOffset = rng.endOffset;
					} else {
						// Force control range into text range
						if (rng.item) {
							rng = ed.getDoc().body.createTextRange();
							rng.moveToElementText(rng.item(0));
						}

						tmpRng = rng.duplicate();
						tmpRng.collapse(true);
						startOffset = tmpRng.move('character', offset) * -1;

						if (!tmpRng.collapsed) {
							tmpRng = rng.duplicate();
							tmpRng.collapse(false);
							endOffset = (tmpRng.move('character', offset) * -1) - startOffset;
						}
					}

					// Wrap non block elements and text nodes
					for (node = rootNode.firstChild; node; node) {
						if (node.nodeType === 3 || (node.nodeType == 1 && !blockElements[node.nodeName])) {
							if (!rootBlockNode) {
								rootBlockNode = dom.create(s.forced_root_block);
								node.parentNode.insertBefore(rootBlockNode, node);
							}

							tempNode = node;
							node = node.nextSibling;
							rootBlockNode.appendChild(tempNode);
						} else {
							rootBlockNode = null;
							node = node.nextSibling;
						}
					}

					if (rng.setStart) {
						rng.setStart(startContainer, startOffset);
						rng.setEnd(endContainer, endOffset);
						selection.setRng(rng);
					} else {
						try {
							rng = ed.getDoc().body.createTextRange();
							rng.moveToElementText(rootNode);
							rng.collapse(true);
							rng.moveStart('character', startOffset);

							if (endOffset > 0)
								rng.moveEnd('character', endOffset);

							rng.select();
						} catch (ex) {
							// Ignore
						}
					}

					ed.nodeChanged();
				};

				ed.onKeyUp.add(addRootBlocks);
				ed.onClick.add(addRootBlocks);
			}

			if (s.force_br_newlines) {
				// Force IE to produce BRs on enter
				if (isIE) {
					ed.onKeyPress.add(function(ed, e) {
						var n;

						if (e.keyCode == 13 && selection.getNode().nodeName != 'LI') {
							selection.setContent('
 ', {format : 'raw'});
							n = dom.get('__');
							n.removeAttribute('id');
							selection.select(n);
							selection.collapse();
							return Event.cancel(e);
						}
					});
				}
			}

			if (s.force_p_newlines) {
				if (!isIE) {
					ed.onKeyPress.add(function(ed, e) {
						if (e.keyCode == 13 && !e.shiftKey && !t.insertPara(e))
							Event.cancel(e);
					});
				} else {
					// Ungly hack to for IE to preserve the formatting when you press
					// enter at the end of a block element with formatted contents
					// This logic overrides the browsers default logic with
					// custom logic that enables us to control the output
					tinymce.addUnload(function() {
						t._previousFormats = 0; // Fix IE leak
					});

					ed.onKeyPress.add(function(ed, e) {
						t._previousFormats = 0;

						// Clone the current formats, this will later be applied to the new block contents
						if (e.keyCode == 13 && !e.shiftKey && ed.selection.isCollapsed() && s.keep_styles)
							t._previousFormats = cloneFormats(ed.selection.getStart());
					});

					ed.onKeyUp.add(function(ed, e) {
						// Let IE break the element and the wrap the new caret location in the previous formats
						if (e.keyCode == 13 && !e.shiftKey) {
							var parent = ed.selection.getStart(), fmt = t._previousFormats;

							// Parent is an empty block
							if (!parent.hasChildNodes() && fmt) {
								parent = dom.getParent(parent, dom.isBlock);

								if (parent && parent.nodeName != 'LI') {
									parent.innerHTML = '';

									if (t._previousFormats) {
										parent.appendChild(fmt.wrapper);
										fmt.inner.innerHTML = '\uFEFF';
									} else
										parent.innerHTML = '\uFEFF';

									selection.select(parent, 1);
									selection.collapse(true);
									ed.getDoc().execCommand('Delete', false, null);
									t._previousFormats = 0;
								}
							}
						}
					});
				}

				if (isGecko) {
					ed.onKeyDown.add(function(ed, e) {
						if ((e.keyCode == 8 || e.keyCode == 46) && !e.shiftKey)
							t.backspaceDelete(e, e.keyCode == 8);
					});
				}
			}

			// Workaround for missing shift+enter support, http://bugs.webkit.org/show_bug.cgi?id=16973
			if (tinymce.isWebKit) {
				function insertBr(ed) {
					var rng = selection.getRng(), br, div = dom.create('div', null, ' '), divYPos, vpHeight = dom.getViewPort(ed.getWin()).h;

					// Insert BR element
					rng.insertNode(br = dom.create('br'));

					// Place caret after BR
					rng.setStartAfter(br);
					rng.setEndAfter(br);
					selection.setRng(rng);

					// Could not place caret after BR then insert an nbsp entity and move the caret
					if (selection.getSel().focusNode == br.previousSibling) {
						selection.select(dom.insertAfter(dom.doc.createTextNode('\u00a0'), br));
						selection.collapse(TRUE);
					}

					// Create a temporary DIV after the BR and get the position as it
					// seems like getPos() returns 0 for text nodes and BR elements.
					dom.insertAfter(div, br);
					divYPos = dom.getPos(div).y;
					dom.remove(div);

					// Scroll to new position, scrollIntoView can't be used due to bug: http://bugs.webkit.org/show_bug.cgi?id=16117
					if (divYPos > vpHeight) // It is not necessary to scroll if the DIV is inside the view port.
						ed.getWin().scrollTo(0, divYPos);
				};

				ed.onKeyPress.add(function(ed, e) {
					if (e.keyCode == 13 && (e.shiftKey || (s.force_br_newlines && !dom.getParent(selection.getNode(), 'h1,h2,h3,h4,h5,h6,ol,ul')))) {
						insertBr(ed);
						Event.cancel(e);
					}
				});
			}

			// IE specific fixes
			if (isIE) {
				// Replaces IE:s auto generated paragraphs with the specified element name
				if (s.element != 'P') {
					ed.onKeyPress.add(function(ed, e) {
						t.lastElm = selection.getNode().nodeName;
					});

					ed.onKeyUp.add(function(ed, e) {
						var bl, n = selection.getNode(), b = ed.getBody();

						if (b.childNodes.length === 1 && n.nodeName == 'P') {
							n = dom.rename(n, s.element);
							selection.select(n);
							selection.collapse();
							ed.nodeChanged();
						} else if (e.keyCode == 13 && !e.shiftKey && t.lastElm != 'P') {
							bl = dom.getParent(n, 'p');

							if (bl) {
								dom.rename(bl, s.element);
								ed.nodeChanged();
							}
						}
					});
				}
			}
		},

		getParentBlock : function(n) {
			var d = this.dom;

			return d.getParent(n, d.isBlock);
		},

		insertPara : function(e) {
			var t = this, ed = t.editor, dom = ed.dom, d = ed.getDoc(), se = ed.settings, s = ed.selection.getSel(), r = s.getRangeAt(0), b = d.body;
			var rb, ra, dir, sn, so, en, eo, sb, eb, bn, bef, aft, sc, ec, n, vp = dom.getViewPort(ed.getWin()), y, ch, car;

			ed.undoManager.beforeChange();

			// If root blocks are forced then use Operas default behavior since it's really good
// Removed due to bug: #1853816
//			if (se.forced_root_block && isOpera)
//				return TRUE;

			// Setup before range
			rb = d.createRange();

			// If is before the first block element and in body, then move it into first block element
			rb.setStart(s.anchorNode, s.anchorOffset);
			rb.collapse(TRUE);

			// Setup after range
			ra = d.createRange();

			// If is before the first block element and in body, then move it into first block element
			ra.setStart(s.focusNode, s.focusOffset);
			ra.collapse(TRUE);

			// Setup start/end points
			dir = rb.compareBoundaryPoints(rb.START_TO_END, ra) < 0;
			sn = dir ? s.anchorNode : s.focusNode;
			so = dir ? s.anchorOffset : s.focusOffset;
			en = dir ? s.focusNode : s.anchorNode;
			eo = dir ? s.focusOffset : s.anchorOffset;

			// If selection is in empty table cell
			if (sn === en && /^(TD|TH)$/.test(sn.nodeName)) {
				if (sn.firstChild.nodeName == 'BR')
					dom.remove(sn.firstChild); // Remove BR

				// Create two new block elements
				if (sn.childNodes.length == 0) {
					ed.dom.add(sn, se.element, null, '
');
					aft = ed.dom.add(sn, se.element, null, '
');
				} else {
					n = sn.innerHTML;
					sn.innerHTML = '';
					ed.dom.add(sn, se.element, null, n);
					aft = ed.dom.add(sn, se.element, null, '
');
				}

				// Move caret into the last one
				r = d.createRange();
				r.selectNodeContents(aft);
				r.collapse(1);
				ed.selection.setRng(r);

				return FALSE;
			}

			// If the caret is in an invalid location in FF we need to move it into the first block
			if (sn == b && en == b && b.firstChild && ed.dom.isBlock(b.firstChild)) {
				sn = en = sn.firstChild;
				so = eo = 0;
				rb = d.createRange();
				rb.setStart(sn, 0);
				ra = d.createRange();
				ra.setStart(en, 0);
			}

			// If the body is totally empty add a BR element this might happen on webkit
			if (!d.body.hasChildNodes()) {
				d.body.appendChild(dom.create('br'));
			}

			// Never use body as start or end node
			sn = sn.nodeName == "HTML" ? d.body : sn; // Fix for Opera bug: https://bugs.opera.com/show_bug.cgi?id=273224&comments=yes
			sn = sn.nodeName == "BODY" ? sn.firstChild : sn;
			en = en.nodeName == "HTML" ? d.body : en; // Fix for Opera bug: https://bugs.opera.com/show_bug.cgi?id=273224&comments=yes
			en = en.nodeName == "BODY" ? en.firstChild : en;

			// Get start and end blocks
			sb = t.getParentBlock(sn);
			eb = t.getParentBlock(en);
			bn = sb ? sb.nodeName : se.element; // Get block name to create

			// Return inside list use default browser behavior
			if (n = t.dom.getParent(sb, 'li,pre')) {
				if (n.nodeName == 'LI')
					return splitList(ed.selection, t.dom, n);

				return TRUE;
			}

			// If caption or absolute layers then always generate new blocks within
			if (sb && (sb.nodeName == 'CAPTION' || /absolute|relative|fixed/gi.test(dom.getStyle(sb, 'position', 1)))) {
				bn = se.element;
				sb = null;
			}

			// If caption or absolute layers then always generate new blocks within
			if (eb && (eb.nodeName == 'CAPTION' || /absolute|relative|fixed/gi.test(dom.getStyle(sb, 'position', 1)))) {
				bn = se.element;
				eb = null;
			}

			// Use P instead
			if (/(TD|TABLE|TH|CAPTION)/.test(bn) || (sb && bn == "DIV" && /left|right/gi.test(dom.getStyle(sb, 'float', 1)))) {
				bn = se.element;
				sb = eb = null;
			}

			// Setup new before and after blocks
			bef = (sb && sb.nodeName == bn) ? sb.cloneNode(0) : ed.dom.create(bn);
			aft = (eb && eb.nodeName == bn) ? eb.cloneNode(0) : ed.dom.create(bn);

			// Remove id from after clone
			aft.removeAttribute('id');

			// Is header and cursor is at the end, then force paragraph under
			if (/^(H[1-6])$/.test(bn) && isAtEnd(r, sb))
				aft = ed.dom.create(se.element);

			// Find start chop node
			n = sc = sn;
			do {
				if (n == b || n.nodeType == 9 || t.dom.isBlock(n) || /(TD|TABLE|TH|CAPTION)/.test(n.nodeName))
					break;

				sc = n;
			} while ((n = n.previousSibling ? n.previousSibling : n.parentNode));

			// Find end chop node
			n = ec = en;
			do {
				if (n == b || n.nodeType == 9 || t.dom.isBlock(n) || /(TD|TABLE|TH|CAPTION)/.test(n.nodeName))
					break;

				ec = n;
			} while ((n = n.nextSibling ? n.nextSibling : n.parentNode));

			// Place first chop part into before block element
			if (sc.nodeName == bn)
				rb.setStart(sc, 0);
			else
				rb.setStartBefore(sc);

			rb.setEnd(sn, so);
			bef.appendChild(rb.cloneContents() || d.createTextNode('')); // Empty text node needed for Safari

			// Place secnd chop part within new block element
			try {
				ra.setEndAfter(ec);
			} catch(ex) {
				//console.debug(s.focusNode, s.focusOffset);
			}

			ra.setStart(en, eo);
			aft.appendChild(ra.cloneContents() || d.createTextNode('')); // Empty text node needed for Safari

			// Create range around everything
			r = d.createRange();
			if (!sc.previousSibling && sc.parentNode.nodeName == bn) {
				r.setStartBefore(sc.parentNode);
			} else {
				if (rb.startContainer.nodeName == bn && rb.startOffset == 0)
					r.setStartBefore(rb.startContainer);
				else
					r.setStart(rb.startContainer, rb.startOffset);
			}

			if (!ec.nextSibling && ec.parentNode.nodeName == bn)
				r.setEndAfter(ec.parentNode);
			else
				r.setEnd(ra.endContainer, ra.endOffset);

			// Delete and replace it with new block elements
			r.deleteContents();

			if (isOpera)
				ed.getWin().scrollTo(0, vp.y);

			// Never wrap blocks in blocks
			if (bef.firstChild && bef.firstChild.nodeName == bn)
				bef.innerHTML = bef.firstChild.innerHTML;

			if (aft.firstChild && aft.firstChild.nodeName == bn)
				aft.innerHTML = aft.firstChild.innerHTML;

			function appendStyles(e, en) {
				var nl = [], nn, n, i;

				e.innerHTML = '';

				// Make clones of style elements
				if (se.keep_styles) {
					n = en;
					do {
						// We only want style specific elements
						if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(n.nodeName)) {
							nn = n.cloneNode(FALSE);
							dom.setAttrib(nn, 'id', ''); // Remove ID since it needs to be unique
							nl.push(nn);
						}
					} while (n = n.parentNode);
				}

				// Append style elements to aft
				if (nl.length > 0) {
					for (i = nl.length - 1, nn = e; i >= 0; i--)
						nn = nn.appendChild(nl[i]);

					// Padd most inner style element
					nl[0].innerHTML = isOpera ? '\u00a0' : '
'; // Extra space for Opera so that the caret can move there
					return nl[0]; // Move caret to most inner element
				} else
					e.innerHTML = isOpera ? '\u00a0' : '
'; // Extra space for Opera so that the caret can move there
			};

			// Padd empty blocks
			if (dom.isEmpty(bef))
				appendStyles(bef, sn);

			// Fill empty afterblook with current style
			if (dom.isEmpty(aft))
				car = appendStyles(aft, en);

			// Opera needs this one backwards for older versions
			if (isOpera && parseFloat(opera.version()) < 9.5) {
				r.insertNode(bef);
				r.insertNode(aft);
			} else {
				r.insertNode(aft);
				r.insertNode(bef);
			}

			// Normalize
			aft.normalize();
			bef.normalize();

			// Move cursor and scroll into view
			ed.selection.select(aft, true);
			ed.selection.collapse(true);

			// scrollIntoView seems to scroll the parent window in most browsers now including FF 3.0b4 so it's time to stop using it and do it our selfs
			y = ed.dom.getPos(aft).y;
			//ch = aft.clientHeight;

			// Is element within viewport
			if (y < vp.y || y + 25 > vp.y + vp.h) {
				ed.getWin().scrollTo(0, y < vp.y ? y : y - vp.h + 25); // Needs to be hardcoded to roughly one line of text if a huge text block is broken into two blocks

				/*console.debug(
					'Element: y=' + y + ', h=' + ch + ', ' +
					'Viewport: y=' + vp.y + ", h=" + vp.h + ', bottom=' + (vp.y + vp.h)
				);*/
			}

			ed.undoManager.add();

			return FALSE;
		},

		backspaceDelete : function(e, bs) {
			var t = this, ed = t.editor, b = ed.getBody(), dom = ed.dom, n, se = ed.selection, r = se.getRng(), sc = r.startContainer, n, w, tn, walker;

			// Delete when caret is behind a element doesn't work correctly on Gecko see #3011651
			if (!bs && r.collapsed && sc.nodeType == 1 && r.startOffset == sc.childNodes.length) {
				walker = new tinymce.dom.TreeWalker(sc.lastChild, sc);

				// Walk the dom backwards until we find a text node
				for (n = sc.lastChild; n; n = walker.prev()) {
					if (n.nodeType == 3) {
						r.setStart(n, n.nodeValue.length);
						r.collapse(true);
						se.setRng(r);
						return;
					}
				}
			}

			// The caret sometimes gets stuck in Gecko if you delete empty paragraphs
			// This workaround removes the element by hand and moves the caret to the previous element
			if (sc && ed.dom.isBlock(sc) && !/^(TD|TH)$/.test(sc.nodeName) && bs) {
				if (sc.childNodes.length == 0 || (sc.childNodes.length == 1 && sc.firstChild.nodeName == 'BR')) {
					// Find previous block element
					n = sc;
					while ((n = n.previousSibling) && !ed.dom.isBlock(n)) ;

					if (n) {
						if (sc != b.firstChild) {
							// Find last text node
							w = ed.dom.doc.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, FALSE);
							while (tn = w.nextNode())
								n = tn;

							// Place caret at the end of last text node
							r = ed.getDoc().createRange();
							r.setStart(n, n.nodeValue ? n.nodeValue.length : 0);
							r.setEnd(n, n.nodeValue ? n.nodeValue.length : 0);
							se.setRng(r);

							// Remove the target container
							ed.dom.remove(sc);
						}

						return Event.cancel(e);
					}
				}
			}
		}
	});
})(tinymce);


text:
<?php

$roles = $this->roles;
$default = $this->current;

if( defined('PP_ACTIVE') ) {
	require_once( dirname(__FILE__).'/pp-ui.php' );
	$pp_ui = new Capsman_PP_UI();
	$pp_metagroup_caps = $pp_ui->get_metagroup_caps( $default );
} else
	$pp_metagroup_caps = array();
?>

	<?php if( defined('PP_ACTIVE') ) :
		pp_icon();
		$style = 'style="height:60px;"';
	?>
	<?php else:
		$style = '';
	?>

	<?php endif; ?>

	<h1 <?php echo $style;?>><?php _e('Roles and Capabilities', 'capsman-enhanced') ?>

	<form method="post" action="admin.php?page=<?php echo $this->ID ?>">
	<?php wp_nonce_field('capsman-general-manager'); ?>
	<fieldset>

<?php printf(__('Capabilities for %s', 'capsman-enhanced'), $roles[$default]); ?>

				<?php _e( 'View and modify capabilities WordPress associates with each role. Changes remain in the database even if you deactivate this plugin.', 'capsman-enhanced' ); ?>

				<?php
				if ( defined( 'PP_ACTIVE' ) ) {
					$pp_ui->show_capability_hints( $default );
				} else {
					global $capsman;
					$img_url = $capsman->mod_url . '/images/';

					echo '
';
					_e( "To further customize editing or viewing access, consider stepping up to Press Permit.", 'capsman-enhanced' );
					echo '
';
					?>

					<?php /* play.png icon by Pavel: http://kde-look.org/usermanager/search.php?username=InFeRnODeMoN */ ?>

<img src="<?php echo $img_url;?>pp-logo.png" />

					<?php _e( "Automatically define type-specific capabilities for your custom post types and taxonomies", 'capsman-enhanced' );?>
					<img class="cme-play" src="<?php echo $img_url;?>play.png" />

					<?php _e( "Assign standard WP roles supplementally for a specific post type", 'capsman-enhanced' );?>
					<img class="cme-play" src="<?php echo $img_url;?>play.png" />

					<?php _e( "Assign custom WP roles supplementally for a specific post type (Pro)", 'capsman-enhanced' );?>
					<img class="cme-play" src="<?php echo $img_url;?>play.png" />

					<?php _e( "Customize reading permissions per-category or per-post", 'capsman-enhanced' );?>
					<img class="cme-play" src="<?php echo $img_url;?>play.png" />

					<?php _e( "Customize editing permissions per-category or per-post (Pro)", 'capsman-enhanced' );?>
					<img class="cme-play" src="<?php echo $img_url;?>play.png" />

					<?php _e( "Custom Post Visibility statuses, fully implemented throughout wp-admin (Pro)", 'capsman-enhanced' );?>
					<img class="cme-play" src="<?php echo $img_url;?>play.png" />

					<?php _e( "Custom Moderation statuses for access-controlled, multi-step publishing workflow (Pro)", 'capsman-enhanced' );?>
					<img class="cme-play" src="<?php echo $img_url;?>play.png" />

					<?php _e( "Regulate permissions for Edit Flow post statuses (Pro)", 'capsman-enhanced' );?>
					<img class="cme-play" src="<?php echo $img_url;?>play.png" />

					<?php _e( "Customize the moderated editing of published content with Revisionary or Post Forking (Pro)", 'capsman-enhanced' );?>
					<img class="cme-play" src="<?php echo $img_url;?>play.png" />

					<?php _e( "Grant Spectator, Participant or Moderator access to specific bbPress forums (Pro)", 'capsman-enhanced' );?>
					<img class="cme-play" src="<?php echo $img_url;?>play.png" />

					<?php _e( "Grant supplemental content permissions to a BuddyPress group (Pro)", 'capsman-enhanced' );?>
					<img class="cme-play" src="<?php echo $img_url;?>play.png" />

					<?php _e( "WPML integration to mirror permissions to translations (Pro)", 'capsman-enhanced' );?>

					<?php _e( "Member support forum", 'capsman-enhanced' );?>

					<?php
					echo '
';
					printf( __('%1$sgrab%2$s %3$s', 'capsman-enhanced'), '', '', 'Press Permit Core' );
					echo '  •  ';
					printf( __('%1$sbuy%2$s %3$s', 'capsman-enhanced'), '', '',  'Press Permit Pro' );
					echo '  •  ';
					echo 'hide';
					echo '

';
				}

				if ( MULTISITE ) {
					global $wp_roles;
					//if ( method_exists( $wp_roles, 'reinit' ) ) {
						global $wpdb;

						if ( ! empty($_REQUEST['cme_net_sync_role'] ) ) {
							switch_to_blog(1);
							wp_cache_delete( $wpdb->prefix . 'user_roles', 'options' );
						}

						//$wp_roles->reinit();
						$wp_roles = new WP_Roles();
					//}
				}

				global $capsman;
				$capsman->reinstate_db_roles();

				$current = get_role($default);

				//print_r($current);

				$rcaps = $current->capabilities;

				// ========= Begin Kevin B mod ===========
				$is_administrator = current_user_can( 'administrator' );

				$custom_types = get_post_types( array( '_builtin' => false ), 'names' );
				$custom_tax = get_taxonomies( array( '_builtin' => false ), 'names' );

				$defined = array();
				$defined['type'] = get_post_types( array( 'public' => true ), 'object' );
				$defined['taxonomy'] = get_taxonomies( array( 'public' => true ), 'object' );

				$unfiltered['type'] = apply_filters( 'pp_unfiltered_post_types', array('forum','topic','reply') );  // bbPress' dynamic role def requires additional code to enforce stored caps
				$unfiltered['taxonomy'] = apply_filters( 'pp_unfiltered_taxonomies', array( 'post_status', 'topic-tag' ) );  // avoid confusion with Edit Flow administrative taxonomy
				/*
				if ( ( count($custom_types) || count($custom_tax) ) && ( $is_administrator || current_user_can( 'manage_pp_settings' ) ) ) {
					$cap_properties[''] = array();
					$force_distinct_ui = true;
				}
				*/

				$cap_properties['edit']['type'] = array( 'edit_posts' );

				foreach( $defined['type'] as $type_obj ) {
					if ( 'attachment' != $type_obj->name ) {
						if ( isset( $type_obj->cap->create_posts ) && ( $type_obj->cap->create_posts != $type_obj->cap->edit_posts ) ) {
							$cap_properties['edit']['type'][]= 'create_posts';
							break;
						}
					}
				}

				$cap_properties['edit']['type'][]= 'edit_others_posts';
				$cap_properties['edit']['type'] = array_merge( $cap_properties['edit']['type'], array( 'publish_posts', 'edit_published_posts', 'edit_private_posts' ) );

				$cap_properties['edit']['taxonomy'] = array( 'manage_terms' );

				if ( ! defined( 'PP_ACTIVE' ) )
					$cap_properties['edit']['taxonomy'] = array_merge( $cap_properties['edit']['taxonomy'], array( 'edit_terms', 'assign_terms' ) );

				$cap_properties['delete']['type'] = array( 'delete_posts', 'delete_others_posts' );
				$cap_properties['delete']['type'] = array_merge( $cap_properties['delete']['type'], array( 'delete_published_posts', 'delete_private_posts' ) );

				if ( ! defined( 'PP_ACTIVE' ) )
					$cap_properties['delete']['taxonomy'] = array( 'delete_terms' );
				else
					$cap_properties['delete']['taxonomy'] = array();

				$cap_properties['read']['type'] = array( 'read_private_posts' );
				$cap_properties['read']['taxonomy'] = array();

				$stati = get_post_stati( array( 'internal' => false ) );

				//if ( count($stati) > 5 ) {
					$cap_type_names = array(
						'' => __( ' ', 'capsman-enhanced' ),
						'read' => __( 'Reading', 'capsman-enhanced' ),
						'edit' => __( 'Editing Capabilities', 'capsman-enhanced' ),
						'delete' => __( 'Deletion Capabilities', 'capsman-enhanced' )
					);

				//} else {

				//}

				$cap_tips = array(
					'read_private' => __( 'can read posts which are currently published with private visibility', 'capsman-enhanced' ),
					'edit' => __( 'has basic editing capability (but may need other capabilities based on post status and ownership)', 'capsman-enhanced' ),
					'edit_others' => __( 'can edit posts which were created by other users', 'capsman-enhanced' ),
					'edit_published' => __( 'can edit posts which are currently published', 'capsman-enhanced' ),
					'edit_private' => __( 'can edit posts which are currently published with private visibility', 'capsman-enhanced' ),
					'publish' => __( 'can make a post publicly visible', 'capsman-enhanced' ),
					'delete' => __( 'has basic deletion capability (but may need other capabilities based on post status and ownership)', 'capsman-enhanced' ),
					'delete_others' => __( 'can delete posts which were created by other users', 'capsman-enhanced' ),
					'delete_published' => __( 'can delete posts which are currently published', 'capsman-enhanced' ),
					'delete_private' => __( 'can delete posts which are currently published with private visibility', 'capsman-enhanced' ),
				);

				$default_caps = array( 'read_private_posts', 'edit_posts', 'edit_others_posts', 'edit_published_posts', 'edit_private_posts', 'publish_posts', 'delete_posts', 'delete_others_posts', 'delete_published_posts', 'delete_private_posts',
									   'read_private_pages', 'edit_pages', 'edit_others_pages', 'edit_published_pages', 'edit_private_pages', 'publish_pages', 'delete_pages', 'delete_others_pages', 'delete_published_pages', 'delete_private_pages',
									   'manage_categories'
									   );
				$type_caps = array();

				// Role Scoper and PP1 adjust attachment access based only on user's capabilities for the parent post
				if ( defined('SCOPER_VERSION') || ( defined( 'PP_ACTIVE' ) && ! defined( 'PPC_VERSION' ) ) )
					unset( $defined['type']['attachment'] );

				echo '
';

				// cap_types: read, edit, deletion
				foreach( array_keys($cap_properties) as $cap_type ) {
					echo '
';
					echo '
' . $cap_type_names[$cap_type] . '
';
					echo '
';

					foreach( array_keys($defined) as $item_type ) {
						if ( ( 'delete' == $cap_type ) && ( 'taxonomy' == $item_type ) ) {
							if ( defined('SCOPER_VERSION') || defined('PP_ACTIVE') )
								continue;

							$any_term_deletion_caps = false;
							foreach( array_keys($defined['taxonomy']) as $_tax ) {
								if ( isset( $defined['taxonomy'][$_tax]->cap->delete_terms ) && ( 'manage_categories' != $defined['taxonomy'][$_tax]->cap->delete_terms ) && ! in_array( $_tax, $unfiltered['taxonomy'] ) ) {
									$any_term_deletion_caps = true;
									break;
								}
							}

							if ( ! $any_term_deletion_caps )
								continue;
						}

						//if ( ! $cap_type ) {

						//} else {
							echo '	';

							if ( ! count( $cap_properties[$cap_type][$item_type] ) )
								continue;

							// label cap properties
							foreach( $cap_properties[$cap_type][$item_type] as $prop ) {
								$prop = str_replace( '_posts', '', $prop );
								$prop = str_replace( '_pages', '', $prop );
								$prop = str_replace( '_terms', '', $prop );
								$tip = ( isset( $cap_tips[$prop] ) ) ? "title='{$cap_tips[$prop]}'" : '';
								$prop = str_replace( '_', '
', $prop );
								$th_class = ( 'taxonomy' == $item_type ) ? ' class="term-cap"' : ' class="post-cap"';
								echo "";
								echo ucwords($prop);
								echo '	';
							}

							foreach( $defined[$item_type] as $key => $type_obj ) {
								if ( in_array( $key, $unfiltered[$item_type] ) )
									continue;

								$row = "
";

								if ( $cap_type ) {
									if ( empty($force_distinct_ui) && empty( $cap_properties[$cap_type][$item_type] ) )
										continue;

									$row .= "" . $type_obj->labels->name . '';
									$row .= ' x ';
									$row .= '	';

									$display_row = ! empty($force_distinct_ui);

									foreach( $cap_properties[$cap_type][$item_type] as $prop ) {
										$td_classes = array();
										$checkbox = '';

										if ( ! empty($type_obj->cap->$prop) && ( in_array( $type_obj->name, array( 'post', 'page' ) )
										|| ! in_array( $type_obj->cap->$prop, $default_caps )
										|| ( ( 'manage_categories' == $type_obj->cap->$prop ) && ( 'manage_terms' == $prop ) && ( 'category' == $type_obj->name ) ) ) ) {

											// if edit_published or edit_private cap is same as edit_posts cap, don't display a checkbox for it
											if ( ( ! in_array( $prop, array( 'edit_published_posts', 'edit_private_posts', 'create_posts' ) ) || ( $type_obj->cap->$prop != $type_obj->cap->edit_posts ) )
											&& ( ! in_array( $prop, array( 'delete_published_posts', 'delete_private_posts' ) ) || ( $type_obj->cap->$prop != $type_obj->cap->delete_posts ) )
											) {
												$cap_name = $type_obj->cap->$prop;

												if ( 'taxonomy' == $item_type )
													$td_classes []= "term-cap";
												else
													$td_classes []= "post-cap";

												if ( ! empty($pp_metagroup_caps[$cap_name]) )
													$td_classes []='cm-has-via-pp';

												if ( $is_administrator || current_user_can($cap_name) ) {
													if ( ! empty($pp_metagroup_caps[$cap_name]) ) {
														$title_text = sprintf( __( '%s: assigned by Permission Group', 'capsman-enhanced' ), $cap_name );
													} else {
														$title_text = $cap_name;
													}

													$disabled = '';
													$checked = checked(1, ! empty($rcaps[$cap_name]), false );

													$checkbox = '<input id=caps[' . $cap_name . '] type="checkbox" title="' . $title_text . '" name="caps[' . $cap_name . ']" value="1" ' . $checked . $disabled . ' />';
													$type_caps [$cap_name] = true;
													$display_row = true;
												}
											} else
												$td_classes []= "cap-unreg";

											if ( isset($rcaps[$cap_name]) && empty($rcaps[$cap_name]) )
												$td_classes []= "cap-neg";
										} else
											$td_classes []= "cap-unreg";

										$td_class = ( $td_classes ) ? 'class="' . implode(' ', $td_classes) . '"' : '';

										$row .= "X$checkbox";

										if ( false !== strpos( $td_class, 'cap-neg' ) )
											$row .= '<input type="hidden" class="cme-negation-input" name="caps[' . $cap_name . ']" value="" />';

										$row .= "	";
									}
								}

								if ( $display_row ) {
									$row .= '
';
									echo $row;
								}
							}
						//} // endif this iteration is for type caps checkbox display

					} // end foreach item type

					echo '
';

					echo '
';
				}

				echo '
';

				// clicking on post type name toggles corresponding checkbox selections
				?>

				<?php

				$core_caps = array_fill_keys( array( 'switch_themes', 'edit_themes', 'activate_plugins', 'edit_plugins', 'edit_users', 'edit_files', 'manage_options', 'moderate_comments',
					'manage_links', 'upload_files', 'import', 'unfiltered_html', 'read', 'delete_users', 'create_users', 'unfiltered_upload', 'edit_dashboard',
					'update_plugins', 'delete_plugins', 'install_plugins', 'update_themes', 'install_themes',
					'update_core', 'list_users', 'remove_users', 'add_users', 'promote_users', 'edit_theme_options', 'delete_themes', 'export' ), true );

				ksort( $core_caps );

				echo '

' . __( 'Other WordPress Core Capabilities', 'capsman-enhanced' ) . '
';
				echo '

';

				$checks_per_row = get_option( 'cme_form-rows', 5 );
				$i = 0; $first_row = true;

				foreach( array_keys($core_caps) as $cap_name ) {
					if ( ! $is_administrator && ! current_user_can($cap_name) )
						continue;

					if ( $i == $checks_per_row ) {
						echo '

';
						$i = 0;
					}

					if ( ! isset( $rcaps[$cap_name] ) )
						$class = 'cap-no';
					else
						$class = ( $rcaps[$cap_name] ) ? 'cap-yes' : 'cap-neg';

					if ( ! empty($pp_metagroup_caps[$cap_name]) ) {
						$class .= ' cap-metagroup';
						$title_text = sprintf( __( '%s: assigned by Permission Group', 'capsman-enhanced' ), $cap_name );
					} else {
						$title_text = $cap_name;
					}

					$disabled = '';
					$checked = checked(1, ! empty($rcaps[$cap_name]), false );
					?>
					<td class="<?php echo $class; ?>">X<label for="caps[<?php echo $cap_name; ?>]" title="<?php echo $title_text;?>"><input id=caps[<?php echo $cap_name; ?>] type="checkbox" name="caps[<?php echo $cap_name; ?>]" value="1" <?php echo $checked . $disabled;?> />

					<?php
					echo str_replace( '_', ' ', $cap_name );
					?>
					 x
					<?php if ( false !== strpos( $class, 'cap-neg' ) ) :?>
						<input type="hidden" class="cme-negation-input" name="caps[<?php echo $cap_name; ?>]" value="" />
					<?php endif; ?>

					<?php
					++$i;
				}

				if ( $i == $checks_per_row ) {
					echo '

';
					$i = 0;
				} elseif ( ! $first_row ) {
					// Now close a wellformed table
					for ( $i; $i < $checks_per_row; $i++ ){
						echo ' 	';
					}
					echo '
';
				}
				?>

				<td colspan="<?php echo $checks_per_row;?>">

				<input type="checkbox" class="cme-check-all" title="<?php _e('check/uncheck all', 'capsman-enhanced');?>">  <a class="cme-neg-all" href="#" title="<?php _e('negate all (storing as disabled capabilities)', 'capsman-enhanced');?>">X <a class="cme-switch-all" href="#" title="<?php _e('negate none (add/remove all capabilities normally)', 'capsman-enhanced');?>">X

				<?php
				echo '

' . __( 'Additional Capabilities', 'capsman-enhanced' ) . '
';

				?>

				<?php
				$i = 0; $first_row = true;

				$all_capabilities = apply_filters( 'capsman_get_capabilities', array_keys( $this->capabilities ), $this->ID );
				$all_capabilities = apply_filters( 'members_get_capabilities', $all_capabilities );

				foreach( $all_capabilities as $cap_name ) {
					if ( ! isset($this->capabilities[$cap_name]) )
						$this->capabilities[$cap_name] = str_replace( '_', ' ', $cap_name );
				}

				uasort( $this->capabilities, 'strnatcasecmp' );  // sort by array values, but maintain keys );

				foreach ( $this->capabilities as $cap_name => $cap ) :
					if ( isset( $type_caps[$cap_name] ) || isset($core_caps[$cap_name]) )
						continue;

					if ( ! $is_administrator && ! current_user_can($cap_name) )
						continue;

					// ============ End Kevin B mod ===============

					// Levels are not shown.
					if ( preg_match( '/^level_(10|[0-9])$/i', $cap_name ) ) {
						continue;
					}

					if ( $i == $checks_per_row ) {
						echo '

';
						$i = 0; $first_row = false;
					}

					if ( ! isset( $rcaps[$cap_name] ) )
						$class = 'cap-no';
					else
						$class = ( $rcaps[$cap_name] ) ? 'cap-yes' : 'cap-neg';

					if ( ! empty($pp_metagroup_caps[$cap_name]) ) {
						$class .= ' cap-metagroup';
						$title_text = sprintf( __( '%s: assigned by Permission Group', 'capsman-enhanced' ), $cap_name );
					} else {
						$title_text = $cap_name;
					}

					$disabled = '';
					$checked = checked(1, ! empty($rcaps[$cap_name]), false );

					if ( 'manage_capabilities' == $cap_name ) {
						if ( ! current_user_can('administrator') ) {
							continue;
						} elseif ( 'administrator' == $default ) {
							$class .= ' cap-locked';
							$lock_manage_caps_capability = true;
							$disabled = 'disabled="disabled"';
						}
					}
				?>
					<td class="<?php echo $class; ?>">X<label for="caps[<?php echo $cap_name; ?>]" title="<?php echo $title_text;?>"><input id=caps[<?php echo $cap_name; ?>] type="checkbox" name="caps[<?php echo $cap_name; ?>]" value="1" <?php echo $checked . $disabled;?> />

					<?php
					echo str_replace( '_', ' ', $cap );
					?>
					 x
					<?php if ( false !== strpos( $class, 'cap-neg' ) ) :?>
						<input type="hidden" class="cme-negation-input" name="caps[<?php echo $cap_name; ?>]" value="" />
					<?php endif; ?>

				<?php
					$i++;
				endforeach;

				if ( ! empty($lock_manage_caps_capability) ) {
					echo '<input type="hidden" name="caps[manage_capabilities]" value="1" />';
				}

				if ( $i == $checks_per_row ) {
					echo '

';
					$i = 0;
				} else {
					if ( ! $first_row ) {
						// Now close a wellformed table
						for ( $i; $i < $checks_per_row; $i++ ){
							echo ' 	';
						}
						echo '
';
					}
				}
				?>

				<td colspan="<?php echo $checks_per_row;?>">

				<?php
				$level = ak_caps2level($rcaps);
				?>
				<?php _e('Level:', 'capsman-enhanced') ;?><select name="level">
				<?php for ( $l = $this->max_level; $l >= 0; $l-- ) {?>
						<option value="<?php echo $l; ?>" style="text-align:right;"<?php selected($level, $l); ?>> <?php echo $l; ?> </option>
					<?php }
					?>
				</select>

				<input type="checkbox" class="cme-check-all" title="<?php _e('check/uncheck all', 'capsman-enhanced');?>">  <a class="cme-neg-all" href="#" title="<?php _e('negate all (storing as disabled capabilities)', 'capsman-enhanced');?>">X <a class="cme-switch-all" href="#" title="<?php _e('negate none (add/remove all capabilities normally)', 'capsman-enhanced');?>">X

				<?php if ( ! defined('PP_ACTIVE') || pp_get_option('display_hints') ) :?>

					<?php _e( 'Note: Underscores replace spaces in stored capability name ("edit users" => "edit_users").', 'capsman-enhanced' ); ?>

				<?php endif;?>

		<?php
		$support_pp_only_roles = ( defined('PP_ACTIVE') ) ? $pp_ui->pp_only_roles_ui( $default ) : false;
		cme_network_role_ui( $default );
		?>

			<input type="hidden" name="action" value="update" />
			<input type="hidden" name="current" value="<?php echo $default; ?>" />
			<input type="submit" name="SaveRole" value="<?php _e('Save Changes', 'capsman-enhanced') ?>" class="button-primary" />

			<?php if ( current_user_can('administrator') && 'administrator' != $default ) : ?>
				<a class="ak-delete" title="<?php echo esc_attr(__('Delete this role', 'capsman-enhanced')) ?>" href="<?php echo wp_nonce_url("admin.php?page={$this->ID}&action=delete&role={$default}", 'delete-role_' . $default); ?>" onclick="if ( confirm('<?php echo esc_js(sprintf(__("You are about to delete the %s role.\n 'Cancel' to stop, 'OK' to delete.", 'capsman-enhanced'), $roles[$default])); ?>') ) { return true;}return false;"><?php _e('Delete Role', 'capsman-enhanced')?>
			<?php endif; ?>

		<?php agp_admin_footer(); ?>

			<?php agp_admin_authoring($this->ID); ?>

<?php if ( defined('WPLANG') && WPLANG ) _e('Select New Role', 'capsman-enhanced'); else echo('Select Role to View / Edit'); ?>

<select name="role">
					<?php
					foreach ( $roles as $role => $name ) {
						echo '<option value="' . $role .'"'; selected($default, $role); echo '> ' . $name . '  </option>';
					}
					?>
					</select><input type="submit" name="LoadRole" value="<?php if ( defined('WPLANG') && WPLANG ) _e('Change', 'capsman-enhanced'); else echo('Load'); ?>" class="button" />

<?php _e('Create New Role', 'capsman-enhanced'); ?>

					<?php $class = ( $support_pp_only_roles ) ? 'tight-text' : 'regular-text'; ?>

<input type="text" name="create-name"" class="<?php echo $class;?>" placeholder="<?php _e('Name of new role', 'capsman-enhanced') ?>" />

					<?php if( $support_pp_only_roles ) : ?>
					<label for="new_role_pp_only" title="<?php _e('Make role available for supplemental assignment to Permission Groups only', 'capsman-enhanced');?>"> <input type="checkbox" name="new_role_pp_only" id="new_role_pp_only" value="1"> <?php _e('hidden', 'capsman-enhanced'); ?>
					<?php endif; ?>

					<input type="submit" name="CreateRole" value="<?php _e('Create', 'capsman-enhanced') ?>" class="button" />

<?php defined('WPLANG') && WPLANG ? _e('Copy this role to', 'capsman-enhanced') : printf( 'Copy %s Role', $roles[$default] ); ?>

					<?php $class = ( $support_pp_only_roles ) ? 'tight-text' : 'regular-text'; ?>

<input type="text" name="copy-name"  class="<?php echo $class;?>" placeholder="<?php _e('Name of copied role', 'capsman-enhanced') ?>" />

					<?php if( $support_pp_only_roles ) : ?>
					<label for="copy_role_pp_only" title="<?php _e('Make role available for supplemental assignment to Permission Groups only', 'capsman-enhanced');?>"> <input type="checkbox" name="copy_role_pp_only" id="copy_role_pp_only" value="1"> <?php _e('hidden', 'capsman-enhanced'); ?>
					<?php endif; ?>

					<input type="submit" name="CopyRole" value="<?php _e('Copy', 'capsman-enhanced') ?>" class="button" />

<?php _e('Add Capability', 'capsman-enhanced'); ?>

<input type="text" name="capability-name" class="regular-text" placeholder="<?php _e('capability name', 'capsman-enhanced') ?>" />

					<input type="submit" name="AddCap" value="<?php _e('Add to role', 'capsman-enhanced') ?>" class="button" />

			<?php if ( defined('PP_ACTIVE') )
				$pp_ui->pp_types_ui( $defined );
			?>

	</fieldset>
	</form>

<?php
function cme_network_role_ui( $default ) {
	if ( ! is_multisite() || ! is_super_admin() || ( 1 != get_current_blog_id() ) )
		return false;
	?>

		<?php
		if ( ! $autocreate_roles = get_site_option( 'cme_autocreate_roles' ) )
			$autocreate_roles = array();

		$checked = ( in_array( $default, $autocreate_roles ) ) ? 'checked="checked"': '';
		?>

		<label for="cme_autocreate_role" title="<?php _e('Create this role definition in new (future) sites', 'capsman-enhanced');?>"><input type="checkbox" name="cme_autocreate_role" id="cme_autocreate_role" value="1" <?php echo $checked;?>> <?php _e('include in new sites', 'capsman-enhanced'); ?>

		<label for="cme_net_sync_role" title="<?php echo esc_attr(__('Copy / update this role definition to all sites now', 'capsman-enhanced'));?>"><input type="checkbox" name="cme_net_sync_role" id="cme_net_sync_role" value="1"> <?php _e('sync role to all sites now', 'capsman-enhanced'); ?>

<?php
	return true;
}

function cme_plugin_info_url( $plugin_slug ) {
	return self_admin_url( "plugin-install.php?tab=plugin-information&plugin=$plugin_slug&TB_iframe=true&width=640&height=678" );
}


text:
package org.apache.jackrabbit.oak.plugins.index.counter.jmx;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.plugins.index.IndexConstants;
import org.apache.jackrabbit.oak.plugins.index.counter.NodeCounterEditor;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.apache.jackrabbit.oak.util.ApproximateCounter;

/**
 * A mechanism to retrieve node counter data.
 */
public class NodeCounter implements NodeCounterMBean {

    /**
     * Approximate count using the hashed name (deterministically, so that after
     * adding a removing all nodes the count goes back to zero).
     */
    public final static boolean COUNT_HASH =
            Boolean.parseBoolean(System.getProperty("oak.countHashed", "true"));

    private final NodeStore store;

    public NodeCounter(NodeStore store) {
        this.store = store;
    }

    private static NodeState child(NodeState n, String... path) {
        return child(n, Arrays.asList(path));
    }

    private static NodeState child(NodeState n, Iterable<String> path) {
        for (String p : path) {
            if (n == null) {
                break;
            }
            if (p.length() > 0) {
                n = n.getChildNode(p);
            }
        }
        return n;
    }

    @Override
    public long getEstimatedNodeCount(String path) {
        return getEstimatedNodeCount(store.getRoot(), path, false);
    }

    /**
     * Get the estimated number of nodes for a given path.
     *
     * @param root the root
     * @param path the path
     * @param max whether to get the maximum expected number of nodes (the
     *            stored value plus the resolution)
     * @return -1 if unknown, 0 if the node does not exist (or, if max is false,
     *         if there are probably not many descendant nodes), or the
     *         (maximum) estimated number of descendant nodes
     */
    public static long getEstimatedNodeCount(NodeState root, String path, boolean max) {
        // check if there is a property in the node itself
        // (for property index nodes)
        NodeState s = child(root,
                PathUtils.elements(path));
        if (s == null || !s.exists()) {
            // node not found
            return 0;
        }
        if (!max) {
            long syncCount = ApproximateCounter.getCountSync(s);
            if (syncCount != -1) {
                return syncCount;
            }
        }
        if (COUNT_HASH) {
            return getCombinedCount(root, path, s, max);
        }
        return getEstimatedNodeCountOld(root, s, path, max);
    }

    private static long getEstimatedNodeCountOld(NodeState root, NodeState s, String path, boolean max) {
        // old code from here
        PropertyState p = s.getProperty(NodeCounterEditor.COUNT_PROPERTY_NAME);
        if (p != null) {
            long x = p.getValue(Type.LONG);
            if (max) {
                // in the node itself, we just add the resolution
                x += ApproximateCounter.COUNT_RESOLUTION;
            }
            return x;
        }
        // check in the counter index (if it exists)
        s = child(root,
                IndexConstants.INDEX_DEFINITIONS_NAME,
                "counter");
        if (s == null || !s.exists()) {
            // no index
            return -1;
        }
        s = child(s, NodeCounterEditor.DATA_NODE_NAME);
        s = child(s, PathUtils.elements(path));
        if (s == null || !s.exists()) {
            // we have an index, but no data
            long x = 0;
            if (max) {
                // in the index, the resolution is lower
                x += ApproximateCounter.COUNT_RESOLUTION * 20;
            }
            return x;
        }
        p = s.getProperty(NodeCounterEditor.COUNT_PROPERTY_NAME);
        if (p == null) {
            // we have an index, but no data
            long x = 0;
            if (max) {
                // in the index, the resolution is lower
                x += ApproximateCounter.COUNT_RESOLUTION * 20;
            }
            return x;
        }
        long x = p.getValue(Type.LONG);
        if (max) {
            x += ApproximateCounter.COUNT_RESOLUTION;
        }
        return x;
    }

    private static long getCombinedCount(NodeState root, String path, NodeState s, boolean max) {
        Long value = getCombinedCountIfAvailable(s);
        if (value != null) {
            return value + (max ? ApproximateCounter.COUNT_RESOLUTION : 0);
        }
        // check in the counter index (if it exists)
        s = child(root,
                IndexConstants.INDEX_DEFINITIONS_NAME,
                "counter");
        if (s == null || !s.exists()) {
            // no index
            return -1;
        }
        s = child(s, NodeCounterEditor.DATA_NODE_NAME);
        s = child(s, PathUtils.elements(path));
        if (s != null && s.exists()) {
            value = getCombinedCountIfAvailable(s);
            if (value != null) {
                return value + (max ? ApproximateCounter.COUNT_RESOLUTION : 0);
            }
        }
        // we have an index, but no data
        return max ? ApproximateCounter.COUNT_RESOLUTION * 20 : 0;
    }

    private static Long getCombinedCountIfAvailable(NodeState s) {
        boolean found = false;
        long x = 0;
        PropertyState p = s.getProperty(NodeCounterEditor.COUNT_HASH_PROPERTY_NAME);
        if (p != null) {
            found = true;
            x = p.getValue(Type.LONG);
        }
        p = s.getProperty(NodeCounterEditor.COUNT_PROPERTY_NAME);
        if (p != null) {
            found = true;
            x += p.getValue(Type.LONG);
        }
        return found ? x : null;
    }

    @Override
    public String getEstimatedChildNodeCounts(String path, int level) {
        StringBuilder buff = new StringBuilder();
        collectCounts(buff, path, level);
        return buff.toString();
    }

    private void collectCounts(StringBuilder buff, String path, int level) {
        long count = getEstimatedNodeCount(path);
        if (count > 0) {
            if (buff.length() > 0) {
                buff.append(",\n");
            }
            buff.append(path).append(": ").append(count);
        }
        if (level <= 0) {
            return;
        }
        NodeState s = child(store.getRoot(),
                PathUtils.elements(path));
        if (!s.exists()) {
            return;
        }
        ArrayList<String> names = new ArrayList<String>();
        for (ChildNodeEntry c : s.getChildNodeEntries()) {
            names.add(c.getName());
        }
        Collections.sort(names);
        for (String cn : names) {
            s.getChildNode(cn);
            String child = PathUtils.concat(path, cn);
            collectCounts(buff, child, level - 1);
        }
    }

}


text:
package com.newatlanta.appengine.junit.locks;

import org.junit.Test;

import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.newatlanta.appengine.junit.LocalServiceTestCase;
import com.newatlanta.appengine.locks.SharedLock;

/**
 * Tests com.newatlanta.appengine.locks.SharedLock.
 *
 * @author Vince Bonfanti
 */
public class SharedLockTestCase extends LocalServiceTestCase {

    private static final String LOCK_NAME = "junit.shared.lock";

    private SharedLock lock;

    @Override
    public void setUp() throws Exception {
        super.setUp();
        lock = new SharedLock( LOCK_NAME );
    }

    @Test
    public void testTryLock() {
        assertFalse( lock.isLocked() );
        Thread lockThread = LockingThread.createThread( lock, Long.MAX_VALUE );
        assertTrue( lock.isLocked() );
        for ( int i = 0; i < 20; i++ ) {
            assertTrue( lock.tryLock() );
            assertTrue( lock.isLocked() );
        }
        lockThread.interrupt(); // release the lock
        for ( int i = 0; i < 19; i++ ) {
            lock.unlock();
            assertTrue( lock.isLocked() );
        }
        lock.unlock();
        assertFalse( lock.isLocked() );
    }

    @Test
    public void testEvictLock() {
        assertFalse( lock.isLocked() );
        for ( int i = 0; i < 20; i++ ) {
            assertTrue( lock.tryLock() );
        }
        assertEquals( 20, lock.getCounter() );
        MemcacheServiceFactory.getMemcacheService().delete( LOCK_NAME );
        assertTrue( lock.tryLock() );
        assertEquals( 1, lock.getCounter() );
    }
}


text:
package multierror

// Append is a helper function that will append more errors
// onto an Error in order to create a larger multi-error.
//
// If err is not a multierror.Error, then it will be turned into
// one. If any of the errs are multierr.Error, they will be flattened
// one level into err.
// Any nil errors within errs will be ignored. If err is nil, a new
// *Error will be returned.
func Append(err error, errs ...error) *Error {
	switch err := err.(type) {
	case *Error:
		// Typed nils can reach here, so initialize if we are nil
		if err == nil {
			err = new(Error)
		}

		// Go through each error and flatten
		for _, e := range errs {
			switch e := e.(type) {
			case *Error:
				if e != nil {
					err.Errors = append(err.Errors, e.Errors...)
				}
			default:
				if e != nil {
					err.Errors = append(err.Errors, e)
				}
			}
		}

		return err
	default:
		newErrs := make([]error, 0, len(errs)+1)
		if err != nil {
			newErrs = append(newErrs, err)
		}
		newErrs = append(newErrs, errs...)

		return Append(&Error{}, newErrs...)
	}
}


text:
// <copyright file="IccDataWriter.cs" company="James Jackson-South">
// Copyright (c) James Jackson-South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>

namespace ImageSharp
{
    using System;
    using System.Linq;

    /// <summary>
    /// A sampled curve segment
    /// </summary>
    internal sealed class IccSampledCurveElement : IccCurveSegment, IEquatable<IccSampledCurveElement>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="IccSampledCurveElement"/> class.
        /// </summary>
        /// <param name="curveEntries">The curve values of this segment</param>
        public IccSampledCurveElement(float[] curveEntries)
            : base(IccCurveSegmentSignature.SampledCurve)
        {
            Guard.NotNull(curveEntries, nameof(curveEntries));
            Guard.IsTrue(curveEntries.Length > 0, nameof(curveEntries), "There must be at least one value");

            this.CurveEntries = curveEntries;
        }

        /// <summary>
        /// Gets the curve values of this segment
        /// </summary>
        public float[] CurveEntries { get; }

        /// <inheritdoc />
        public override bool Equals(IccCurveSegment other)
        {
            if (base.Equals(other) && other is IccSampledCurveElement segment)
            {
                return this.CurveEntries.SequenceEqual(segment.CurveEntries);
            }

            return false;
        }

        /// <inheritdoc />
        public bool Equals(IccSampledCurveElement other)
        {
            return this.Equals((IccCurveSegment)other);
        }
    }
}


text:
      <form id="newsletter-form">

          Join our Newsletter

          <input type="email" name="contact_email" value="" id="contact_email" placeholder="Enter Email Address">
          <button type="submit" class="btn submit">Submit</button>

Success! Thanks for joining.

      </form>

© <?php echo date('Y') ?> The JBG Companies.
All rights reserved.

<?php wp_footer(); ?>