text:
package net.paoding.rose.web.impl.thread;

import static org.springframework.validation.BindingResult.MODEL_KEY_PREFIX;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.RoseVersion;
import net.paoding.rose.util.RoseStringUtil;
import net.paoding.rose.web.ControllerInterceptor;
import net.paoding.rose.web.InterceptorDelegate;
import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.InvocationChain;
import net.paoding.rose.web.ParamValidator;
import net.paoding.rose.web.RequestPath;
import net.paoding.rose.web.annotation.HttpFeatures;
import net.paoding.rose.web.annotation.IfParamExists;
import net.paoding.rose.web.annotation.Intercepted;
import net.paoding.rose.web.annotation.Return;
import net.paoding.rose.web.impl.module.Module;
import net.paoding.rose.web.impl.validation.ParameterBindingResult;
import net.paoding.rose.web.paramresolver.MethodParameterResolver;
import net.paoding.rose.web.paramresolver.ParamMetaData;
import net.paoding.rose.web.paramresolver.ParamResolver;
import net.paoding.rose.web.paramresolver.ParameterNameDiscovererImpl;
import net.paoding.rose.web.paramresolver.ResolverFactoryImpl;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.SpringVersion;
import org.springframework.util.Assert;
import org.springframework.validation.Errors;

/**
 * @author 王志亮 [qieqie.wang@gmail.com]
 */
public final class ActionEngine implements Engine {

    private final static Log logger = LogFactory.getLog(ActionEngine.class);

    private final Module module;

    private final Class<?> controllerClass;

    private final Object controller;

    private final Method method;

    private final HttpFeatures httpFeatures;

    private final InterceptorDelegate[] interceptors;

    private final ParamValidator[] validators;

    private final ParamExistenceChecker[] paramExistenceChecker;

    private final MethodParameterResolver methodParameterResolver;

    private transient String toStringCache;

    public ActionEngine(Module module, Class<?> controllerClass, Object controller, Method method) {
        this.module = module;
        this.controllerClass = controllerClass;
        this.controller = controller;
        this.method = method;
        this.interceptors = compileInterceptors();
        this.methodParameterResolver = compileParamResolvers();
        this.validators = compileValidators();
        this.paramExistenceChecker = compileParamExistenceChecker();
        HttpFeatures httpFeatures = method.getAnnotation(HttpFeatures.class);
        if (httpFeatures == null) {
            httpFeatures = this.controllerClass.getAnnotation(HttpFeatures.class);
        }
        this.httpFeatures = httpFeatures;
    }

    public InterceptorDelegate[] getRegisteredInterceptors() {
        return interceptors;
    }

    public Class<?> getControllerClass() {
        return controllerClass;
    }

    public Object getController() {
        return controller;
    }

    public Method getMethod() {
        return method;
    }

    public String[] getParameterNames() {
        return methodParameterResolver.getParameterNames();
    }

    private MethodParameterResolver compileParamResolvers() {
        ParameterNameDiscovererImpl parameterNameDiscoverer = new ParameterNameDiscovererImpl();
        ResolverFactoryImpl resolverFactory = new ResolverFactoryImpl();
        for (ParamResolver resolver : module.getCustomerResolvers()) {
            resolverFactory.addCustomerResolver(resolver);
        }
        return new MethodParameterResolver(this.controllerClass, method, parameterNameDiscoverer,
                resolverFactory);
    }

    @SuppressWarnings("unchecked")
    private ParamValidator[] compileValidators() {
        Class[] parameterTypes = method.getParameterTypes();
        List<ParamValidator> validators = module.getValidators();
        ParamValidator[] registeredValidators = new ParamValidator[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            for (ParamValidator validator : validators) {
                if (validator.supports(methodParameterResolver.getParamMetaDatas()[i])) {
                    registeredValidators[i] = validator;
                    break;
                }
            }
        }
        //
        return registeredValidators;
    }

    private InterceptorDelegate[] compileInterceptors() {
        List<InterceptorDelegate> interceptors = module.getInterceptors();
        List<InterceptorDelegate> registeredInterceptors = new ArrayList<InterceptorDelegate>(
                interceptors.size());
        for (InterceptorDelegate interceptor : interceptors) {

            ControllerInterceptor most = InterceptorDelegate.getMostInnerInterceptor(interceptor);

            if (!most.getClass().getName().startsWith("net.paoding.rose.web")) {

                // 获取@Intercepted注解 (@Intercepted注解配置于控制器或其方法中,决定一个拦截器是否应该拦截之。没有配置按"需要"处理)
                Intercepted intercepted = method.getAnnotation(Intercepted.class);
                if (intercepted == null) {
                    // 对于标注@Inherited的annotation,class.getAnnotation可以保证:如果本类没有,自动会从父类判断是否具有
                    intercepted = this.controllerClass.getAnnotation(Intercepted.class);
                }
                // 通过@Intercepted注解的allow和deny排除拦截器
                if (intercepted != null) {
                    // 3.1 先排除deny禁止的
                    if (RoseStringUtil.matches(intercepted.deny(), interceptor.getName())) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("action '" + controllerClass.getName() + "#"
                                    + method.getName()
                                    + "': remove interceptor by @Intercepted.deny: "
                                    + most.getClass().getName());
                        }
                        continue;
                    }
                    // 3.2 确认最大的allow允许
                    if (!RoseStringUtil.matches(intercepted.allow(), interceptor.getName())) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("action '" + controllerClass.getName() + "#"
                                    + method.getName()
                                    + "': remove interceptor by @Intercepted.allow: "
                                    + most.getClass().getName());
                        }
                        continue;
                    }
                }
            }
            // 取得拦截器同意后,注册到这个控制器方法中
            if (interceptor.isForAction(controllerClass, method)) {
                registeredInterceptors.add(interceptor);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("action '" + controllerClass.getName() + "#" + method.getName()
                            + "': remove interceptor by interceptor.isForAction: "
                            + most.getClass().getName());
                }
            }
        }
        //

        if (logger.isDebugEnabled()) {
            logger.debug("interceptors of " + controllerClass.getName() + "#" + method.getName()
                    + "=(" + registeredInterceptors.size() + "/" + interceptors.size() + ")"
                    + registeredInterceptors);
        }
        return registeredInterceptors
                .toArray(new InterceptorDelegate[registeredInterceptors.size()]);

    }

    /**
     * 用来抽象与{@link IfParamExists}相对应的判断逻辑
     *
     * @author Li Weibo (weibo.leo@gmail.com)
     */
    private static interface ParamExistenceChecker {

        public int check(Map<String, String[]> params);
    }

    /**
     * 初始化的时候来决定所有的判断条件,并抽象为{@link ParamExistenceChecker}数组
     *
     * @return
     */
    private ParamExistenceChecker[] compileParamExistenceChecker() {

        IfParamExists ifParamExists = method.getAnnotation(IfParamExists.class);
        //没标注IfParamExists或者标注了IfParamExists("")都认为不作检查
        if (ifParamExists == null || ifParamExists.value().trim().length() == 0) {
            return new ParamExistenceChecker[] {};
        }

        List<ParamExistenceChecker> checkers = new ArrayList<ParamExistenceChecker>(); //所有判断条件的列表
        String value = ifParamExists.value();

        //可以写多个判断条件,以这样的形式: type&subtype=value&anothername=value2
        String[] terms = StringUtils.split(value, "&");
        Assert.isTrue(terms.length >= 1); //这个应该永远成立

        //按'&'分割后,每一个term就是一个检查条件
        for (final String term : terms) {
            final int index = term.indexOf('='); //找'='
            if (index == -1) { //没有=说明只有参数名,此时term就是参数名
                checkers.add(new ParamExistenceChecker() {

                    final String paramName = term.trim();

                    @Override
                    public int check(Map<String, String[]> params) {
                        String[] paramValues = params.get(paramName);
                        if (logger.isDebugEnabled()) {
                            logger.debug(this.toString() + " is checking param:" + paramName + "="
                                    + Arrays.toString(paramValues));
                        }

                        //规则中没有约束参数值,所以只要存在就ok
                        if (paramValues != null && paramValues.length > 0) {
                            return 10;
                        } else {
                            return -1;
                        }
                    }
                });
            } else { //term中有'='

                final String paramName = term.substring(0, index).trim(); //参数名
                final String expected = term.substring(index + 1).trim(); //期望的参数值

                if (expected.startsWith(":")) { //expected是正则表达式
                    Pattern tmpPattern = null;
                    try {
                        tmpPattern = Pattern.compile(expected.substring(1));
                    } catch (PatternSyntaxException e) {
                        logger.error("@IfParamExists pattern error, " + controllerClass.getName()
                                + "#" + method.getName(), e);
                    }
                    final Pattern pattern = tmpPattern; //转成final的
                    checkers.add(new ParamExistenceChecker() {

                        @Override
                        public int check(Map<String, String[]> params) {
                            String[] paramValues = params.get(paramName);
                            if (logger.isDebugEnabled()) {
                                logger.debug(this.toString() + " is checking param:" + paramName
                                        + "=" + Arrays.toString(paramValues) + ", pattern="
                                        + pattern.pattern());
                            }
                            if (paramValues == null) { //参数值不能存在就不能通过
                                return -1;
                            }

                            for (String paramValue : paramValues) {
                                if (pattern != null && pattern.matcher(paramValue).matches()) {
                                    return 12;
                                }
                            }
                            return -1;
                        }
                    });
                } else { //expected是常量字符串,包括空串""
                    checkers.add(new ParamExistenceChecker() {

                        @Override
                        public int check(Map<String, String[]> params) {
                            String[] paramValues = params.get(paramName);
                            if (logger.isDebugEnabled()) {
                                logger.debug(this.toString() + " is checking param:" + paramName
                                        + "=" + Arrays.toString(paramValues) + ", expected="
                                        + expected);
                            }
                            if (paramValues == null) { //参数值不能存在就不能通过
                                return -1;
                            }

                            for (String paramValue : paramValues) {
                                if (expected.equals(paramValue)) {
                                    return 13;// 13优先于正则表达式的12
                                }
                            }
                            return -1;
                        }
                    });
                }
            }
        }
        return checkers.toArray(new ParamExistenceChecker[] {});
    }

    @Override
    public int isAccepted(HttpServletRequest request) {
        if (paramExistenceChecker.length == 0) { //没有约束条件,返回1
            return 1;
        }
        int total = 0;
        Map<String, String[]> params = resolveQueryString(request.getQueryString());
        for (ParamExistenceChecker checker : paramExistenceChecker) {
            int c = checker.check(params);
            if (c == -1) { //-1表示此约束条件未通过
                if (logger.isDebugEnabled()) {
                    logger.debug("Accepted check not passed by " + checker.toString());
                }
                return -1;
            }
            //FIXME 目前采用各个检查条件权值相加的办法来决定最终权值,
            //在权值相等的情况下,可能会有选举问题,需要更好的策略来取代
            total += c;
        }
        return total;
    }

    private Map<String, String[]> resolveQueryString(String queryString) {
        Map<String, String[]> params;
        if (queryString == null || queryString.length() == 0) {
            params = Collections.emptyMap();
        } else {
            params = new HashMap<String, String[]>();
            String[] kvs = queryString.split("&");
            for (String kv : kvs) {
                String[] pair = kv.split("=");
                if (pair.length == 2) {
                    mapPut(params, pair[0], pair[1]);
                } else if (pair.length == 1) {
                    mapPut(params, pair[0], "");
                } else {
                    logger.error("Illegal queryString:" + queryString);
                }
            }
        }
        return params;
    }

    private void mapPut(Map<String, String[]> map, String key, String value) {
        String[] values = map.get(key);
        if (values == null) {
            values = new String[] { value };
        } else {
            values = Arrays.copyOf(values, values.length + 1);
            values[values.length - 1] = value;
        }
        map.put(key, values);
    }

    @Override
    public Object execute(Rose rose) throws Throwable {
        try {
            return innerExecute(rose);
        } catch (Throwable local) {
            throw createException(rose, local);
        }
    }

    protected Object innerExecute(Rose rose) throws Throwable {
        Invocation inv = rose.getInvocation();

        // creates parameter binding result (not bean, just simple type, like int, Integer, int[] ...
        ParameterBindingResult paramBindingResult = new ParameterBindingResult(inv);
        String paramBindingResultName = MODEL_KEY_PREFIX + paramBindingResult.getObjectName();
        inv.addModel(paramBindingResultName, paramBindingResult);

        // resolves method parameters, adds the method parameters to model
        Object[] methodParameters = methodParameterResolver.resolve(inv, paramBindingResult);
        ((InvocationBean) inv).setMethodParameters(methodParameters);
        String[] parameterNames = methodParameterResolver.getParameterNames();

        Object instruction = null;

        ParamMetaData[] metaDatas = methodParameterResolver.getParamMetaDatas();
        // validators
        for (int i = 0; i < this.validators.length; i++) {
            if (validators[i] != null && !(methodParameters[i] instanceof Errors)) {
                Errors errors = inv.getBindingResult(parameterNames[i]);
                instruction = validators[i].validate(//
                        metaDatas[i], inv, methodParameters[i], errors);
                if (logger.isDebugEnabled()) {
                    logger.debug("do validate [" + validators[i].getClass().getName()
                            + "] and return '" + instruction + "'");
                }
                // 如果返回的instruction不是null、boolean或空串==>杯具:流程到此为止!
                if (instruction != null) {
                    if (instruction instanceof Boolean) {
                        continue;
                    }
                    if (instruction instanceof String && ((String) instruction).length() == 0) {
                        continue;
                    }
                    return instruction;
                }
            }
        }

        //
        for (int i = 0; i < parameterNames.length; i++) {
            if (parameterNames[i] != null && methodParameters[i] != null
                    && inv.getModel().get(parameterNames[i]) != methodParameters[i]) {
                inv.addModel(parameterNames[i], methodParameters[i]);
            }
        }

        // intetceptors & controller
        return new InvocationChainImpl(rose).doNext();
    }

    private class InvocationChainImpl implements InvocationChain {

        private final boolean debugEnabled = logger.isDebugEnabled();

        private int index = -1;

        private final Rose rose;

        private Object instruction;

        public InvocationChainImpl(Rose rose) {
            this.rose = rose;
        }

        @Override
        public Object doNext() throws Exception {
            if (++index < interceptors.length) { // ++index 用于将-1转化为0
                InterceptorDelegate interceptor = interceptors[index];
                //
                rose.addAfterCompletion(interceptor);
                Object instruction = interceptor.roundInvocation(rose.getInvocation(), this);
                //
                if (debugEnabled) {
                    logger.debug("interceptor[" + interceptor.getName() + "] do round and return '"
                            + instruction + "'");
                }

                // 拦截器返回null的,要恢复为原instruction
                // 这个功能非常有用!!
                if (instruction != null) {
                    this.instruction = instruction;
                }
                return this.instruction;
            } else if (index == interceptors.length) {
                // applies http features before the resolvers
                if (httpFeatures != null) {
                    applyHttpFeatures(rose.getInvocation());
                }

                this.instruction = method.invoke(controller, rose.getInvocation()
                        .getMethodParameters());

                // @Return
                if (this.instruction == null) {
                    Return returnAnnotation = method.getAnnotation(Return.class);
                    if (returnAnnotation != null) {
                        this.instruction = returnAnnotation.value();
                    }
                }
                return this.instruction;
            }
            throw new IndexOutOfBoundsException(
                    "don't call twice 'chain.doNext()' in one intercpetor; index=" + index
                            + "; interceptors.length=" + interceptors.length);
        }

    }

    private Exception createException(Rose rose, Throwable exception) {
        final RequestPath requestPath = rose.getInvocation().getRequestPath();
        StringBuilder sb = new StringBuilder(1024);
        sb.append("[Rose-").append(RoseVersion.getVersion()).append("@Spring-").append(
                SpringVersion.getVersion());
        sb.append("]Error happended: ").append(requestPath.getMethod());
        sb.append(" ").append(requestPath.getUri());
        sb.append("->");
        sb.append(this).append(" params=");
        sb.append(Arrays.toString(rose.getInvocation().getMethodParameters()));
        InvocationTargetException servletException = new InvocationTargetException(exception, sb
                .toString());
        return servletException;
    }

    private void applyHttpFeatures(final Invocation inv) throws UnsupportedEncodingException {
        HttpServletResponse response = inv.getResponse();
        if (StringUtils.isNotBlank(httpFeatures.charset())) {
            response.setCharacterEncoding(httpFeatures.charset());
            if (logger.isDebugEnabled()) {
                logger.debug("set response.characterEncoding by HttpFeatures:"
                        + httpFeatures.charset());
            }
        }
        if (StringUtils.isNotBlank(httpFeatures.contentType())) {
            String contentType = httpFeatures.contentType();
            if (contentType.equals("json")) {
                contentType = "application/json";
            } else if (contentType.equals("xml")) {
                contentType = "text/xml";
            } else if (contentType.equals("html")) {
                contentType = "text/html";
            } else if (contentType.equals("plain") || contentType.equals("text")) {
                contentType = "text/plain";
            }
            response.setContentType(contentType);
            if (logger.isDebugEnabled()) {
                logger.debug("set response.contentType by HttpFeatures:"
                        + response.getContentType());
            }
        }
    }

    @Override
    public String toString() {
        if (toStringCache == null) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            String appPackageName = this.controllerClass.getPackage().getName();
            if (appPackageName.indexOf('.') != -1) {
                appPackageName = appPackageName.substring(0, appPackageName.lastIndexOf('.'));
            }
            String methodParamNames = "";
            for (int i = 0; i < parameterTypes.length; i++) {
                if (methodParamNames.length() == 0) {
                    methodParamNames = showSimpleName(parameterTypes[i], appPackageName);
                } else {
                    methodParamNames = methodParamNames + ", "
                            + showSimpleName(parameterTypes[i], appPackageName);
                }
            }
            toStringCache = ""//
                    + showSimpleName(method.getReturnType(), appPackageName)
                    + " "
                    + method.getName() //
                    + "(" + methodParamNames + ")";
        }
        return toStringCache;
    }

    private String showSimpleName(Class<?> parameterType, String appPackageName) {
        if (parameterType.getName().startsWith("net.paoding")
                || parameterType.getName().startsWith("java.lang")
                || parameterType.getName().startsWith("java.util")
                || parameterType.getName().startsWith(appPackageName)) {
            return parameterType.getSimpleName();
        }
        return parameterType.getName();
    }

    public void destroy() {

    }
}


text:
<?php

namespace ElkArte\sources\subs\SessionHandler;

/**
 * Class DatabaseHandler
 *
 * @package ElkArte\sources\subs\SessionHandler
 */
class DatabaseHandler extends SessionHandler
{
	/**
	 * {@inheritdoc}
	 */
	public function destroy($sessionId)
	{
		// Better safe than sorry
		if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $sessionId) == 0)
		{
			return false;
		}

		// Just delete the row...
		$this->_db->query('', '
			DELETE FROM {db_prefix}sessions
			WHERE session_id = {string:session_id}',
			array(
				'session_id' => $sessionId,
			)
		);

		return true;
	}

	/**
	 * {@inheritdoc}
	 */
	public function gc($maxLifetime)
	{
		// Just set to the default or lower?  Ignore it for a higher value. (hopefully)
		if (!empty($this->_modSettings['databaseSession_lifetime']) && ($maxLifetime <= 1440 || $this->_modSettings['databaseSession_lifetime'] > $maxLifetime))
		{
			$maxLifetime = max($this->_modSettings['databaseSession_lifetime'], 60);
		}

		// Clean up after yerself ;).
		$this->_db->query('', '
			DELETE FROM {db_prefix}sessions
			WHERE last_update < {int:last_update}',
			array(
				'last_update' => time() - $maxLifetime,
			)
		);

		return $this->_db->affected_rows() != 0;
	}

	/**
	 * {@inheritdoc}
	 */
	public function read($sessionId)
	{
		if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $sessionId) == 0)
		{
			return '';
		}

		// Look for it in the database.
		$result = $this->_db->query('', '
			SELECT data
			FROM {db_prefix}sessions
			WHERE session_id = {string:session_id}
			LIMIT 1',
			array(
				'session_id' => $sessionId,
			)
		);
		list ($sessionData) = $this->_db->fetch_row($result);
		$this->_db->free_result($result);

		return empty($sessionData) ? '' : $sessionData;
	}

	/**
	 * {@inheritdoc}
	 */
	public function write($sessionId, $data)
	{
		if (preg_match('~^[A-Za-z0-9,-]{16,64}$~', $sessionId) == 0)
		{
			return false;
		}

		// First try to update an existing row...
		$this->_db->query('', '
			UPDATE {db_prefix}sessions
			SET data = {string:data}, last_update = {int:last_update}
			WHERE session_id = {string:session_id}',
			array(
				'last_update' => time(),
				'data' => $data,
				'session_id' => $sessionId,
			)
		);

		// If that didn't work, try inserting a new one.
		if ($this->_db->affected_rows() == 0)
		{
			$this->_db->insert('ignore',
				'{db_prefix}sessions',
				array('session_id' => 'string', 'data' => 'string', 'last_update' => 'int'),
				array($sessionId, $data, time()),
				array('session_id')
			);
		}

		return true;
	}
}

redpajama_set_name: RedPajamaGithub


text:
#include <linux/percpu.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>

#include "rds.h"

DEFINE_PER_CPU_SHARED_ALIGNED(struct rds_statistics, rds_stats);
EXPORT_PER_CPU_SYMBOL_GPL(rds_stats);

/* :.,$s/unsigned long\>.*\<s_\(.*\);/"\1",/g */

static const char *const rds_stat_names[] = {
	"conn_reset",
	"recv_drop_bad_checksum",
	"recv_drop_old_seq",
	"recv_drop_no_sock",
	"recv_drop_dead_sock",
	"recv_deliver_raced",
	"recv_delivered",
	"recv_queued",
	"recv_immediate_retry",
	"recv_delayed_retry",
	"recv_ack_required",
	"recv_rdma_bytes",
	"recv_ping",
	"send_queue_empty",
	"send_queue_full",
	"send_sem_contention",
	"send_sem_queue_raced",
	"send_immediate_retry",
	"send_delayed_retry",
	"send_drop_acked",
	"send_ack_required",
	"send_queued",
	"send_rdma",
	"send_rdma_bytes",
	"send_pong",
	"page_remainder_hit",
	"page_remainder_miss",
	"copy_to_user",
	"copy_from_user",
	"cong_update_queued",
	"cong_update_received",
	"cong_send_error",
	"cong_send_blocked",
};

void rds_stats_info_copy(struct rds_info_iterator *iter,
			 uint64_t *values, const char *const *names, size_t nr)
{
	struct rds_info_counter ctr;
	size_t i;

	for (i = 0; i < nr; i++) {
		BUG_ON(strlen(names[i]) >= sizeof(ctr.name));
		strncpy(ctr.name, names[i], sizeof(ctr.name) - 1);
		ctr.value = values[i];

		rds_info_copy(iter, &ctr, sizeof(ctr));
	}
}
EXPORT_SYMBOL_GPL(rds_stats_info_copy);

/*
 * This gives global counters across all the transports.  The strings
 * are copied in so that the tool doesn't need knowledge of the specific
 * stats that we're exporting.  Some are pretty implementation dependent
 * and may change over time.  That doesn't stop them from being useful.
 *
 * This is the only function in the chain that knows about the byte granular
 * length in userspace.  It converts it to number of stat entries that the
 * rest of the functions operate in.
 */
static void rds_stats_info(struct socket *sock, unsigned int len,
			   struct rds_info_iterator *iter,
			   struct rds_info_lengths *lens)
{
	struct rds_statistics stats = {0, };
	uint64_t *src;
	uint64_t *sum;
	size_t i;
	int cpu;
	unsigned int avail;

	avail = len / sizeof(struct rds_info_counter);

	if (avail < ARRAY_SIZE(rds_stat_names)) {
		avail = 0;
		goto trans;
	}

	for_each_online_cpu(cpu) {
		src = (uint64_t *)&(per_cpu(rds_stats, cpu));
		sum = (uint64_t *)&stats;
		for (i = 0; i < sizeof(stats) / sizeof(uint64_t); i++)
			*(sum++) += *(src++);
	}

	rds_stats_info_copy(iter, (uint64_t *)&stats, rds_stat_names,
			    ARRAY_SIZE(rds_stat_names));
	avail -= ARRAY_SIZE(rds_stat_names);

trans:
	lens->each = sizeof(struct rds_info_counter);
	lens->nr = rds_trans_stats_info_copy(iter, avail) +
		   ARRAY_SIZE(rds_stat_names);
}

void rds_stats_exit(void)
{
	rds_info_deregister_func(RDS_INFO_COUNTERS, rds_stats_info);
}

int __init rds_stats_init(void)
{
	rds_info_register_func(RDS_INFO_COUNTERS, rds_stats_info);
	return 0;
}


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Pedro Gonnet (pedro.gonnet@gmail.com)
// Copyright (C) 2016 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_MATHFUNCTIONSIMPL_H
#define EIGEN_MATHFUNCTIONSIMPL_H

namespace Eigen {

namespace internal {

/** \internal \returns the hyperbolic tan of \a a (coeff-wise)
    Doesn't do anything fancy, just a 13/6-degree rational interpolant which
    is accurate up to a couple of ulp in the range [-9, 9], outside of which
    the tanh(x) = +/-1.

    This implementation works on both scalars and packets.
*/
template<typename T>
T generic_fast_tanh_float(const T& a_x)
{
  // Clamp the inputs to the range [-9, 9] since anything outside
  // this range is +/-1.0f in single-precision.
  const T plus_9 = pset1<T>(9.f);
  const T minus_9 = pset1<T>(-9.f);
  const T x = pmax(pmin(a_x, plus_9), minus_9);
  // The monomial coefficients of the numerator polynomial (odd).
  const T alpha_1 = pset1<T>(4.89352455891786e-03f);
  const T alpha_3 = pset1<T>(6.37261928875436e-04f);
  const T alpha_5 = pset1<T>(1.48572235717979e-05f);
  const T alpha_7 = pset1<T>(5.12229709037114e-08f);
  const T alpha_9 = pset1<T>(-8.60467152213735e-11f);
  const T alpha_11 = pset1<T>(2.00018790482477e-13f);
  const T alpha_13 = pset1<T>(-2.76076847742355e-16f);

  // The monomial coefficients of the denominator polynomial (even).
  const T beta_0 = pset1<T>(4.89352518554385e-03f);
  const T beta_2 = pset1<T>(2.26843463243900e-03f);
  const T beta_4 = pset1<T>(1.18534705686654e-04f);
  const T beta_6 = pset1<T>(1.19825839466702e-06f);

  // Since the polynomials are odd/even, we need x^2.
  const T x2 = pmul(x, x);

  // Evaluate the numerator polynomial p.
  T p = pmadd(x2, alpha_13, alpha_11);
  p = pmadd(x2, p, alpha_9);
  p = pmadd(x2, p, alpha_7);
  p = pmadd(x2, p, alpha_5);
  p = pmadd(x2, p, alpha_3);
  p = pmadd(x2, p, alpha_1);
  p = pmul(x, p);

  // Evaluate the denominator polynomial p.
  T q = pmadd(x2, beta_6, beta_4);
  q = pmadd(x2, q, beta_2);
  q = pmadd(x2, q, beta_0);

  // Divide the numerator by the denominator.
  return pdiv(p, q);
}

template<typename RealScalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
RealScalar positive_real_hypot(const RealScalar& x, const RealScalar& y)
{
  EIGEN_USING_STD_MATH(sqrt);
  RealScalar p, qp;
  p = numext::maxi(x,y);
  if(p==RealScalar(0)) return RealScalar(0);
  qp = numext::mini(y,x) / p;
  return p * sqrt(RealScalar(1) + qp*qp);
}

template<typename Scalar>
struct hypot_impl
{
  typedef typename NumTraits<Scalar>::Real RealScalar;
  static EIGEN_DEVICE_FUNC
  inline RealScalar run(const Scalar& x, const Scalar& y)
  {
    EIGEN_USING_STD_MATH(abs);
    return positive_real_hypot<RealScalar>(abs(x), abs(y));
  }
};

} // end namespace internal

} // end namespace Eigen

#endif // EIGEN_MATHFUNCTIONSIMPL_H


text:
class CourseSectionsController < ApplicationController
  def show
    @course_section = CourseSection.find(params[:id])
    @buddyship = @course_section.buddyships.new
    @enemyship = @course_section.enemyships.new
    @student_course_section = StudentCourseSection.new
    @assignment = @course_section.assignments.new
    assignments_to_paginate = Assignment.where(course_section_id: @course_section.id)
    @assignments = assignments_to_paginate.paginate(:page => params[:page], :per_page => 5)
    @tests = @assignments.where(category:"Test").paginate(:page => params[:page], :per_page => 5)
    @homeworks = @assignments.where(category:"Homework").paginate(:page => params[:page], :per_page => 5)
    @classworks = @assignments.where(category:"Classwork").paginate(:page => params[:page], :per_page => 5)
    @assignments_hash = Assignment.all_by_category(@course_section)
  end

  def new
    @teacher = Teacher.find(params[:teacher_id])
    @course_section = CourseSection.new(course_teacher_assignment_id: params[:course_section][:course_teacher_assignment_id])
    @course_teacher_assignment = CourseTeacherAssignment.find(params[:course_section][:course_teacher_assignment_id])
  end

  def create
    #binding.pry
    @teacher = Teacher.find(params[:teacher_id])
    @course_section = CourseSection.create(course_teacher_assignment_id: params[:course_section][:course_teacher_assignment_id], name: params[:course_section][:name])
    if @course_section.save
      flash[:notice] = "Class successfully created!"
      redirect_to teacher_class_path(@teacher, @course_section)
    else
      flash.now[:alert] = "Class could not be created!"
      render :new
    end
  end

  def update
    @course_section = CourseSection.find(params[:id])
    @course_section.update(course_section_params)
    flash[:notice] = "Class succesfully updated!"
    redirect_to(:back)
  end

  private
    def course_section_params
      params.require(:course_section).permit(:name)
    end

end


text:
struct list_node {
	struct list_head link;
	int data;
};

struct list_node_forward {
	struct list_node_forward *next;
	int data;
};

int comp_list_node(void *, const void *x, const void *y)
{
	return generic_compare(((const list_node *)x)->data, ((const list_node *)y)->data);
}

int comp_list_node_forward(void *, const void *x, const void *y)
{
	return generic_compare(((const list_node_forward *)x)->data, ((const list_node_forward *)y)->data);
}

int main()
{
	LIST_HEAD(head);
	struct list_node_forward fhead, *fn = &fhead;
	struct list_node *node;
	srand((int)time(NULL));

	// insert some nodes
	for (int i = 0; i < 10000; i++) {
		node = new list_node;
		node->data = rand();
		list_add_tail(&node->link, &head);
		fn->next = new list_node_forward;
		fn->next->data = rand();
		fn = fn->next;
	}

	fn->next = NULL;

	list_sort(NULL, &head, comp_list_node);
	list_sort_forward(NULL, (list_head_forward *)&fhead, comp_list_node_forward);

	// verify and sorted list
	struct list_node *tmp;
	list_for_each_entry_safe(node, tmp, &head, link) {
		if (&tmp->link != &head)
			assert(comp_list_node(NULL, node, tmp) <= 0);
		delete node;
	}

	for (fn = fhead.next; fn;) {
		list_node_forward *next = fn->next? fn->next: fn;
		assert(comp_list_node_forward(NULL, fn, next) <= 0);
		delete fn;
		if (fn == next)
			break;
		fn = next;
	}

	printf("passed\n");

	return 0;
}


text:
var ChannelDownload = (function(){

	function start() {
		Helpers.Application.isAndroid() ? _getAndroid() : _getIphone();
	}

	function _getAndroid() {
		var zipfile = require("com.websiteburo.androzip");

		var _writeZip = function() {
			Ti.API.info("WRITING FILE");
			var zipPath = Ti.Filesystem.resourcesDirectory + Ti.Filesystem.separator + "android_channels.zip";
			var dirFullPath = Ti.Filesystem.resourcesDirectory + Ti.Filesystem.separator + 'images';
			var dir = Titanium.Filesystem.getFile(dirFullPath);

			var f = Ti.Filesystem.getFile(zipPath);
		  f.write(this.responseData);
			Ti.API.info("FINISHING WRITING");
			Ti.API.info(f.nativePath);

			Ti.API.info("Full path:");
			Ti.API.info(dirFullPath);
			Ti.API.info("RESOURCES");
			Ti.API.info(Ti.Filesystem.resourcesDirectory);
			zipfile.extract(dataDir+"/android_channels.zip", dirFullPath);
			Ti.API.info("DONE!");
		}

		App.base_url = "http://looprecur.com";
		App.http_client.get("/android_channels.zip", {success: _writeZip, error: function(e){Ti.API.info(e)}});
	}

	function _getIphone() {
		var zipfile = require("zipfile");

		var _writeZip = function() {
			var f = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'channels.zip');
		  f.write(this.responseData);

			var dataDir = Ti.Filesystem.resourcesDirectory.slice(0,Ti.Filesystem.resourcesDirectory.length - 1).replace('file://localhost','').replace(/%20/g,'\\ ');
			zipfile.extract(dataDir+"/channels.zip", dataDir+"/images/channels");
		}

		App.base_url = "http://looprecur.com";
		App.http_client.get("/channels.zip", {success: _writeZip, error: function(e){Ti.API.info(e)}});
	}

	return {start: start}
})();


text:
namespace codex.debugbar.util
{
    export function camel2dash(str:string) : string{
        return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
    }

    var kindsOf:any = {};
    'Number String Boolean Function RegExp Array Date Error'.split(' ').forEach(function (k)
    {
        kindsOf['[object ' + k + ']'] = k.toLowerCase();
    });
    var nativeTrim = String.prototype.trim;

    var entityMap = {
        "&": "&",
        "<": "<",
        ">": ">",
        '"': '"',
        "'": ''',
        "/": '/'
    };

    /**
     * Returns the type of a variablse
     *
     * @param value
     * @returns {any}
     */
    export function kindOf(value:any):any
    {
        // Null or undefined.
        if (value == null) {
            return String(value);
        }
        // Everything else.
        return kindsOf[kindsOf.toString.call(value)] || 'object';
    }

    /**
     * If val is not defined, return def as default
     * @param val
     * @param def
     * @returns {any}
     */
    export function def(val, def)
    {
        return defined(val) ? val : def;
    }

    /**
     * Checks wether the passed variable is defined
     *
     * @param obj
     * @returns {boolean}
     */
    export function defined(obj?:any)
    {
        return !_.isUndefined(obj);
    }

    /**
     * Get a random generated id string
     *
     * @param length
     * @returns {string}
     */
    export function getRandomId(length?:number):string
    {
        if (!_.isNumber(length)) {
            length = 15;
        }
        var text:string     = "";
        var possible:string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for (var i = 0; i < length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        return text;
    }
}


text:
package org.apache.jackrabbit.oak.plugins.index.elastic;

import org.apache.jackrabbit.oak.api.ContentRepository;
import org.apache.jackrabbit.oak.plugins.index.PropertyIndexCommonTest;
import org.junit.After;
import org.junit.ClassRule;

import java.io.IOException;

public class ElasticPropertyIndexCommonTest extends PropertyIndexCommonTest {

    // Set this connection string as
    // <scheme>://<hostname>:<port>?key_id=<>,key_secret=<>
    // key_id and key_secret are optional in case the ES server
    // needs authentication
    // Do not set this if docker is running and you want to run the tests on docker instead.
    private static String elasticConnectionString = System.getProperty("elasticConnectionString");
    @ClassRule
    public static ElasticConnectionRule elasticRule = new ElasticConnectionRule(elasticConnectionString);

    public ElasticPropertyIndexCommonTest() {
        indexOptions = new ElasticIndexOptions();
    }

    @Override
    protected ContentRepository createRepository() {
        repositoryOptionsUtil = new ElasticTestRepositoryBuilder(elasticRule).build();
        return repositoryOptionsUtil.getOak().createContentRepository();
    }

    @Override
    protected void createTestIndexNode() {
        setTraversalEnabled(false);
    }

    /*
    Close the ES connection after every test method execution
     */
    @After
    public void cleanup() throws IOException {
        elasticRule.closeElasticConnection();
    }
}


text:
namespace cc {

void FakeOutputSurfaceClient::DidReceiveSwapBuffersAck(const gfx::SwapTimings&,
                                                       gfx::GpuFenceHandle) {
  swap_count_++;
}

}  // namespace cc


text:
title: Cherish Thine .dotfiles
date: 2018-11-12 11:23:00 -06:00
tags:
- development
- setup
- tech
custom_type: post
subtitle: Setting up a new Mac is so much easier these days
---

Earlier this year, I started to feel it was time to buy a new Mac, but wanted to make a sensible and adult decision. I'd wait till the Fall, see what Apple had announced for the year, and then decide.

The Fall Apple events came and went, and none of the new announcements spoke to me. While the Mac mini looked interesting, I'd need to plug in an eGPU for the video editing I do. I didn't want to maintain another expensive piece of hardware.

One day while I was hanging out [in the #applenerds channel in the Changelog Slack](https://changelog.com/community), someone brought up buying refurbished. One of my previous Mac's was purchased refurbished from Apple, and I'd had no issues with it. To my surprise, there was a refurbished 2018 MacBook Pro with a bigger hard drive, faster processor, and more RAM than my previous Mac. After talking to my wife, the buy button was clicked.

Getting a new machine always makes me ner-cited (nervous and excited). You get used to the way you've setup a machine—which depending how long you've had it—there's no telling how many settings you've customized just right to your tastes.

All this makes me a lot less anxious these days though. Ever since I started version controlling my `.dotfiles` on GitHub, and putting all my files in Dropbox, moving to a new machine is a lot simpler. Sure, it'll still take you a few hours. This last time took about 3-4 hours, but it was mostly headache free. And more importantly, I don't have that feeling of, "did I forget anything on my old machine?"

If you're curious about how I do it, [I've written extensively on my process for setting up new machines](/2016/12/speeding-up-your-new-mac-setup/). It could probably be automated even furthur, but it's a pretty sweet setup.


text:
using System;
using System.Web;
using System.Web.Routing;
using Valcon.HelloWorld.Configuration;

namespace Valcon.HelloWorld
{
    public class Global : HttpApplication
    {
        protected void Application_Start(object sender, EventArgs args)
        {
            var routes = RouteTable.Routes;
            FubuStructureMapBootstrapper.Bootstrap(routes);
        }
    }
}


text:
package com.elytradev.movingworld.common.chunk.assembly;

import com.elytradev.movingworld.MovingWorldMod;
import com.elytradev.movingworld.common.chunk.LocatedBlock;
import com.elytradev.movingworld.common.chunk.MovingWorldAssemblyInteractor;
import com.elytradev.movingworld.common.entity.EntityMovingWorld;
import com.elytradev.movingworld.common.tile.TileMovingMarkingBlock;
import com.elytradev.movingworld.common.util.LocatedBlockList;
import com.elytradev.movingworld.common.util.MaterialDensity;
import io.netty.buffer.ByteBuf;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;

import java.util.ArrayList;

public class AssembleResult {

    public final LocatedBlockList assembledBlocks = new LocatedBlockList();
    public BlockPos offset;
    public MovingWorldAssemblyInteractor assemblyInteractor;
    LocatedBlock movingWorldMarkingBlock;
    ResultType resultType;
    int blockCount;
    int tileEntityCount;
    float mass;

    public AssembleResult(ResultType resultCode, ByteBuf buf) {
        this.resultType = resultCode;
        if (resultCode == ResultType.RESULT_NONE) return;
        blockCount = buf.readInt();
        tileEntityCount = buf.readInt();
        mass = buf.readFloat();
    }

    public AssembleResult(NBTTagCompound tag, World world) {
        resultType = ResultType.fromByte(tag.getByte("res"));
        blockCount = tag.getInteger("blockc");
        tileEntityCount = tag.getInteger("tec");
        mass = tag.getFloat("mass");
        offset = new BlockPos(-tag.getInteger("xO"),
                tag.getInteger("yO"),
                tag.getInteger("zO"));
        if (tag.hasKey("list")) {
            NBTTagList list = tag.getTagList("list", 10);
            for (int i = 0; i < list.tagCount(); i++) {
                NBTTagCompound comp = list.getCompoundTagAt(i);
                assembledBlocks.add(new LocatedBlock(comp, world));
            }
        }
        if (tag.hasKey("marker")) {
            NBTTagCompound comp = tag.getCompoundTag("marker");
            movingWorldMarkingBlock = new LocatedBlock(comp, world);
        }
    }

    AssembleResult() {
        clear();
    }

    void assembleBlock(LocatedBlock lb) {
        assembledBlocks.add(lb);
        blockCount = assembledBlocks.size();
        if (lb.tileEntity != null) {
            tileEntityCount++;
        }
        mass += MaterialDensity.getDensity(lb.blockState);
        offset = new BlockPos(Math.min(offset.getX(), lb.blockPos.getX()),
                Math.min(offset.getY(), lb.blockPos.getY()),
                Math.min(offset.getZ(), lb.blockPos.getZ()));
    }

    public void clear() {
        resultType = ResultType.RESULT_NONE;
        movingWorldMarkingBlock = null;
        assembledBlocks.clear();
        offset = new BlockPos(BlockPos.ORIGIN);
    }

    public EntityMovingWorld getEntity(World world, EntityMovingWorld entity) {
        if (!isOK()) return null;

        if (entity == null) {
            MovingWorldMod.LOG.error("A null movingWorld was attempted!");
            return null;
        }

        EnumFacing facing = assemblyInteractor.getFrontDirection(movingWorldMarkingBlock);
        BlockPos riderDestination = new BlockPos(movingWorldMarkingBlock.blockPos.getX() - offset.getX(), movingWorldMarkingBlock.blockPos.getY() - offset.getY(), movingWorldMarkingBlock.blockPos.getZ() - offset.getZ());

        entity.setRiderDestination(facing, riderDestination);
        entity.getMobileChunk().setCreationSpotBiomeGen(world.getBiome(movingWorldMarkingBlock.blockPos));

        boolean doTileDropsInWorld = world.getGameRules().getBoolean("doTileDrops");
        world.getGameRules().setOrCreateGameRule("doTileDrops", "false");

        ArrayList<LocatedBlockList> separatedLbLists = assembledBlocks.getSortedAssemblyBlocks();

        try {
            for (LocatedBlockList locatedBlockList : separatedLbLists) {
                if (locatedBlockList != null && !locatedBlockList.isEmpty()) {
                    setWorldBlocksToAir(world, entity, locatedBlockList);
                }
            }
        } catch (Exception e) {
            resultType = ResultType.RESULT_ERROR_OCCURED;
            world.getGameRules().setOrCreateGameRule("doTileDrops", String.valueOf(doTileDropsInWorld));
            MovingWorldMod.LOG.error("Result code: RESULT ERROR OCCURRED was reached when attempting to getEntity from assembly result. Printing stacktrace...");
            MovingWorldMod.LOG.error(e);
            e.printStackTrace();
            return null;
        }

        world.getGameRules().setOrCreateGameRule("doTileDrops", String.valueOf(doTileDropsInWorld));

        entity.getMobileChunk().setChunkModified();
        entity.getMobileChunk().onChunkLoad();
        entity.setLocationAndAngles(offset.getX() + entity.getMobileChunk().getCenterX(), offset.getY(), offset.getZ() + entity.getMobileChunk().getCenterZ(), 0F, 0F);
        entity.assembleResultEntity();

        return entity;
    }

    public void setWorldBlocksToAir(World world, EntityMovingWorld entityMovingWorld, LocatedBlockList locatedBlocks) {
        boolean setFluids = false;

        LocatedBlockList setAirState2 = new LocatedBlockList();

        if (movingWorldMarkingBlock != null && movingWorldMarkingBlock.tileEntity instanceof TileMovingMarkingBlock
                && ((TileMovingMarkingBlock) movingWorldMarkingBlock.tileEntity).removedFluidBlocks != null &&
                !((TileMovingMarkingBlock) movingWorldMarkingBlock.tileEntity).removedFluidBlocks.isEmpty()) {

            setFluids = true;
        }

        TileEntity tileentity;
        BlockPos iPos;
        for (LocatedBlock lb : locatedBlocks) {
            iPos = new BlockPos(lb.blockPos.getX() - offset.getX(), lb.blockPos.getY() - offset.getY(), lb.blockPos.getZ() - offset.getZ());

            tileentity = lb.tileEntity;
            if (tileentity != null || lb.blockState.getBlock().hasTileEntity(lb.blockState) && (tileentity = world.getTileEntity(lb.blockPos)) != null) {
                tileentity.validate();
            }
            if (entityMovingWorld.getMobileChunk().addBlockWithState(iPos, lb.blockState)) {
                if (lb.tileEntity != null && movingWorldMarkingBlock.tileEntity != null && lb.blockPos.equals(movingWorldMarkingBlock.blockPos)) {
                    entityMovingWorld.getMobileChunk().marker = lb;
                }
                setAirState2.add(lb);

                entityMovingWorld.getMobileChunk().setTileEntity(iPos, tileentity);
            }
        }

        for (LocatedBlock lb : setAirState2) {
            try {
                world.removeTileEntity(lb.blockPos);
                world.setBlockState(lb.blockPos, Blocks.AIR.getDefaultState(), 2);
            } catch (Exception e) {
                MovingWorldMod.LOG.warn("Failed to remove a block from the world, forcing...", e);
                forceBlockRemoval(world, lb);
            }
        }

        for (LocatedBlock lb : locatedBlocks) {
            try {
                world.removeTileEntity(lb.blockPos);
                world.setBlockToAir(lb.blockPos);
            } catch (Exception e) {
                MovingWorldMod.LOG.warn("Failed to remove a block from the world, forcing...", e);
                forceBlockRemoval(world, lb);
            }
        }

        if (setFluids) {
            ((TileMovingMarkingBlock) movingWorldMarkingBlock.tileEntity).removedFluidBlocks.stream()
                    .filter(fluid -> fluid != null && world.isAirBlock(fluid.blockPos))
                    .forEach(fluid -> world.setBlockState(fluid.blockPos, fluid.blockState, 2));

            ((TileMovingMarkingBlock) movingWorldMarkingBlock.tileEntity).removedFluidBlocks.stream()
                    .filter(fluid -> fluid != null && world.isAirBlock(fluid.blockPos))
                    .forEach(fluid -> world.setBlockState(fluid.blockPos, fluid.blockState, 3));
        }
    }

    private void forceBlockRemoval(World world, LocatedBlock block) {
        world.setTileEntity(block.blockPos, null);
        try {
            world.setBlockState(block.blockPos, Blocks.AIR.getDefaultState(), 2); // Try and remove the block from the world, if this fails then some dev doesn't know what they're doing...
        } catch (Exception e) {
            MovingWorldMod.LOG.warn("Caught exception when removing a block from the world, attempting fallback method...", e);
            try {
                world.setBlockToAir(block.blockPos);
            } catch (Exception secondE) {
                MovingWorldMod.LOG.warn("Fallback failed, attempting manual removal without telling the block about it...", secondE);
                try {
                    Chunk chunk = world.getChunkFromBlockCoords(block.blockPos);
                    ExtendedBlockStorage blockStorage = chunk.getBlockStorageArray()[block.blockPos.getY() >> 4];
                    blockStorage.set(block.blockPos.getX() & 15, block.blockPos.getY() >> 4, block.blockPos.getZ() & 15, Blocks.AIR.getDefaultState());
                    chunk.markDirty();
                    // Just tell the world about it after the block isn't in storage anymore. In an ideal world this should always work...
                    world.setBlockToAir(block.blockPos);
                } catch (Exception thirdE) {
                    MovingWorldMod.LOG.error("At this point I don't really know what to tell you, I've done everything I could yet I still failed.", thirdE);
                    throw thirdE;
                }
            }
        }
    }

    public ResultType getType() {
        return resultType;
    }

    public boolean isOK() {
        return resultType == ResultType.RESULT_OK || resultType == ResultType.RESULT_OK_WITH_WARNINGS;
    }

    public LocatedBlock getShipMarker() {
        return movingWorldMarkingBlock;
    }

    public int getBlockCount() {
        return blockCount;
    }

    public int getTileEntityCount() {
        return tileEntityCount;
    }

    public float getMass() {
        return mass;
    }

    public void checkConsistent(World world) {
        boolean warn = false;
        for (LocatedBlock lb : assembledBlocks) {
            IBlockState blockState = world.getBlockState(lb.blockPos);
            Block block = blockState.getBlock();
            if (block != lb.blockState.getBlock()) {
                resultType = ResultType.RESULT_INCONSISTENT;
                return;
            }
            if (blockState != lb.blockState) {
                warn = true;
            }
        }
        resultType = warn ? ResultType.RESULT_OK_WITH_WARNINGS : ResultType.RESULT_OK;
    }

    public void writeNBTFully(NBTTagCompound tag) {
        writeNBTMetadata(tag);
        NBTTagList list = new NBTTagList();
        for (LocatedBlock lb : assembledBlocks) {
            NBTTagCompound comp = new NBTTagCompound();
            lb.writeToNBT(comp);
            list.appendTag(comp);
        }
        tag.setTag("list", list);

        if (movingWorldMarkingBlock != null) {
            NBTTagCompound comp = new NBTTagCompound();
            movingWorldMarkingBlock.writeToNBT(comp);
            tag.setTag("marker", comp);
        }
    }

    public void writeNBTMetadata(NBTTagCompound tag) {
        tag.setByte("res", getType().toByte());
        tag.setInteger("blockc", getBlockCount());
        tag.setInteger("tec", getTileEntityCount());
        tag.setFloat("mass", getMass());
        tag.setInteger("xO", offset.getX());
        tag.setInteger("yO", offset.getY());
        tag.setInteger("zO", offset.getZ());
    }

    public ByteBuf toByteBuf(ByteBuf buf) {
        buf.writeByte(getType().toByte());
        buf.writeInt(getBlockCount());
        buf.writeInt(getTileEntityCount());
        buf.writeFloat(getMass());
        if (assemblyInteractor != null)
            assemblyInteractor.toByteBuf(buf);

        return buf;
    }

    public enum ResultType {
        RESULT_NONE, RESULT_OK, RESULT_BLOCK_OVERFLOW, RESULT_MISSING_MARKER, RESULT_ERROR_OCCURED,
        RESULT_BUSY_COMPILING, RESULT_INCONSISTENT, RESULT_OK_WITH_WARNINGS;

        public static byte toByte(ResultType action) {
            switch (action) {
                case RESULT_OK:
                    return (byte) 1;
                case RESULT_BLOCK_OVERFLOW:
                    return (byte) 2;
                case RESULT_MISSING_MARKER:
                    return (byte) 3;
                case RESULT_ERROR_OCCURED:
                    return (byte) 4;
                case RESULT_BUSY_COMPILING:
                    return (byte) 5;
                case RESULT_INCONSISTENT:
                    return (byte) 6;
                case RESULT_OK_WITH_WARNINGS:
                    return (byte) 7;
                default:
                    return (byte) 0;
            }
        }

        public static ResultType fromByte(byte actionInt) {
            switch (actionInt) {
                case 1:
                    return RESULT_OK;
                case 2:
                    return RESULT_BLOCK_OVERFLOW;
                case 3:
                    return RESULT_MISSING_MARKER;
                case 4:
                    return RESULT_ERROR_OCCURED;
                case 5:
                    return RESULT_BUSY_COMPILING;
                case 6:
                    return RESULT_INCONSISTENT;
                case 7:
                    return RESULT_OK_WITH_WARNINGS;
                default:
                    return RESULT_NONE;
            }
        }

        public byte toByte() {
            return ResultType.toByte(this);
        }
    }

}


text:
package org.openbel.framework.api;

import java.util.HashSet;
import java.util.Set;

import org.openbel.framework.common.enums.RelationshipType;

/**
 *
 * @author julianjray
 *
 */
public class RelationshipTypeFilterCriteria extends FilterCriteria {

    private Set<RelationshipType> valueSet;

    /**
     *
     */
    public RelationshipTypeFilterCriteria() {
        super();
        this.valueSet = new HashSet<RelationshipType>();
    }

    /**
     *
     * @return
     */
    @Override
    public Set<RelationshipType> getValues() {
        return valueSet;
    }

    /**
     *
     * @param relationshipType
     * @return current {@link RelationshipTypeFilterCriteria} for chaining
     */
    public RelationshipTypeFilterCriteria
            add(RelationshipType relationshipType) {
        valueSet.add(relationshipType);
        return this;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else if (obj == null) {
            return false;
        } else if (!(obj instanceof RelationshipTypeFilterCriteria)) {
            return false;
        } else {
            RelationshipTypeFilterCriteria other =
                    (RelationshipTypeFilterCriteria) obj;
            return ((isInclude() == other.isInclude()) && valueSet
                    .equals(other.valueSet));
        }
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hash = 0;
        hash += (isInclude() ? 1 : 0);
        hash *= prime;
        hash += valueSet.hashCode();
        return hash;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Revision$ -->
<section xml:id="autogen" xml:lang="pt_BR">
 <title>Texto autogerado</title>
 <variablelist>
  <varlistentry>
   <term>toc</term>
   <listitem>
    <simpara>Índice</simpara>
   </listitem>
  </varlistentry>
  <varlistentry>
   <term>warning</term>
   <listitem>
    <simpara>Aviso</simpara>
   </listitem>
  </varlistentry>
  <varlistentry>
   <term>note</term>
   <listitem>
    <simpara>Nota</simpara>
   </listitem>
  </varlistentry>
  <varlistentry>
   <term>caution</term>
   <listitem>
    <simpara>Cuidado</simpara>
   </listitem>
  </varlistentry>
  <varlistentry>
   <term>tip</term>
   <listitem>
    <simpara>Dica</simpara>
   </listitem>
  </varlistentry>
  <varlistentry>
   <term>important</term>
   <listitem>
    <simpara>Importante</simpara>
   </listitem>
  </varlistentry>
  <varlistentry>
   <term>by</term>
   <listitem>
    <simpara>por</simpara>
   </listitem>
  </varlistentry>
  <varlistentry>
   <term>editedby</term>
   <listitem>
    <simpara>Editado por</simpara>
   </listitem>
  </varlistentry>
  <varlistentry>
   <term>example</term>
   <listitem>
    <simpara>Exemplo #</simpara>
   </listitem>
  </varlistentry>
  <varlistentry>
   <term>unknownversion</term>
   <listitem>
    <simpara>Não há informação de versão disponível, talvez apenas no SVN</simpara>
   </listitem>
  </varlistentry>
  <varlistentry>
   <term>refname</term>
   <listitem>
    <simpara>NOME</simpara>
   </listitem>
  </varlistentry>
  <varlistentry>
   <term>refsynopsis</term>
   <listitem>
    <simpara>SINOPSE</simpara>
   </listitem>
  </varlistentry>
  <varlistentry>
   <term>mediaobject</term>
   <listitem>
    <simpara>[MÍDIA NÃO DISPONÍVEL]</simpara>
   </listitem>
  </varlistentry>
 </variablelist>
</section>


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/mystyles.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/easyui.css') }}">

Choosing a university and major is a big decision. Beyond the academic ranking of a school and your interest in STEM, the financial decisions you make now will impact you well into the future. Students with STEM degrees generally earn more money,however tuition rates and job opportunities vary by state. By thinking about your academic and future professional career as an investment, you can start planning for your future right now. Start by using this exploratory tool to investigate salary trends, job market saturation, and calculate a simplified return on investment score by university.

        <fieldset>

            Choose a state:

                <select id="statelist"></select>

            Choose a university:

                <select id="unislist" ></select>

            Choose a major:

                <select id="majorlist" ></select>

ROI for  in

                Tuition:

                Starting Salary in :

                Peak Salary in :

                Return On Investment (ROI):

  Click here  for more information about data sources and how ROI is calculated.

        </fieldset>

                        State
                        Average Tuition ($)
                        Average Starting Salary ($)
                        Average Peak Salary ($)
                        10-Year ROI Score


text:
export DEBIAN_FRONTEND=noninteractive

# update
apt-get update -qq

# timezone
echo "Asia/Tokyo" > /etc/timezone
dpkg-reconfigure -f noninteractive tzdata

# git
apt-get install -y git-core

# misc
apt-get install -y man

# vim
apt-get install -y vim


text:
package edu.iu.grid.oim.view.divrep.form;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;

import com.divrep.DivRepEvent;
import com.divrep.DivRepEventListener;
import com.divrep.common.DivRepCheckBox;
import com.divrep.common.DivRepForm;
import com.divrep.common.DivRepStaticContent;
import com.divrep.common.DivRepTextArea;
import com.divrep.common.DivRepTextBox;
import com.divrep.validator.DivRepUniqueValidator;
import com.divrep.validator.DivRepUrlValidator;

import edu.iu.grid.oim.lib.Authorization;
import edu.iu.grid.oim.lib.Footprints;
import edu.iu.grid.oim.lib.AuthorizationException;
import edu.iu.grid.oim.model.ContactRank;
import edu.iu.grid.oim.model.UserContext;
import edu.iu.grid.oim.model.UserContext.MessageType;
import edu.iu.grid.oim.model.db.ContactTypeModel;
import edu.iu.grid.oim.model.db.ContactModel;
import edu.iu.grid.oim.model.db.ResourceAliasModel;
import edu.iu.grid.oim.model.db.ResourceContactModel;
import edu.iu.grid.oim.model.db.ResourceGroupModel;
import edu.iu.grid.oim.model.db.ResourceServiceDetailModel;
import edu.iu.grid.oim.model.db.ResourceServiceModel;
import edu.iu.grid.oim.model.db.ResourceWLCGModel;
import edu.iu.grid.oim.model.db.SCModel;
import edu.iu.grid.oim.model.db.ServiceModel;
import edu.iu.grid.oim.model.db.ResourceModel;
import edu.iu.grid.oim.model.db.SiteModel;
import edu.iu.grid.oim.model.db.VOModel;
import edu.iu.grid.oim.model.db.VOResourceOwnershipModel;
import edu.iu.grid.oim.model.db.record.ContactTypeRecord;
import edu.iu.grid.oim.model.db.record.ContactRecord;
import edu.iu.grid.oim.model.db.record.ResourceAliasRecord;
import edu.iu.grid.oim.model.db.record.ResourceContactRecord;
import edu.iu.grid.oim.model.db.record.ResourceGroupRecord;
import edu.iu.grid.oim.model.db.record.ResourceRecord;
import edu.iu.grid.oim.model.db.record.ResourceServiceDetailRecord;
import edu.iu.grid.oim.model.db.record.ResourceServiceRecord;
import edu.iu.grid.oim.model.db.record.ResourceWLCGRecord;
import edu.iu.grid.oim.model.db.record.SCRecord;
import edu.iu.grid.oim.model.db.record.SiteRecord;
import edu.iu.grid.oim.model.db.record.VORecord;
import edu.iu.grid.oim.model.db.record.VOResourceOwnershipRecord;
import edu.iu.grid.oim.view.ToolTip;
import edu.iu.grid.oim.view.divrep.AUPConfirmation;
import edu.iu.grid.oim.view.divrep.Confirmation;
import edu.iu.grid.oim.view.divrep.ContactEditor;
import edu.iu.grid.oim.view.divrep.URLListEditor;
import edu.iu.grid.oim.view.divrep.ResourceGroupSelector;
import edu.iu.grid.oim.view.divrep.ResourceServices;
import edu.iu.grid.oim.view.divrep.ResourceWLCG;
import edu.iu.grid.oim.view.divrep.VOResourceOwnership;

public class ResourceFormDE extends DivRepForm
{
    static Logger log = Logger.getLogger(ResourceFormDE.class);

    private UserContext context;

	protected Authorization auth;
	private Integer id;

	private DivRepTextBox name;
	private DivRepTextArea description;
	private DivRepTextBox fqdn;
	private DivRepTextBox url;

	private DivRepCheckBox active;
	private DivRepCheckBox disable;
	private ResourceGroupSelector resource_group_id;
	private URLListEditor aliases;
	private ResourceServices resource_services;
	private VOResourceOwnership owners;

	private DivRepCheckBox wlcg;
	private ResourceWLCG wlcg_section;

	private Confirmation confirmation;

	private DivRepTextArea comment;

	static public ArrayList<ContactTypeRecord.Info> ContactTypes;
	static {
		ContactTypes = new ArrayList<ContactTypeRecord.Info>();
		ContactTypes.add(new ContactTypeRecord.Info(1, "A contact who has registered this resource"));
		ContactTypes.add(new ContactTypeRecord.Info(9, "Gratia-accounting based resource-usage reports are sent out daily/weekly to these contacts"));
		ContactTypes.add(new ContactTypeRecord.Info(3, "GOC tickets when assigned to a support center of a resource are also sent to the primary resource admin contact (usually the sysadmin of a resource) via the ticket's CC mechanism. Admin contacts are also contacted by GOC staff and others to deal with system-administrative problems"));
		ContactTypes.add(new ContactTypeRecord.Info(2, "Security notifications sent out by the OSG security team are sent to primary and secondary security contacts for this resource"));
		ContactTypes.add(new ContactTypeRecord.Info(5, "Contacts who do not fall under any of the above types but would like to be able to edit this resource can be added as miscellaneous contact"));
	}

	private HashMap<Integer, ContactEditor> contact_editors = new HashMap();

	public ResourceFormDE(UserContext _context, ResourceRecord rec, String origin_url) throws AuthorizationException, SQLException
	{
		super(_context.getPageRoot(), origin_url);
		context = _context;
		auth = context.getAuthorization();

		id = rec.id;

		new DivRepStaticContent(this, "
Resource Information
");

		//pull vos for unique validator
		HashMap<Integer, String> resources = getResources();
		if(id != null) {
			//if doing update, remove my own name (I can use my own name)
			resources.remove(id);
		}

		name = new DivRepTextBox(this);
		name.setLabel("Name");
		name.setValue(rec.name);
		name.addValidator(new DivRepUniqueValidator<String>(resources.values()));
		name.setRequired(true);
		name.setSampleValue("Indiana_Sample_CE");

		fqdn = new DivRepTextBox(this);
		fqdn.setLabel("Fully Qualified Domain Name (FQDN) of this resource");
		fqdn.setValue(rec.fqdn);
		fqdn.addValidator(new DivRepUniqueValidator<String>(resources.values()));
		fqdn.setRequired(true);
		fqdn.setSampleValue("gate01.sample.edu");

		resource_group_id = new ResourceGroupSelector(this, context);
		resource_group_id.setRequired(true);
		if(rec.resource_group_id != null) {
			resource_group_id.setValue(rec.resource_group_id);
		}

		description = new DivRepTextArea(this);
		description.setLabel("Short Description");
		description.setValue(rec.description);
		description.setRequired(true);
		description.setSampleValue("This is a hidden gatekeeper accessible from the FermiGrid site only. It reports to Gratia and RSV directly but offsite jobs can only get to it via the FermiGrid job gateway fermigridosg1");

		url = new DivRepTextBox(this);
		url.setLabel("Information URL");
		url.setValue(rec.url);
		url.addValidator(DivRepUrlValidator.getInstance());
		url.setRequired(true);
		url.setSampleValue("http://sample.edu/information");

		new DivRepStaticContent(this, "
Resource FQDN Aliases (If Applicable)
");
		new DivRepStaticContent(this, "
If you used a DNS alias as their main gatekeeper or SE head node FQDN (as defined above), then you can add real host name(s) here as reverse alias(es).
");
		aliases = new URLListEditor (this);
		ResourceAliasModel ramodel = new ResourceAliasModel(context);
		if(id != null) {
			for(ResourceAliasRecord rarec : ramodel.getAllByResourceID(id)) {
				aliases.addUrl(rarec.resource_alias);
			}
		}

		new DivRepStaticContent(this, "
Resource Services
");
		//new DivRepStaticContent(this, "
Add, remove, modify services associated with your resource. For example, a CE or an SRM.
");
		ServiceModel smodel = new ServiceModel(context);
		resource_services = new ResourceServices(this, context/*, smodel.getAll()*/);

		ResourceServiceModel rsmodel = new ResourceServiceModel(context);
		if(id != null) {
			ResourceServiceDetailModel rsdmodel = new ResourceServiceDetailModel(context);
			ArrayList<ResourceServiceDetailRecord> details = rsdmodel.getAllByResourceID(id);
			for(ResourceServiceRecord rarec : rsmodel.getByResourceID(id)) {
				resource_services.addService(rarec, details);
			}
		} else {
			//add new one
			resource_services.addService(new ResourceServiceRecord(), null);
		}
		resource_services.setRequired(true);

		// Resource ownership stuff
		new DivRepStaticContent(this, "
Resource Ownership
");
		//new DivRepStaticContent(this, "
Add/modify VO ownership of this resource.
");
		VOModel vo_model = new VOModel(context);
		owners = new VOResourceOwnership(this, vo_model.getAll());
		VOResourceOwnershipModel voresowner_model = new VOResourceOwnershipModel(context);
		if(id != null) {
			for(VOResourceOwnershipRecord voresowner_rec : voresowner_model.getAllByResourceID(id)) {
				owners.addOwner(voresowner_rec);
			}
		} else {
			//add new one
			owners.addOwner(new VOResourceOwnershipRecord());
		}

		ToolTip tip = new ToolTip("Add, remove, modify various types of contacts associated with your resource. These contacts have the authorization to modify this resource. Each contact entry field shows you a list of contacts as you type a name.");
		new DivRepStaticContent(this, "
Contact Information "+tip.render()+"
");
		//new DivRepStaticContent(this, "
Add, remove, modify various types of contacts associated with your resource. These contacts have the authorization to modify this resource. Each contact entry field shows you a list of contacts as you type a name.
");

		HashMap<Integer/*contact_type_id*/, ArrayList<ResourceContactRecord>> voclist_grouped = null;
		if(id != null) {
			ResourceContactModel vocmodel = new ResourceContactModel(context);
			ArrayList<ResourceContactRecord> voclist = vocmodel.getByResourceID(id);
			voclist_grouped = vocmodel.groupByContactTypeID(voclist);
		} else {
			//set user's contact as submitter
			voclist_grouped = new HashMap<Integer, ArrayList<ResourceContactRecord>>();

			//prepopulate submitter
			ArrayList<ResourceContactRecord> submitter_list = new ArrayList<ResourceContactRecord>();
			ResourceContactRecord submitter = new ResourceContactRecord();
			submitter.contact_id = auth.getContact().id;
			submitter.contact_rank_id = 1;//primary
			submitter.contact_type_id = 1;//submitter
			submitter_list.add(submitter);
			voclist_grouped.put(1/*submitter*/, submitter_list);

			//prepopulatee admin contact
			ArrayList<ResourceContactRecord> admin_list = new ArrayList<ResourceContactRecord>();
			ResourceContactRecord admin = new ResourceContactRecord();
			admin.contact_id = auth.getContact().id;
			admin.contact_rank_id = 1;//primary
			admin.contact_type_id = 3;//admin
			admin_list.add(admin);
			voclist_grouped.put(3/*admin*/, admin_list);

			//security contact
			ArrayList<ResourceContactRecord> security_list = new ArrayList<ResourceContactRecord>();
			ResourceContactRecord security = new ResourceContactRecord();
			security.contact_id = auth.getContact().id;
			security.contact_rank_id = 1;//primary
			security.contact_type_id = 2;//security
			security_list.add(security);
			voclist_grouped.put(2/*security*/, security_list);
		}
		ContactTypeModel ctmodel = new ContactTypeModel(context);
		for(ContactTypeRecord.Info contact_type : ContactTypes) {
			tip = new ToolTip(contact_type.desc);
			ContactEditor editor = createContactEditor(voclist_grouped, ctmodel.get(contact_type.id), tip);
			//disable submitter editor if needed
			if(!auth.allows("admin")) {
				if(contact_type.id == 1) { //1 = Submitter Contact
					editor.setDisabled(true);
				}
			}
			if(contact_type.id != 5 && contact_type.id != 9) { //5 = misc, 9 = resource report
				editor.setMinContacts(ContactRank.Primary, 1);
			}
			if(contact_type.id == 2 || contact_type.id == 3) {
				editor.setMaxContacts(ContactRank.Secondary, 3);
			}
			contact_editors.put(contact_type.id, editor);
		}

		new DivRepStaticContent(this, "
WLCG Interoperability Information (If Applicable)
");
		//new DivRepStaticContent(this, "
By enabling this section you agree to publish Resource Information (GLUE via BDII), Monitoring Data (RSV), and Accounting Data (OIM Capacity and Benchmarking) to the WLCG and/or EGI.
");

		wlcg = new DivRepCheckBox(this);
		wlcg.setLabel("This is a WLCG resource");

		//indent the whole WCLG things
		//new DivRepStaticContent(this, "
");
		wlcg_section = new ResourceWLCG(this, context, null);
		hideWLCGElement(true);

		wlcg.addEventListener(new DivRepEventListener() {
			public void handleEvent(DivRepEvent e) {
				if(((String)e.value).compareTo("true") == 0) {
					hideWLCGElement(false);
				} else {
					hideWLCGElement(true);
				}
			}
		});

		if(id != null) {
			ResourceWLCGModel wmodel = new ResourceWLCGModel(context);
			ResourceWLCGRecord wrec = wmodel.get(rec.id);
			if(wrec != null) {
				wlcg.setValue(true);
				wlcg_section.setWlcgRecord(wrec);
				hideWLCGElement(false);
			}
		}

		new DivRepStaticContent(this, "
Confirmation
");
		confirmation = new Confirmation(this, rec, auth);

		if(auth.allows("admin")) {
			new DivRepStaticContent(this, "
Administrative Tasks
");
		}
		active = new DivRepCheckBox(this);
		active.setLabel("Active");
		active.setValue(rec.active);
		if(!auth.allows("admin")) {
			active.setHidden(true);
		}

		disable = new DivRepCheckBox(this);
		disable.setLabel("Disable");
		disable.setValue(rec.disable);
		if(!auth.allows("admin")) {
			disable.setHidden(true);
		}

		if(id == null) {
			AUPConfirmation aup = new AUPConfirmation(this);
		}

		comment = new DivRepTextArea(this);
		comment.setLabel("Update Comment");
		comment.setSampleValue("Please provide a reason for this update.");

		submitbutton.addClass("btn");
	}

	private void hideWLCGElement(Boolean b)
	{
		wlcg_section.setHidden(b);
		wlcg_section.redraw();
	}

	private ContactEditor createContactEditor(HashMap<Integer, ArrayList<ResourceContactRecord>> voclist, ContactTypeRecord ctrec, ToolTip tip) throws SQLException
	{
		new DivRepStaticContent(this, "
" + StringEscapeUtils.escapeHtml(ctrec.name) + " " + tip.render() + "
");
		ContactModel pmodel = new ContactModel(context);
		ContactEditor editor = new ContactEditor(this, pmodel, ctrec.allow_secondary, ctrec.allow_tertiary);

		//if provided, populate currently selected contacts
		if(voclist != null) {
			ArrayList<ResourceContactRecord> clist = voclist.get(ctrec.id);
			if(clist != null) {
				for(ResourceContactRecord rec : clist) {
					ContactRecord keyrec = new ContactRecord();
					keyrec.id = rec.contact_id;
					ContactRecord person = pmodel.get(keyrec);
					editor.addSelected(person, rec.contact_rank_id);
				}
			}
		}

		return editor;
	}

	protected Boolean doSubmit()
	{
		Boolean ret = true;

		//Construct VORecord
		ResourceRecord rec = new ResourceRecord();
		rec.id = id;

		rec.name = name.getValue();
		rec.description = description.getValue();
		rec.fqdn = fqdn.getValue();
		rec.url = url.getValue();
		rec.active = active.getValue();
		rec.disable = disable.getValue();
		rec.resource_group_id = resource_group_id.getValue();
		rec.confirmed = confirmation.getTimestamp();

		//If WLCG is on, then create wlcg record
		ResourceWLCGRecord wrec = null;
		if(wlcg.getValue()) {
			wrec = wlcg_section.getWlcgRecord();
		}

		context.setComment(comment.getValue());

		ResourceModel model = new ResourceModel(context);
		try {
			if(rec.id == null) {
				model.insertDetail(rec,
						aliases.getURLs(),
						getContactRecordsFromEditor(),
						wrec,
						resource_services.getResourceServiceRecords(),
						resource_services.getResourceServiceDetailsRecords(),
						owners.getOwners());
				context.message(MessageType.SUCCESS, "Successfully registered new resource. A ticket has been generated and OSG Operations will alert you when they have reviewed and activated your resource.");

				try {
					//Traverse OIM hirearchy to find the Footprint ID of the associated SC
					ResourceGroupModel rgmodel = new ResourceGroupModel(context);
					ResourceGroupRecord rgrec = rgmodel.get(rec.resource_group_id);
					SiteModel smodel = new SiteModel(context);
					SiteRecord srec = smodel.get(rgrec.site_id);
					SCModel scmodel = new SCModel(context);
					SCRecord screc = scmodel.get(srec.sc_id);

					//create footprint ticket
					Footprints fp = new Footprints(context);
					fp.createNewResourceTicket(rec.name, screc);//, vo_name);
				} catch (Exception fpe) {
					log.error("Failed to open footprints ticket: ", fpe);
				}
			} else {
				model.updateDetail(rec,
						aliases.getURLs(),
						getContactRecordsFromEditor(),
						wrec,
						resource_services.getResourceServiceRecords(),
						resource_services.getResourceServiceDetailsRecords(),
						owners.getOwners());
				context.message(MessageType.SUCCESS, "Successfully updated a resource.");
			}
			return true;
		} catch (Exception e) {
			alert(e.getMessage());
			log.error("Failed to insert/update record", e);
			return false;
		}
	}

	//retrieve contact records from the contact editor.
	//be aware that VOContactRecord's vo_id is not populated.. you need to fill it out with
	//appropriate vo_id later
	private ArrayList<ResourceContactRecord> getContactRecordsFromEditor()
	{
		ArrayList<ResourceContactRecord> list = new ArrayList();

		for(Integer type_id : contact_editors.keySet())
		{
			ContactEditor editor = contact_editors.get(type_id);
			HashMap<ContactRecord, ContactRank> contacts = editor.getContactRecords();
			for(ContactRecord contact : contacts.keySet()) {
				ResourceContactRecord rec = new ResourceContactRecord();
				ContactRank rank = contacts.get(contact);
				rec.contact_id = contact.id;
				rec.contact_type_id = type_id;
				rec.contact_rank_id = rank.id;
				list.add(rec);
			}
		}

		return list;
	}

	private HashMap<Integer, String> getResources() throws SQLException
	{
		ResourceModel model = new ResourceModel(context);
		HashMap<Integer, String> resources = new HashMap();
		for(ResourceRecord rec : model.getAll()) {
			resources.put(rec.id, rec.name);
		}
		return resources;
	}

	public Boolean isValidResourceFQDN(String url)
	{
		if(fqdn.getValue().equals(url)) return true;
		ArrayList<String> as = aliases.getURLs();
		if(as.contains(url)) return true;

		return false;
	}
}


text:
<?php

class Object_Class_Layout_Button extends Object_Class_Layout {

    /**
     * Static type of this element
     *
     * @var string
     */
    public $fieldtype = "button";

    public $handler;

    public $text;

    public function getText() {
        return $this->text;
    }

    public function setText($text) {
        $this->text = $text;
    }

    public function getHandler() {
        return $this->handler;
    }

    public function setHandler($handler) {
        $this->handler = $handler;
    }

}


text:
var reporter = require('nodeunit').reporters.default;
reporter.run([
	'test-startstop.js',
	'../plugins/mc_jsonapi/plugintest.js',
]);


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package helloworld.cpd4414.pkg02;

/**
 *
 * @author c0587637
 */
public class HelloWorldCPD441402 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("Leonard Payne");
        System.out.println("Jasmyn Newton");
        System.out.println("Dylan Huculak - dylan@dylanweb.ca");
        System.out.println("Ashika Shallow");
        System.out.println("Kyle Crossman");
        System.out.println("Lewis A. Menelaws");
        System.out.println("Jason Preston (JSON is here)");
        System.out.println("Ryan McLeod");
        System.out.println("Austin Coombes-Reid");
        System.out.println("For the LOVE of the universe... Add my friggin' name! - Jeff Codling");
        System.out.println("Amanda Cohoon");
    }

    public void amanda() {
        System.out.println("howdy");
    }

    public static void austin() {
        System.out.println("WOOO I HAVE A PALACE!!... ");
    }

    public static void dylan() {
        System.out.println("This is my method. There are many others like it, but this one is mine.");
        //Test comment
    }

}


text:
[![Latest Version on Packagist][ico-version]][link-packagist]
[![Software License][ico-license]](LICENSE.md)
[![Coverage Status][ico-scrutinizer]][link-scrutinizer]
[![Quality Score][ico-code-quality]][link-code-quality]
[![Total Downloads][ico-downloads]][link-downloads]

## Install

Via Composer

``` bash
Case laravel 5.x

$ composer require sonar/valiable:1.*

Case laravel 6.x

$ composer require sonar/valiable:2.*

```

Add ServiceProvider in config.php
``` php
    'providers' => [
        :
        :
        Sonar\Valiable\ValiableServiceProvider::class,
    ],

    'aliases' => [
        :
        :
        'Valiable' => Sonar\Valiable\ValiableFacade::class,
    ],
```

Artisan Command
``` bash
$ php artisan vendor:publish
```

Create Valiables Directory to storage_path
put Yaml Files to Valiables Direcoty

Example:
``` file
properties:
  parameter_kinds:
    name: "種別"
    value:
      "1": "土地"
      "2": "一戸建て"
      "3": "マンション"
```

Valiable Import
``` bash
$ php artisan valiable:import
```

Example Code
``` php
use Valiable;

print_r(Valiable::get('properties_parameter_kinds')); # Array([1] => 土地 [2] => 一戸建て [3] => マンション )
print_r(Valiable::getValue('properties_parameter_kinds',1)); # 土地
print_r(Valiable::getNames()); # Array([0] => properties_parameter_kinds)

```

<!--
## Usage

``` php
$skeleton = new League\Skeleton();
echo $skeleton->echoPhrase('Hello, League!');
```

## Change log

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

## Testing

``` bash
$ composer test
```

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details.

## Security

If you discover any security related issues, please email :author_email instead of using the issue tracker.
-->

## Credits

- [dev-sonar][link-author]
- [All Contributors][link-contributors]

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

[ico-version]: https://img.shields.io/packagist/v/sonar/valiable.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[ico-circleci]: https://circleci.com/gh/dev-sonar/sonar-valiable.svg?style=shield&circle-token=d9c8812dec2ac73a00306fcfadaaa1528b6f8ce2
[ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/dev-sonar/sonar-valiable.svg?style=flat-square
[ico-code-quality]: https://img.shields.io/scrutinizer/g/dev-sonar/sonar-valiable.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/sonar/valiable.svg?style=flat-square

[link-packagist]: https://packagist.org/packages/sonar/valiable
[link-circleci]: https://circleci.com/gh/dev-sonar/sonar-valiable
[link-scrutinizer]: https://scrutinizer-ci.com/g/dev-sonar/sonar-valiable/code-structure
[link-code-quality]: https://scrutinizer-ci.com/g/dev-sonar/sonar-valiable
[link-downloads]: https://packagist.org/packages/sonar/valiable
[link-author]: https://github.com/dev-sonar
[link-contributors]: ../../contributors


text:
#import <SenTestingKit/SenTestingKit.h>

#import "FakeFileHandle.h"
#import "Options.h"
#import "Options+Testing.h"
#import "Reporter+Testing.h"
#import "Swizzler.h"
#import "TextReporter.h"

@interface TextReporterTests : SenTestCase
@end

@implementation TextReporterTests

/**
 Just verify the plumbing works and our text reporters don't crash when getting
 fed events.  This is a really lame test - over time, we should add cases to
 actually verify output.
 */
- (void)testReporterDoesntCrash
{
  void (^pumpReporter)(Class, NSString *) = ^(Class cls, NSString *path) {
    NSLog(@"pumpReporter(%@, %@) ...", cls, path);
    Options *options = [[[Options alloc] init] autorelease];
    options.workspace = TEST_DATA @"TestProject-Library/TestProject-Library.xcodeproj";
    options.scheme = @"TestProject-Library";

    // Pump the events to make sure all the plumbing works and we don't crash.
    [cls outputDataWithEventsFromFile:path options:options];
  };

  pumpReporter([PlainTextReporter class], TEST_DATA @"JSONStreamReporter-build-good.txt");
  pumpReporter([PlainTextReporter class], TEST_DATA @"JSONStreamReporter-build-bad.txt");
  pumpReporter([PlainTextReporter class], TEST_DATA @"JSONStreamReporter-runtests.txt");

  pumpReporter([PrettyTextReporter class], TEST_DATA @"JSONStreamReporter-build-good.txt");
  pumpReporter([PrettyTextReporter class], TEST_DATA @"JSONStreamReporter-build-bad.txt");
  pumpReporter([PrettyTextReporter class], TEST_DATA @"JSONStreamReporter-runtests.txt");
}

- (void)testStatusMessageShowsOneLineWithNoDuration
{
  FakeFileHandle *fh = [[[FakeFileHandle alloc] init] autorelease];
  PrettyTextReporter *reporter = [[[PrettyTextReporter alloc] init] autorelease];
  // Force _isPretty to YES to avoid the isatty() detection.
  reporter->_isPretty = YES;

  [reporter setOutputPath:@"-"];
  [reporter openWithStandardOutput:(NSFileHandle *)fh error:nil];

  ReportStatusMessage(@[reporter], REPORTER_MESSAGE_INFO, @"Some message...");

  [reporter close];
  assertThat([fh stringWritten],
             equalTo(// the first line, from beginStatusMessage:
                     @"\r[Info] Some message..."
                     // the second line, from endStatusMessage:
                     @"\r[Info] Some message...\n"
                     // the trailing newline from -[Reporter close]
                     @"\n"));
}

- (void)testStatusMessageWithBeginAndEndIncludesDuration
{
  FakeFileHandle *fh = [[[FakeFileHandle alloc] init] autorelease];
  PrettyTextReporter *reporter = [[[PrettyTextReporter alloc] init] autorelease];
  // Force _isPretty to YES to avoid the isatty() detection.
  reporter->_isPretty = YES;

  [reporter setOutputPath:@"-"];
  [reporter openWithStandardOutput:(NSFileHandle *)fh error:nil];

  // call begin at T+0 seconds.
  [Swizzler whileSwizzlingSelector:@selector(date)
                          forClass:[NSDate class]
                         withBlock:^{ [NSDate dateWithTimeIntervalSince1970:0]; }
                          runBlock:
   ^{
     ReportStatusMessageBegin(@[reporter], REPORTER_MESSAGE_INFO, @"Some message...");
   }];

  // call end at T+1 seconds.
  [Swizzler whileSwizzlingSelector:@selector(date)
                          forClass:[NSDate class]
                         withBlock:^{ [NSDate dateWithTimeIntervalSince1970:1.0]; }
                          runBlock:
   ^{
     ReportStatusMessageEnd(@[reporter], REPORTER_MESSAGE_INFO, @"Some message.");
   }];

  [reporter close];
  assertThat([fh stringWritten],
             equalTo(// the first line, from beginStatusMessage:
                     @"\r[Info] Some message..."
                     // the second line, from endStatusMessage:
                     @"\r[Info] Some message. (1000 ms)\n"
                     // the trailing newline from -[Reporter close]
                     @"\n"));
}

@end


text:
package com.easyjf.demo.dao;

import com.easyjf.core.dao.GenericDAO;
import com.easyjf.demo.domain.Person;
/**
 * AdvertisementDAO
 * @author EasyJWeb 1.0-m2
 * $Id: AdvertisementDAO.java,v 0.0.1 2007-11-27 10:37:00 EasyJWeb 1.0-m2 Exp $
 */
public interface IPersonDAO extends GenericDAO<Person> {

}


text:
import * as webpack from 'webpack'
import * as devserver from 'webpack-dev-middleware'
import * as hot from 'webpack-hot-middleware'
import hotServer  = require('webpack-hot-server-middleware')
import * as express from 'express'
import errorOverlay = require('react-dev-utils/errorOverlayMiddleware')
import { pick } from 'lodash'
import { getWebpackConfig } from '../bundler/getWebpackConfig'
import { renderHtmlWrapper } from './renderHtmlWrapper'
import { PluginConstructor } from '../core/PluginConfig'
import { Config } from './Config'
import { getEntrypointFiles } from './setup'

export interface DevServerOpts {
  port: number
  plugins: Record<string, PluginConstructor>
  config: Config
}

export async function startDevserver({ port, plugins, config }: DevServerOpts) {
  const webpackConfig = getWebpackConfig({
    pages: getEntrypointFiles(),
    plugins,
    devServer: true
  })

  const bundler = webpack(webpackConfig)
  const app = express()

  const clientBundler = (bundler as any).compilers.find((compiler: webpack.Compiler) =>
    compiler.name === 'client'
  )

  app.use(hot(clientBundler, { path: '/_hot' }))
  app.get('*', devserver(bundler, { noInfo: true, publicPath: '/' }))
  app.use(hotServer(bundler))
  app.use(errorOverlay())

  app.get('*', (req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html' })
    res.write(renderHtmlWrapper({ config: getFrontendEnvironment(), devserver: true }))
    res.end()
  })

  const server = app.listen(port, () => {
    const address = `http://localhost:${server.address().port}`
    process.stderr.write(`Development server started on ${address}\n`)
  })

  function getFrontendEnvironment(): NodeJS.ProcessEnv {
    return pick(process.env, config.frontendEnvironment)
  }
}


text:
{% autoescape false %}
var orm = require('../index.js'),
{{ dataTypeVariable }} = orm.Sequelize();

module.exports = {
    modelName: {{ table.modelName }},
    options: {
        tableName: {{ table.tableName }}
        {{ ifTrue('schema',             table.schema) }}
        {{ ifTrue('omitNull',           table.omitNull) }}
        {{ ifFalse('timestamps',        table.timestamps) }}
        {{ ifTrue('paranoid',           table.paranoid) }}
        {{ ifTrue('underscored',        table.underscored) }}
        {{ ifTrue('underscoredAll',     table.underscoredAll) }}
        {{ ifTrue('freezeTableName',    table.freezeTableName) }}
        {{ ifTrue('createdAt',          table.createdAt) }}
        {{ ifTrue('updatedAt',          table.updatedAt) }}
        {{ ifTrue('deletedAt',          table.deletedAt) }}
        {{ ifTrue('charset',            table.charset) }}
        {{ ifTrue('collate',            table.collate) }}
        {{ ifTrue('comment',            table.comment) }}
    },
    attributes: {
        {% for column in table.columns %}
            {% include "./column.html" %}{% if not loop.last %},{% endif %}
        {% endfor %}
    },
    relations: [
        {% for relation in table.relations %}
            {% include "./relation.html" %}{% if not loop.last %},{% endif %}
        {% endfor %}
    ]
};

{% endautoescape %}


text:
<?php

namespace AppBundle\Chart\Data;

use Doctrine\ORM\EntityManager;

class DoctrineDataProcessor implements DataProcessorInterface
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $objectManager;

    /**
     * @var string
     */
    protected $class;

    public function __construct(EntityManager $objectManager, $class)
    {
        $this->objectManager = $objectManager;
        $this->class = $class;
    }

    /**
     * @param array $criteria
     * @return \AppBundle\Entity\Data[]|array
     */
    public function getData(array $criteria)
    {
        $qb = $this->objectManager->createQueryBuilder();
        $qb->select('d');
        $qb->from($this->class, 'd');

        if (array_key_exists('wilayah', $criteria) || array_key_exists('regional', $criteria)) {
            if (empty($criteria['regional'])) {
                $qb->andWhere($qb->expr()->orX($qb->expr()->eq('d.propinsi', ':propinsi'), $qb->expr()->eq('d.kabupaten', ':kabupaten')));
                $qb->setParameter('propinsi', $criteria['wilayah']);
                $qb->setParameter('kabupaten', $criteria['wilayah']);
            } else {
                $qb->andWhere($qb->expr()->eq('d.regional', ':regional'));
                $qb->setParameter('regional', $criteria['regional']);
            }
        }

        $qb->andWhere($qb->expr()->eq('d.indikator', ':indikator'));
        $qb->andWhere($qb->expr()->eq('d.tahun', ':tahun'));
        $qb->andWhere($qb->expr()->eq('d.bulan', ':bulan'));

        $qb->setParameter('indikator', $criteria['indikator']);
        $qb->setParameter('tahun', $criteria['tahun']);
        $qb->setParameter('bulan', $criteria['bulan']);

        return $qb->getQuery()->getResult();
    }

    public function getName()
    {
        return 'doctrine';
    }
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="target-densitydpi=device-dpi, width=device-width, user-scalable=no,initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="BoardMap">
    <title>Board Map</title>

    <link href="css/button.css" rel="stylesheet" media="all" type="text/css" />
    <link href="css/map_style.css" rel="stylesheet" media="all" type="text/css" />

            <select id="move_area_status">
                <option value="open">未貼付</option>
                <option value="close">貼付完了</option>
                <option value="*">全て表示</option>
            </select>

    付近の掲示板を表示

    説明
    ★

        <textarea name="bookmark_list_txte" id="bookmark_list_txte" cols="45" rows="20"></textarea>

        クリアー

掲示板データについて

このアプリは、以下のデータを元にAPIから随時取得して表示しています。

http://beta.shirasete.jp/projects/ieiri-poster/issues

行政区 一括選択

表示する行政区を一括で表示します

注意)APIの負荷軽減の為、選択は最大5件までです。スマホ等ではフリーズする場合があります。

[試験機能]住所で検索

住所から、該当する地域の付近の掲示板を表示

注意)APIの都合場、その位置を中心とした近い順に最大100件のみ表示されます。

                <input name="move_area_address" class="input_text_mid" type="text" id="move_area_address" value=""/>
                移動

[試験機能]現在の地図の中心位置から近くの掲示板を表示

現在表示している地図の位置にある掲示板を表示

注意)APIの都合場、その位置を中心とした近い順に最大100件のみ表示されます。

                表示

未受信

検索中


text:
package mau.mauannotation

import scala.concurrent.ExecutionContext.Implicits.global

import mau._
import mau.test._

class AllIndexAnnotationTest extends MauRedisSpec("AllIndexAnnotationTest", true) {

  describe("@allIndex class annotation") {
    it("should allow to find all instances") {
      val personMauRepo = Person.mauRepo
      val person = Person(None, "Hans", 27)
      val savedPerson = await(personMauRepo.save(person))
      val id = savedPerson.id.get
      val retrievedPeople = await(personMauRepo.findAll)
      retrievedPeople should be(Seq(savedPerson))
      val retrievedPerson = retrievedPeople(0)
      retrievedPerson.name should be(person.name)
    }

    it("should allow to delete all instances") {
      val personMauRepo = Person.mauRepo
      val person = Person(None, "Hans", 27)
      val savedPerson = await(personMauRepo.save(person))
      val id = savedPerson.id.get
      val deleteResult = await(personMauRepo.deleteAll)
      deleteResult should be(1)
      val retrievedPerson = await(personMauRepo.get(id))
      retrievedPerson should be(None)
    }

    it("should allow to count all instances") {
      val personMauRepo = Person.mauRepo
      val person = Person(None, "Hans", 27)
      val savedPerson = await(personMauRepo.save(person))
      val id = savedPerson.id.get
      val countResult = await(personMauRepo.countAll)
      countResult should be(1)
    }
  }

  @mauModel("Mau:Test:AllIndexAnnotationTest", false)
  @sprayJson
  @allIndex
  case class Person(
    id: Option[Id],
    name: String,
    age: Int)
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.masterbaron.intenttunnel.glass">

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

    <application>
        <activity
            android:name="com.masterbaron.intenttunnel.glass.GlassConfigureActivity"
            android:theme="@style/MenuTheme">
        </activity>
        <activity
            android:name="com.masterbaron.intenttunnel.glass.DeviceSelectActivity"
            android:label="Select Bluetooth Device">
        </activity>

    </application>

</manifest>