text:
package cn.dmesoft.haibao.modules.act.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.dmesoft.haibao.common.utils.StringUtils;
import cn.dmesoft.haibao.modules.act.entity.Act;
import cn.dmesoft.haibao.modules.act.service.creator.ChainedActivitiesCreator;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.RuntimeServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.interceptor.CommandExecutor;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.delegate.ActivityBehavior;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import cn.dmesoft.haibao.common.persistence.Page;
import cn.dmesoft.haibao.common.service.BaseService;
import cn.dmesoft.haibao.modules.act.dao.ActDao;
import cn.dmesoft.haibao.modules.act.service.cmd.CreateAndTakeTransitionCmd;
import cn.dmesoft.haibao.modules.act.service.cmd.JumpTaskCmd;
import cn.dmesoft.haibao.modules.act.service.creator.MultiInstanceActivityCreator;
import cn.dmesoft.haibao.modules.act.service.creator.RuntimeActivityDefinitionEntityIntepreter;
import cn.dmesoft.haibao.modules.act.service.creator.SimpleRuntimeActivityDefinitionEntity;
import cn.dmesoft.haibao.modules.act.utils.ActUtils;
import cn.dmesoft.haibao.modules.act.utils.ProcessDefCache;
import cn.dmesoft.haibao.modules.act.utils.ProcessDefUtils;
import cn.dmesoft.haibao.modules.sys.entity.User;
import cn.dmesoft.haibao.modules.sys.utils.UserUtils;

/**
 * 流程定义相关Service
 * @author dmesoft
 * @version 2013-11-03
 */
@Service
@Transactional(readOnly = true)
public class ActTaskService extends BaseService {

	@Autowired
	private ActDao actDao;

	@Autowired
	private ProcessEngineFactoryBean processEngineFactory;

	@Autowired
	private ProcessEngine processEngine;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private FormService formService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private IdentityService identityService;

	/**
	 * 获取待办列表
	 * @param procDefKey 流程定义标识
	 * @return
	 */
	public List<Act> todoList(Act act){
		String userId = UserUtils.getUser().getLoginName();//ObjectUtils.toString(UserUtils.getUser().getId());

		List<Act> result = new ArrayList<Act>();

		// =============== 已经签收的任务  ===============
		TaskQuery todoTaskQuery = taskService.createTaskQuery().taskAssignee(userId).active()
				.includeProcessVariables().orderByTaskCreateTime().desc();

		// 设置查询条件
		if (StringUtils.isNotBlank(act.getProcDefKey())){
			todoTaskQuery.processDefinitionKey(act.getProcDefKey());
		}
		if (act.getBeginDate() != null){
			todoTaskQuery.taskCreatedAfter(act.getBeginDate());
		}
		if (act.getEndDate() != null){
			todoTaskQuery.taskCreatedBefore(act.getEndDate());
		}

		// 查询列表
		List<Task> todoList = todoTaskQuery.list();
		for (Task task : todoList) {
			Act e = new Act();
			e.setTask(task);
			e.setVars(task.getProcessVariables());
//			e.setTaskVars(task.getTaskLocalVariables());
//			System.out.println(task.getId()+"  =  "+task.getProcessVariables() + "  ========== " + task.getTaskLocalVariables());
			e.setProcDef(ProcessDefCache.get(task.getProcessDefinitionId()));
//			e.setProcIns(runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult());
//			e.setProcExecUrl(ActUtils.getProcExeUrl(task.getProcessDefinitionId()));
			e.setStatus("todo");
			result.add(e);
		}

		// =============== 等待签收的任务  ===============
		TaskQuery toClaimQuery = taskService.createTaskQuery().taskCandidateUser(userId)
				.includeProcessVariables().active().orderByTaskCreateTime().desc();

		// 设置查询条件
		if (StringUtils.isNotBlank(act.getProcDefKey())){
			toClaimQuery.processDefinitionKey(act.getProcDefKey());
		}
		if (act.getBeginDate() != null){
			toClaimQuery.taskCreatedAfter(act.getBeginDate());
		}
		if (act.getEndDate() != null){
			toClaimQuery.taskCreatedBefore(act.getEndDate());
		}

		// 查询列表
		List<Task> toClaimList = toClaimQuery.list();
		for (Task task : toClaimList) {
			Act e = new Act();
			e.setTask(task);
			e.setVars(task.getProcessVariables());
//			e.setTaskVars(task.getTaskLocalVariables());
//			System.out.println(task.getId()+"  =  "+task.getProcessVariables() + "  ========== " + task.getTaskLocalVariables());
			e.setProcDef(ProcessDefCache.get(task.getProcessDefinitionId()));
//			e.setProcIns(runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult());
//			e.setProcExecUrl(ActUtils.getProcExeUrl(task.getProcessDefinitionId()));
			e.setStatus("claim");
			result.add(e);
		}
		return result;
	}

	/**
	 * 获取已办任务
	 * @param page
	 * @param procDefKey 流程定义标识
	 * @return
	 */
	public Page<Act> historicList(Page<Act> page, Act act){
		String userId = UserUtils.getUser().getLoginName();//ObjectUtils.toString(UserUtils.getUser().getId());

		HistoricTaskInstanceQuery histTaskQuery = historyService.createHistoricTaskInstanceQuery().taskAssignee(userId).finished()
				.includeProcessVariables().orderByHistoricTaskInstanceEndTime().desc();

		// 设置查询条件
		if (StringUtils.isNotBlank(act.getProcDefKey())){
			histTaskQuery.processDefinitionKey(act.getProcDefKey());
		}
		if (act.getBeginDate() != null){
			histTaskQuery.taskCompletedAfter(act.getBeginDate());
		}
		if (act.getEndDate() != null){
			histTaskQuery.taskCompletedBefore(act.getEndDate());
		}

		// 查询总数
		page.setCount(histTaskQuery.count());

		// 查询列表
		List<HistoricTaskInstance> histList = histTaskQuery.listPage(page.getFirstResult(), page.getMaxResults());
		//处理分页问题
		List<Act> actList=Lists.newArrayList();
		for (HistoricTaskInstance histTask : histList) {
			Act e = new Act();
			e.setHistTask(histTask);
			e.setVars(histTask.getProcessVariables());
//			e.setTaskVars(histTask.getTaskLocalVariables());
//			System.out.println(histTask.getId()+"  =  "+histTask.getProcessVariables() + "  ========== " + histTask.getTaskLocalVariables());
			e.setProcDef(ProcessDefCache.get(histTask.getProcessDefinitionId()));
//			e.setProcIns(runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult());
//			e.setProcExecUrl(ActUtils.getProcExeUrl(task.getProcessDefinitionId()));
			e.setStatus("finish");
			actList.add(e);
			//page.getList().add(e);
		}
		page.setList(actList);
		return page;
	}

	/**
	 * 获取流转历史列表
	 * @param procInsId 流程实例
	 * @param startAct 开始活动节点名称
	 * @param endAct 结束活动节点名称
	 */
	public List<Act> histoicFlowList(String procInsId, String startAct, String endAct){
		List<Act> actList = Lists.newArrayList();
		List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery().processInstanceId(procInsId)
				.orderByHistoricActivityInstanceStartTime().asc().orderByHistoricActivityInstanceEndTime().asc().list();

		boolean start = false;
		Map<String, Integer> actMap = Maps.newHashMap();

		for (int i=0; i<list.size(); i++){

			HistoricActivityInstance histIns = list.get(i);

			// 过滤开始节点前的节点
			if (StringUtils.isNotBlank(startAct) && startAct.equals(histIns.getActivityId())){
				start = true;
			}
			if (StringUtils.isNotBlank(startAct) && !start){
				continue;
			}

			// 只显示开始节点和结束节点,并且执行人不为空的任务
			if (StringUtils.isNotBlank(histIns.getAssignee())
					 || "startEvent".equals(histIns.getActivityType())
					 || "endEvent".equals(histIns.getActivityType())){

				// 给节点增加一个序号
				Integer actNum = actMap.get(histIns.getActivityId());
				if (actNum == null){
					actMap.put(histIns.getActivityId(), actMap.size());
				}

				Act e = new Act();
				e.setHistIns(histIns);
				// 获取流程发起人名称
				if ("startEvent".equals(histIns.getActivityType())){
					List<HistoricProcessInstance> il = historyService.createHistoricProcessInstanceQuery().processInstanceId(procInsId).orderByProcessInstanceStartTime().asc().list();
//					List<HistoricIdentityLink> il = historyService.getHistoricIdentityLinksForProcessInstance(procInsId);
					if (il.size() > 0){
						if (StringUtils.isNotBlank(il.get(0).getStartUserId())){
							User user = UserUtils.getByLoginName(il.get(0).getStartUserId());
							if (user != null){
								e.setAssignee(histIns.getAssignee());
								e.setAssigneeName(user.getName());
							}
						}
					}
				}
				// 获取任务执行人名称
				if (StringUtils.isNotEmpty(histIns.getAssignee())){
					User user = UserUtils.getByLoginName(histIns.getAssignee());
					if (user != null){
						e.setAssignee(histIns.getAssignee());
						e.setAssigneeName(user.getName());
					}
				}
				// 获取意见评论内容
				if (StringUtils.isNotBlank(histIns.getTaskId())){
					List<Comment> commentList = taskService.getTaskComments(histIns.getTaskId());
					if (commentList.size()>0){
						e.setComment(commentList.get(0).getFullMessage());
					}
				}
				actList.add(e);
			}

			// 过滤结束节点后的节点
			if (StringUtils.isNotBlank(endAct) && endAct.equals(histIns.getActivityId())){
				boolean bl = false;
				Integer actNum = actMap.get(histIns.getActivityId());
				// 该活动节点,后续节点是否在结束节点之前,在后续节点中是否存在
				for (int j=i+1; j<list.size(); j++){
					HistoricActivityInstance hi = list.get(j);
					Integer actNumA = actMap.get(hi.getActivityId());
					if ((actNumA != null && actNumA < actNum) || StringUtils.equals(hi.getActivityId(), histIns.getActivityId())){
						bl = true;
					}
				}
				if (!bl){
					break;
				}
			}
		}
		return actList;
	}

	/**
	 * 获取流程列表
	 * @param category 流程分类
	 */
	public Page<Object[]> processList(Page<Object[]> page, String category) {
		/*
		 * 保存两个对象,一个是ProcessDefinition(流程定义),一个是Deployment(流程部署)
		 */
	    ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery()
	    		.latestVersion().active().orderByProcessDefinitionKey().asc();

	    if (StringUtils.isNotEmpty(category)){
	    	processDefinitionQuery.processDefinitionCategory(category);
		}

	    page.setCount(processDefinitionQuery.count());

	    List<ProcessDefinition> processDefinitionList = processDefinitionQuery.listPage(page.getFirstResult(), page.getMaxResults());
	    for (ProcessDefinition processDefinition : processDefinitionList) {
	      String deploymentId = processDefinition.getDeploymentId();
	      Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
	      page.getList().add(new Object[]{processDefinition, deployment});
	    }
		return page;
	}

	/**
	 * 获取流程表单(首先获取任务节点表单KEY,如果没有则取流程开始节点表单KEY)
	 * @return
	 */
	public String getFormKey(String procDefId, String taskDefKey){
		String formKey = "";
		if (StringUtils.isNotBlank(procDefId)){
			if (StringUtils.isNotBlank(taskDefKey)){
				try{
					formKey = formService.getTaskFormKey(procDefId, taskDefKey);
				}catch (Exception e) {
					formKey = "";
				}
			}
			if (StringUtils.isBlank(formKey)){
				formKey = formService.getStartFormKey(procDefId);
			}
			if (StringUtils.isBlank(formKey)){
				formKey = "/404";
			}
		}
		logger.debug("getFormKey: {}", formKey);
		return formKey;
	}

	/**
	 * 获取流程实例对象
	 * @param procInsId
	 * @return
	 */
	@Transactional(readOnly = false)
	public ProcessInstance getProcIns(String procInsId) {
		return runtimeService.createProcessInstanceQuery().processInstanceId(procInsId).singleResult();
	}

	/**
	 * 启动流程
	 * @param procDefKey 流程定义KEY
	 * @param businessTable 业务表表名
	 * @param businessId	业务表编号
	 * @return 流程实例ID
	 */
	@Transactional(readOnly = false)
	public String startProcess(String procDefKey, String businessTable, String businessId) {
		return startProcess(procDefKey, businessTable, businessId, "");
	}

	/**
	 * 启动流程
	 * @param procDefKey 流程定义KEY
	 * @param businessTable 业务表表名
	 * @param businessId	业务表编号
	 * @param title			流程标题,显示在待办任务标题
	 * @return 流程实例ID
	 */
	@Transactional(readOnly = false)
	public String startProcess(String procDefKey, String businessTable, String businessId, String title) {
		Map<String, Object> vars = Maps.newHashMap();
		return startProcess(procDefKey, businessTable, businessId, title, vars);
	}

	/**
	 * 启动流程
	 * @param procDefKey 流程定义KEY
	 * @param businessTable 业务表表名
	 * @param businessId	业务表编号
	 * @param title			流程标题,显示在待办任务标题
	 * @param vars			流程变量
	 * @return 流程实例ID
	 */
	@Transactional(readOnly = false)
	public String startProcess(String procDefKey, String businessTable, String businessId, String title, Map<String, Object> vars) {
		String userId = UserUtils.getUser().getLoginName();//ObjectUtils.toString(UserUtils.getUser().getId())

		// 用来设置启动流程的人员ID,引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(userId);

		// 设置流程变量
		if (vars == null){
			vars = Maps.newHashMap();
		}

		// 设置流程标题
		if (StringUtils.isNotBlank(title)){
			vars.put("title", title);
		}

		// 启动流程
		ProcessInstance procIns = runtimeService.startProcessInstanceByKey(procDefKey, businessTable+":"+businessId, vars);

		// 更新业务表流程实例ID
		Act act = new Act();
		act.setBusinessTable(businessTable);// 业务表名
		act.setBusinessId(businessId);	// 业务表ID
		act.setProcInsId(procIns.getId());
		actDao.updateProcInsIdByBusinessId(act);
		return act.getProcInsId();
	}

	/**
	 * 获取任务
	 * @param taskId 任务ID
	 */
	public Task getTask(String taskId){
		return taskService.createTaskQuery().taskId(taskId).singleResult();
	}

	/**
	 * 删除任务
	 * @param taskId 任务ID
	 * @param deleteReason 删除原因
	 */
	@Transactional(readOnly = false)
	public void deleteTask(String taskId, String deleteReason){
		taskService.deleteTask(taskId, deleteReason);
	}

	/**
	 * 签收任务
	 * @param taskId 任务ID
	 * @param userId 签收用户ID(用户登录名)
	 */
	@Transactional(readOnly = false)
	public void claim(String taskId, String userId){
		taskService.claim(taskId, userId);
	}

	/**
	 * 提交任务, 并保存意见
	 * @param taskId 任务ID
	 * @param procInsId 流程实例ID,如果为空,则不保存任务提交意见
	 * @param comment 任务提交意见的内容
	 * @param vars 任务变量
	 */
	@Transactional(readOnly = false)
	public void complete(String taskId, String procInsId, String comment, Map<String, Object> vars){
		complete(taskId, procInsId, comment, "", vars);
	}

	/**
	 * 提交任务, 并保存意见
	 * @param taskId 任务ID
	 * @param procInsId 流程实例ID,如果为空,则不保存任务提交意见
	 * @param comment 任务提交意见的内容
	 * @param title			流程标题,显示在待办任务标题
	 * @param vars 任务变量
	 */
	@Transactional(readOnly = false)
	public void complete(String taskId, String procInsId, String comment, String title, Map<String, Object> vars){
		// 添加意见
		if (StringUtils.isNotBlank(procInsId) && StringUtils.isNotBlank(comment)){
			taskService.addComment(taskId, procInsId, comment);
		}

		// 设置流程变量
		if (vars == null){
			vars = Maps.newHashMap();
		}

		// 设置流程标题
		if (StringUtils.isNotBlank(title)){
			vars.put("title", title);
		}

		// 提交任务
		taskService.complete(taskId, vars);
	}

	/**
	 * 完成第一个任务
	 * @param procInsId
	 */
	@Transactional(readOnly = false)
	public void completeFirstTask(String procInsId){
		completeFirstTask(procInsId, null, null, null);
	}

	/**
	 * 完成第一个任务
	 * @param procInsId
	 * @param comment
	 * @param title
	 * @param vars
	 */
	@Transactional(readOnly = false)
	public void completeFirstTask(String procInsId, String comment, String title, Map<String, Object> vars){
		String userId = UserUtils.getUser().getLoginName();
		Task task = taskService.createTaskQuery().taskAssignee(userId).processInstanceId(procInsId).active().singleResult();
		if (task != null){
			complete(task.getId(), procInsId, comment, title, vars);
		}
	}

//	/**
//	 * 委派任务
//	 * @param taskId 任务ID
//	 * @param userId 被委派人
//	 */
//	public void delegateTask(String taskId, String userId){
//		taskService.delegateTask(taskId, userId);
//	}
//
//	/**
//	 * 被委派人完成任务
//	 * @param taskId 任务ID
//	 */
//	public void resolveTask(String taskId){
//		taskService.resolveTask(taskId);
//	}
//
//	/**
//	 * 回退任务
//	 * @param taskId
//	 */
//	public void backTask(String taskId){
//		taskService.
//	}

	/**
	 * 添加任务意见
	 */
	public void addTaskComment(String taskId, String procInsId, String comment){
		taskService.addComment(taskId, procInsId, comment);
	}

	//////////////////  回退、前进、跳转、前加签、后加签、分裂 移植  https://github.com/bluejoe2008/openwebflow  //////////////////////////////////////////////////

	/**
	 * 任务后退一步
	 */
	public void taskBack(String procInsId, Map<String, Object> variables) {
		taskBack(getCurrentTask(procInsId), variables);
	}

	/**
	 * 任务后退至指定活动
	 */
	public void taskBack(TaskEntity currentTaskEntity, Map<String, Object> variables) {
		ActivityImpl activity = (ActivityImpl) ProcessDefUtils
				.getActivity(processEngine, currentTaskEntity.getProcessDefinitionId(), currentTaskEntity.getTaskDefinitionKey())
				.getIncomingTransitions().get(0).getSource();
		jumpTask(currentTaskEntity, activity, variables);
	}

	/**
	 * 任务前进一步
	 */
	public void taskForward(String procInsId, Map<String, Object> variables) {
		taskForward(getCurrentTask(procInsId), variables);
	}

	/**
	 * 任务前进至指定活动
	 */
	public void taskForward(TaskEntity currentTaskEntity, Map<String, Object> variables) {
		ActivityImpl activity = (ActivityImpl) ProcessDefUtils
				.getActivity(processEngine, currentTaskEntity.getProcessDefinitionId(), currentTaskEntity.getTaskDefinitionKey())
				.getOutgoingTransitions().get(0).getDestination();

		jumpTask(currentTaskEntity, activity, variables);
	}

	/**
	 * 跳转(包括回退和向前)至指定活动节点
	 */
	public void jumpTask(String procInsId, String targetTaskDefinitionKey, Map<String, Object> variables) {
		jumpTask(getCurrentTask(procInsId), targetTaskDefinitionKey, variables);
	}

	/**
	 * 跳转(包括回退和向前)至指定活动节点
	 */
	public void jumpTask(String procInsId, String currentTaskId, String targetTaskDefinitionKey, Map<String, Object> variables) {
		jumpTask(getTaskEntity(currentTaskId), targetTaskDefinitionKey, variables);
	}

	/**
	 * 跳转(包括回退和向前)至指定活动节点
	 * @param currentTaskEntity 当前任务节点
	 * @param targetTaskDefinitionKey 目标任务节点(在模型定义里面的节点名称)
	 * @throws Exception
	 */
	public void jumpTask(TaskEntity currentTaskEntity, String targetTaskDefinitionKey, Map<String, Object> variables) {
		ActivityImpl activity = ProcessDefUtils.getActivity(processEngine, currentTaskEntity.getProcessDefinitionId(),
				targetTaskDefinitionKey);
		jumpTask(currentTaskEntity, activity, variables);
	}

	/**
	 * 跳转(包括回退和向前)至指定活动节点
	 * @param currentTaskEntity 当前任务节点
	 * @param targetActivity 目标任务节点(在模型定义里面的节点名称)
	 * @throws Exception
	 */
	private void jumpTask(TaskEntity currentTaskEntity, ActivityImpl targetActivity, Map<String, Object> variables) {
		CommandExecutor commandExecutor = ((RuntimeServiceImpl) runtimeService).getCommandExecutor();
		commandExecutor.execute(new JumpTaskCmd(currentTaskEntity, targetActivity, variables));
	}

	/**
	 * 后加签
	 */
	@SuppressWarnings("unchecked")
	public ActivityImpl[] insertTasksAfter(String procDefId, String procInsId, String targetTaskDefinitionKey, Map<String, Object> variables, String... assignees) {
		List<String> assigneeList = new ArrayList<String>();
		assigneeList.add(Authentication.getAuthenticatedUserId());
		assigneeList.addAll(CollectionUtils.arrayToList(assignees));
		String[] newAssignees = assigneeList.toArray(new String[0]);
		ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity)repositoryService.getProcessDefinition(procDefId);
		ActivityImpl prototypeActivity = ProcessDefUtils.getActivity(processEngine, processDefinition.getId(), targetTaskDefinitionKey);
		return cloneAndMakeChain(processDefinition, procInsId, targetTaskDefinitionKey, prototypeActivity.getOutgoingTransitions().get(0).getDestination().getId(), variables, newAssignees);
	}

	/**
	 * 前加签
	 */
	public ActivityImpl[] insertTasksBefore(String procDefId, String procInsId, String targetTaskDefinitionKey, Map<String, Object> variables, String... assignees) {
		ProcessDefinitionEntity procDef = (ProcessDefinitionEntity)repositoryService.getProcessDefinition(procDefId);
		return cloneAndMakeChain(procDef, procInsId, targetTaskDefinitionKey, targetTaskDefinitionKey, variables, assignees);
	}

	/**
	 * 分裂某节点为多实例节点
	 */
	public ActivityImpl splitTask(String procDefId, String procInsId, String targetTaskDefinitionKey, Map<String, Object> variables, String... assignee) {
		return splitTask(procDefId, procInsId, targetTaskDefinitionKey, variables, true, assignee);
	}

	/**
	 * 分裂某节点为多实例节点
	 */
	@SuppressWarnings("unchecked")
	public ActivityImpl splitTask(String procDefId, String procInsId, String targetTaskDefinitionKey, Map<String, Object> variables, boolean isSequential, String... assignees) {
		SimpleRuntimeActivityDefinitionEntity info = new SimpleRuntimeActivityDefinitionEntity();
		info.setProcessDefinitionId(procDefId);
		info.setProcessInstanceId(procInsId);

		RuntimeActivityDefinitionEntityIntepreter radei = new RuntimeActivityDefinitionEntityIntepreter(info);

		radei.setPrototypeActivityId(targetTaskDefinitionKey);
		radei.setAssignees(CollectionUtils.arrayToList(assignees));
		radei.setSequential(isSequential);

		ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity)repositoryService.getProcessDefinition(procDefId);
		ActivityImpl clone = new MultiInstanceActivityCreator().createActivities(processEngine, processDefinition, info)[0];

		TaskEntity currentTaskEntity = this.getCurrentTask(procInsId);

		CommandExecutor commandExecutor = ((RuntimeServiceImpl) runtimeService).getCommandExecutor();
		commandExecutor.execute(new CreateAndTakeTransitionCmd(currentTaskEntity, clone, variables));

//		recordActivitiesCreation(info);
		return clone;
	}

	private TaskEntity getCurrentTask(String procInsId) {
		return (TaskEntity) taskService.createTaskQuery().processInstanceId(procInsId).active().singleResult();
	}

	private TaskEntity getTaskEntity(String taskId) {
		return (TaskEntity) taskService.createTaskQuery().taskId(taskId).singleResult();
	}

	@SuppressWarnings("unchecked")
	private ActivityImpl[] cloneAndMakeChain(ProcessDefinitionEntity procDef, String procInsId, String prototypeActivityId, String nextActivityId, Map<String, Object> variables, String... assignees) {
		SimpleRuntimeActivityDefinitionEntity info = new SimpleRuntimeActivityDefinitionEntity();
		info.setProcessDefinitionId(procDef.getId());
		info.setProcessInstanceId(procInsId);

		RuntimeActivityDefinitionEntityIntepreter radei = new RuntimeActivityDefinitionEntityIntepreter(info);
		radei.setPrototypeActivityId(prototypeActivityId);
		radei.setAssignees(CollectionUtils.arrayToList(assignees));
		radei.setNextActivityId(nextActivityId);

		ActivityImpl[] activities = new ChainedActivitiesCreator().createActivities(processEngine, procDef, info);

		jumpTask(procInsId, activities[0].getId(), variables);
//		recordActivitiesCreation(info);

		return activities;
	}

//	private void recordActivitiesCreation(SimpleRuntimeActivityDefinitionEntity info) {
//		info.serializeProperties();
//		_activitiesCreationStore.save(info);
//	}

	////////////////////////////////////////////////////////////////////

//	private void recordActivitiesCreation(SimpleRuntimeActivityDefinitionEntity info) throws Exception {
//		info.serializeProperties();
//		_activitiesCreationStore.save(info);
//	}
//
//	/**
//	 * 分裂某节点为多实例节点
//	 *
//	 * @param targetTaskDefinitionKey
//	 * @param assignee
//	 * @throws IOException
//	 * @throws IllegalAccessException
//	 * @throws IllegalArgumentException
//	 */
//	public ActivityImpl split(String targetTaskDefinitionKey, boolean isSequential, String... assignees) throws Exception {
//		SimpleRuntimeActivityDefinitionEntity info = new SimpleRuntimeActivityDefinitionEntity();
//		info.setProcessDefinitionId(processDefinition.getId());
//		info.setProcessInstanceId(_processInstanceId);
//
//		RuntimeActivityDefinitionEntityIntepreter radei = new RuntimeActivityDefinitionEntityIntepreter(info);
//
//		radei.setPrototypeActivityId(targetTaskDefinitionKey);
//		radei.setAssignees(CollectionUtils.arrayToList(assignees));
//		radei.setSequential(isSequential);
//
//		ActivityImpl clone = new MultiInstanceActivityCreator().createActivities(_processEngine, processDefinition, info)[0];
//
//		TaskEntity currentTaskEntity = getCurrentTask();
//		executeCommand(new CreateAndTakeTransitionCmd(currentTaskEntity.getExecutionId(), clone));
//		executeCommand(new DeleteRunningTaskCmd(currentTaskEntity));
//
//		recordActivitiesCreation(info);
//		return clone;
//	}
//
//	public ActivityImpl split(String targetTaskDefinitionKey, String... assignee) throws Exception {
//		return split(targetTaskDefinitionKey, true, assignee);
//	}

	////////////////////////////////////////////////////////////////////

	/**
	 * 读取带跟踪的图片
	 * @param executionId	环节ID
	 * @return	封装了各种节点信息
	 */
	public InputStream tracePhoto(String processDefinitionId, String executionId) {
//		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(executionId).singleResult();
		BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);

		List<String> activeActivityIds = Lists.newArrayList();
		if (runtimeService.createExecutionQuery().executionId(executionId).count() > 0){
			activeActivityIds = runtimeService.getActiveActivityIds(executionId);
		}

		// 不使用spring请使用下面的两行代码
		// ProcessEngineImpl defaultProcessEngine = (ProcessEngineImpl)ProcessEngines.getDefaultProcessEngine();
		// Context.setProcessEngineConfiguration(defaultProcessEngine.getProcessEngineConfiguration());

		// 使用spring注入引擎请使用下面的这行代码
		Context.setProcessEngineConfiguration(processEngineFactory.getProcessEngineConfiguration());
//		return ProcessDiagramGenerator.generateDiagram(bpmnModel, "png", activeActivityIds);
		return processEngine.getProcessEngineConfiguration().getProcessDiagramGenerator()
				.generateDiagram(bpmnModel, "png", activeActivityIds);
	}

	/**
	 * 流程跟踪图信息
	 * @param processInstanceId		流程实例ID
	 * @return	封装了各种节点信息
	 */
	public List<Map<String, Object>> traceProcess(String processInstanceId) throws Exception {
		Execution execution = runtimeService.createExecutionQuery().executionId(processInstanceId).singleResult();//执行实例
		Object property = PropertyUtils.getProperty(execution, "activityId");
		String activityId = "";
		if (property != null) {
			activityId = property.toString();
		}
		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId)
				.singleResult();
		ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
				.getDeployedProcessDefinition(processInstance.getProcessDefinitionId());
		List<ActivityImpl> activitiList = processDefinition.getActivities();//获得当前任务的所有节点

		List<Map<String, Object>> activityInfos = new ArrayList<Map<String, Object>>();
		for (ActivityImpl activity : activitiList) {

			boolean currentActiviti = false;
			String id = activity.getId();

			// 当前节点
			if (id.equals(activityId)) {
				currentActiviti = true;
			}

			Map<String, Object> activityImageInfo = packageSingleActivitiInfo(activity, processInstance, currentActiviti);

			activityInfos.add(activityImageInfo);
		}

		return activityInfos;
	}

	/**
	 * 封装输出信息,包括:当前节点的X、Y坐标、变量信息、任务类型、任务描述
	 * @param activity
	 * @param processInstance
	 * @param currentActiviti
	 * @return
	 */
	private Map<String, Object> packageSingleActivitiInfo(ActivityImpl activity, ProcessInstance processInstance,
			boolean currentActiviti) throws Exception {
		Map<String, Object> vars = new HashMap<String, Object>();
		Map<String, Object> activityInfo = new HashMap<String, Object>();
		activityInfo.put("currentActiviti", currentActiviti);
		setPosition(activity, activityInfo);
		setWidthAndHeight(activity, activityInfo);

		Map<String, Object> properties = activity.getProperties();
		vars.put("节点名称", properties.get("name"));
		vars.put("任务类型", ActUtils.parseToZhType(properties.get("type").toString()));

		ActivityBehavior activityBehavior = activity.getActivityBehavior();
		logger.debug("activityBehavior={}", activityBehavior);
		if (activityBehavior instanceof UserTaskActivityBehavior) {

			Task currentTask = null;

			// 当前节点的task
			if (currentActiviti) {
				currentTask = getCurrentTaskInfo(processInstance);
			}

			// 当前任务的分配角色
			UserTaskActivityBehavior userTaskActivityBehavior = (UserTaskActivityBehavior) activityBehavior;
			TaskDefinition taskDefinition = userTaskActivityBehavior.getTaskDefinition();
			Set<Expression> candidateGroupIdExpressions = taskDefinition.getCandidateGroupIdExpressions();
			if (!candidateGroupIdExpressions.isEmpty()) {

				// 任务的处理角色
				setTaskGroup(vars, candidateGroupIdExpressions);

				// 当前处理人
				if (currentTask != null) {
					setCurrentTaskAssignee(vars, currentTask);
				}
			}
		}

		vars.put("节点说明", properties.get("documentation"));

		String description = activity.getProcessDefinition().getDescription();
		vars.put("描述", description);

		logger.debug("trace variables: {}", vars);
		activityInfo.put("vars", vars);
		return activityInfo;
	}

	/**
	 * 设置任务组
	 * @param vars
	 * @param candidateGroupIdExpressions
	 */
	private void setTaskGroup(Map<String, Object> vars, Set<Expression> candidateGroupIdExpressions) {
		String roles = "";
		for (Expression expression : candidateGroupIdExpressions) {
			String expressionText = expression.getExpressionText();
			String roleName = identityService.createGroupQuery().groupId(expressionText).singleResult().getName();
			roles += roleName;
		}
		vars.put("任务所属角色", roles);
	}

	/**
	 * 设置当前处理人信息
	 * @param vars
	 * @param currentTask
	 */
	private void setCurrentTaskAssignee(Map<String, Object> vars, Task currentTask) {
		String assignee = currentTask.getAssignee();
		if (assignee != null) {
			org.activiti.engine.identity.User assigneeUser = identityService.createUserQuery().userId(assignee).singleResult();
			String userInfo = assigneeUser.getFirstName() + " " + assigneeUser.getLastName();
			vars.put("当前处理人", userInfo);
		}
	}

	/**
	 * 获取当前节点信息
	 * @param processInstance
	 * @return
	 */
	private Task getCurrentTaskInfo(ProcessInstance processInstance) {
		Task currentTask = null;
		try {
			String activitiId = (String) PropertyUtils.getProperty(processInstance, "activityId");
			logger.debug("current activity id: {}", activitiId);

			currentTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskDefinitionKey(activitiId)
					.singleResult();
			logger.debug("current task for processInstance: {}", ToStringBuilder.reflectionToString(currentTask));

		} catch (Exception e) {
			logger.error("can not get property activityId from processInstance: {}", processInstance);
		}
		return currentTask;
	}

	/**
	 * 设置宽度、高度属性
	 * @param activity
	 * @param activityInfo
	 */
	private void setWidthAndHeight(ActivityImpl activity, Map<String, Object> activityInfo) {
		activityInfo.put("width", activity.getWidth());
		activityInfo.put("height", activity.getHeight());
	}

	/**
	 * 设置坐标位置
	 * @param activity
	 * @param activityInfo
	 */
	private void setPosition(ActivityImpl activity, Map<String, Object> activityInfo) {
		activityInfo.put("x", activity.getX());
		activityInfo.put("y", activity.getY());
	}

	public ProcessEngine getProcessEngine() {
		return processEngine;
	}

}


text:
//
//  GrowlPluginPreferenceStrings.h
//  Growl
//
//  Created by Daniel Siemer on 1/30/12.
//  Copyright (c) 2012 The Growl Project. All rights reserved.
//

/* FOR GROWL DEVELOPED COCOA PLUGINS ONLY AT THIS TIME, NOT STABLE */

#import <Foundation/Foundation.h>

@interface GrowlPluginPreferenceStrings : NSObject

@property (nonatomic, retain) NSString *growlDisplayOpacity;
@property (nonatomic, retain) NSString *growlDisplayDuration;

@property (nonatomic, retain) NSString *growlDisplayPriority;
@property (nonatomic, retain) NSString *growlDisplayPriorityVeryLow;
@property (nonatomic, retain) NSString *growlDisplayPriorityModerate;
@property (nonatomic, retain) NSString *growlDisplayPriorityNormal;
@property (nonatomic, retain) NSString *growlDisplayPriorityHigh;
@property (nonatomic, retain) NSString *growlDisplayPriorityEmergency;

@property (nonatomic, retain) NSString *growlDisplayTextColor;
@property (nonatomic, retain) NSString *growlDisplayBackgroundColor;

@property (nonatomic, retain) NSString *growlDisplayLimitLines;
@property (nonatomic, retain) NSString *growlDisplayScreen;
@property (nonatomic, retain) NSString *growlDisplaySize;
@property (nonatomic, retain) NSString *growlDisplaySizeNormal;
@property (nonatomic, retain) NSString *growlDisplaySizeLarge;
@property (nonatomic, retain) NSString *growlDisplaySizeSmall;

@property (nonatomic, retain) NSString *growlDisplayFloatingIcon;

@property (nonatomic, retain) NSString *effectLabel;
@property (nonatomic, retain) NSString *slideEffect;
@property (nonatomic, retain) NSString *fadeEffect;

@end

redpajama_set_name: RedPajamaGithub


text:
const Travis = require(`travis-ci`),
      _ = require('lodash/fp'),
      optionParser = require('node-getopt').create([
        ['b', 'branch=[ARG]', 'Branch to query; Default is master'],
        ['h', 'help', 'Display this help']]);

var travis = new Travis({
    version: `2.0.0`,
    headers: {
        'user-agent': 'Travis/1.0'
    }
});

const arg = optionParser.bindHelp().parseSystem();
const branch = _.getOr('master', 'branch', arg.options);

var isRelevantCommitId = _.curry((successfulCommits, commitOnBranch) => _.includes(commitOnBranch.id, successfulCommits));

var getCommitsOnBranch = _.compose(
    _.filter({branch}),
    _.prop('commits')
);

var getCommitIdsThatPassed = _.compose(
    _.map(_.prop('commit_id')),
    _.filter({state: 'passed'}),
    _.prop('builds')
);

var getLatestCommit = _.compose(
    _.head,
    _.sortBy('commited_at')
);

travis.authenticate({
    github_token: process.env.GITHUB_TOKEN
}, (error) => {
    if (error) {
        console.log(`Error authenticating: ${error}`);
        return;
    }

    travis.repos('4minitz', '4minitz').builds().get((error, response) => {
        if (error) {
            console.error(`Error getting latest builds: ${error}`);
            return;
        }

        const commitsOnBranch = getCommitsOnBranch(response);
        const commitsThatPassed = getCommitIdsThatPassed(response);
        const commitsOnBranchThatPassed = _.filter(isRelevantCommitId(commitsThatPassed), commitsOnBranch);
        const latestStableCommit = getLatestCommit(commitsOnBranchThatPassed);

        const sha = _.getOr('', 'sha', latestStableCommit);

        console.log(sha);
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/specific-people/photographers/taber-photographer-san-francisco" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/photographers/taber-photographer-san-francisco</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Taber, photographer (San Francisco)</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/photographers/taber-photographer-san-francisco</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/photographers/taber-photographer-san-francisco</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
var word = 'bar';

function speak(word) { // implicit local `var word = bar`
  word = 'baz'; // overwrite local `word`
  return word;
}
console.log(speak()) // => 'baz'
console.log(word) // => 'bar'


text:
//-----------------------------------------------------------------------
// <copyright file="LayoutHelper.cs" company="none">
// Copyright (c) kenny-nelson All Rights Reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Dodai.Helpers
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Dodai;
    using Xceed.Wpf.AvalonDock.Layout;
    using Xceed.Wpf.AvalonDock.Layout.Serialization;

    /// <summary>
    /// レイアウトヘルパークラスです。
    /// </summary>
    public static class LayoutHelper
    {
        /// <summary>
        /// レイアウトのコンフィグファイル名です。
        /// </summary>
        public const string LayoutConfigFile = @".\Dodai.AvalonDock.config";

        /// <summary>
        /// アヴァロンドックのコンフィグファイルが存在するか判定します。
        /// </summary>
        /// <returns>存在すれば、真を返します。</returns>
        public static bool HasAvalonDockConfigFile()
        {
            return File.Exists(LayoutConfigFile);
        }

        /// <summary>
        /// レイアウトのシリアライズ処理を呼び出します。
        /// </summary>
        /// <param name="sender">送信元のオブジェクトです。</param>
        /// <param name="e">イベント引数です。</param>
        public static void CallLayoutSerialization(object sender, LayoutSerializationCallbackEventArgs e)
        {
            var anchorable = e.Model as LayoutAnchorable;
            if (anchorable != null)
            {
                var panelPresenter = GlobalPresenter.GetPanelPresenter();
                var factory = GlobalPresenter.GetToolFactory(e.Model.ContentId);
                if (factory != null)
                {
                    var tool = GlobalPresenter.AddTool(factory, panelPresenter);
                    e.Content = tool;
                    tool.IsVisible = anchorable.IsVisible;
                    if (anchorable.IsActive)
                    {
                        tool.IsActive = true;
                    }

                    tool.IsSelected = anchorable.IsSelected;
                }
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
}


text:
#! /usr/bin/env node

/* perform the following steps

* set working directory X
* create directory structure
* write out package.json to wd
* run npm init
* preprocess our templates
* write processed files to wd
* npm install dev deps
* clean up
 */

var os = require('os'),
    fs = require('fs-extra'),
    path = require('path'),
    spawn = require('child_process').spawnSync,
    interpolate = require('es6-interpolate-stream'),
    cwd = process.cwd(),
    templateDir = path.normalize(__dirname + '/../templates'),
    tempDir = cwd + '/.tmp';

fs.mkdirSync(tempDir);

fs.copySync(templateDir + '/package.json',
  cwd + '/package.json');

fs.copySync(templateDir + '/index.js',
  cwd + '/index.js');

function checkExit (cmd, status) {
  if (status) {
    console.log("Error: " + cmd
      + "exited with status " + status);
    process.exit(status);
  }
}

function getPkg() {
  return JSON.parse(fs.readFileSync('package.json', 'utf8'));
}

checkExit('npm init', spawn('npm', ['init'], {stdio: 'inherit'}).status);

var context = getPkg();
context.year = (new Date()).getFullYear();
var s = fs.createReadStream('index.js', {encoding: 'utf8'})
  .pipe(interpolate(context))
  .pipe(fs.createWriteStream(tempDir + '/index.js', {encoding: 'utf8'}))
  .on('finish', function () {
    fs.copySync(tempDir + '/index.js', cwd + '/index.js');
    fs.removeSync(tempDir);
  });

checkExit('npm install', spawn('npm', ['install'], {stdio: 'inherit'}).status);

console.log('OK!');


text:
<html>
<head>
<script type='application/javascript'>
window.onload = function() { window.location = "textmatch-upload.jsp" }
</script>
</html>
</head>


text:
@interface MoviesViewController () <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSArray *movies;
@property (strong, nonatomic) NSArray *searchResults;
@property (weak, nonatomic) IBOutlet UIView *networkErrorAlertView;
@property (strong, nonatomic) UIRefreshControl *refreshControl;
@end

@implementation MoviesViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.timeoutIntervalForRequest = 3.0;
    [self.networkErrorAlertView setHidden:YES];

    self.searchBar.delegate = self;

    // Do any additional setup after loading the view, typically from a nib.
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];

    self.refreshControl = [[UIRefreshControl alloc] init];
    self.refreshControl.tintColor = [UIColor whiteColor];
    [self.refreshControl addTarget:self action:@selector(onRefresh) forControlEvents:UIControlEventValueChanged];
    [self.tableView insertSubview:self.refreshControl atIndex:0];

    [self onRefresh];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length == 0) {
        [self.searchBar setShowsCancelButton:NO];
        [self.searchBar resignFirstResponder];
    } else {
        [self.searchBar setShowsCancelButton:YES];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.title contains[cd] %@", searchText];
        self.searchResults = [self.movies filteredArrayUsingPredicate:predicate];
    }
    [self.tableView reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.text=@"";
    [searchBar setShowsCancelButton:NO];
    [searchBar resignFirstResponder];
    self.searchResults = self.movies;
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.searchResults count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    MoviesTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"movieCell"];
    cell.titleLabel.text = self.searchResults[indexPath.row][@"title"];
    cell.synopsisLabel.text = self.searchResults[indexPath.row][@"synopsis"];

    [self fadeInImages:self.searchResults[indexPath.row][@"posters"][@"thumbnail"] CellImageView:cell.posterImageView];

    cell.mpaaRateLabel.text = self.searchResults[indexPath.row][@"mpaa_rating"];
    cell.timeLabel.text = [NSString stringWithFormat:@"%@%@", self.searchResults[indexPath.row][@"runtime"], @"min"];

    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    if ([@"Spilled" isEqualToString:self.searchResults[indexPath.row][@"ratings"][@"audience_rating"]])
        attachment.image = [UIImage imageNamed:@"rotten.png"];
    else
        attachment.image = [UIImage imageNamed:@"tomato.png"];

    NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];
    NSMutableString *ratingString = [NSMutableString stringWithFormat:@" %@%%", self.searchResults[indexPath.row][@"ratings"][@"audience_score"]];

    NSMutableAttributedString *ratingStringWithAttachment = [[NSMutableAttributedString alloc] initWithAttributedString:attachmentString];
    NSAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:ratingString];
    [ratingStringWithAttachment appendAttributedString:attributedString];
    cell.ratingLabel.attributedText = ratingStringWithAttachment;

    cell.accessoryType = UITableViewCellAccessoryNone;
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender {
    MovieDetailViewController *detailsViewController = [segue destinationViewController];

    NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
    NSDictionary *movie = self.searchResults[indexPath.row];
    detailsViewController.movie = movie;
}

- (void)onRefresh {
    NSString *urlString = @"https://gist.githubusercontent.com/timothy1ee/d1778ca5b944ed974db0/raw/489d812c7ceeec0ac15ab77bf7c47849f2d1eb2b/gistfile1.json";

    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    NSURLSession *session =
    [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                  delegate:nil
                             delegateQueue:[NSOperationQueue mainQueue]];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData * _Nullable data,
                                                                NSURLResponse * _Nullable response,
                                                                NSError * _Nullable error) {
                                                if (!error) {
                                                    NSError *jsonError = nil;
                                                    NSDictionary *responseDictionary =
                                                    [NSJSONSerialization JSONObjectWithData:data
                                                                                options:kNilOptions
                                                                                error:&jsonError];
                                                    self.movies = responseDictionary[@"movies"];
                                                    self.searchResults = self.movies;
                                                    [self.tableView reloadData];

                                                    [self.networkErrorAlertView setHidden:YES];
                                                    [self.tableView setHidden:NO];
                                                    NSLog(@"Response: %@", responseDictionary);
                                                } else {
                                                    [self.networkErrorAlertView setHidden:NO];
                                                    [self.tableView setHidden:YES];
                                                    NSLog(@"An error occurred: %@", error.description);
                                                }
                                                [self.refreshControl endRefreshing];
                                            }];
    [task resume];
}

- (void)fadeInImages:(NSString*)url CellImageView:(UIImageView*) imageView {
    NSURL *imageUrl = [NSURL URLWithString:url];

    NSURLRequest *imageUrlRequest = [NSURLRequest requestWithURL:imageUrl];
    __weak UIImageView *weakSelf = imageView;
    [imageView setImageWithURLRequest:imageUrlRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        UIImage *cachedImage = [[[weakSelf class] sharedImageCache] cachedImageForRequest:request];
        if (cachedImage) // image was cached
            [weakSelf setImage:image];
        else
            [UIView transitionWithView:weakSelf duration:0.5f options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
                [weakSelf setImage:image];
            } completion:nil];
    } failure:nil];
}

@end


text:
/*#############################################################################
 ::: Namespace, settings, vars
 ############################################################################*/
/**
 * @namespace The namespace for the whole diagram JavaScript.
 */
var opr = opr || {};
opr.settings = {
    defaultCacheExpiration : 60000, // milli seconds
    urls : {
        suggestTag : "/suggest/tag?start={0}"
    }
}
opr.vars = {
    jsonCache : {}
};

/*#############################################################################
 ::: Manage pattern toggle accordion
 ############################################################################*/
$(function() {
    $(".accordion > div").not(":first").hide();

    $('.togglePreviewSize').click(function() {
        $(this).siblings('.markdownEditor, .preview').toggleClass('bigger');
        return false;
    });

    opr.markdown.enable();
    // click listener should execute latest
    // maybe do this in a addField hook?
    // TODO
    addFieldAddListener(opr.markdown.enable);

    var hideAll = function(except) {
        if (except == undefined) {
            $(".accordion > div").slideUp();
        } else {
            $(".accordion > div").not(except).slideUp();
        }

    }

    $(".accordion > h2").click(function() {
        $(this).next().slideToggle();
        return false;
    });

    $(".accordion > div > input.previous").click(function() {
        var target = $(this).parent().prev().prev();
        hideAll(target);

        target.slideDown();

        target.find(":input:visible:first").focus();

        return false;
    });

    $(".accordion > div > input.next").click(function() {
        var target = $(this).parent().next().next();
        hideAll(target);

        target.slideDown();

        target.find(":input:visible:first").focus();

        return false;
    });

    $(".accordion-manage-links > .open-all").click(function() {
        $(this).parent().prev(".accordion").children("div").slideDown();
        return false;
    });

    $(".accordion-manage-links > .close-all").click(function() {
        $(this).parent().prev(".accordion").children("div").slideUp();
        return false;
    });

    $(".accordion-manage-links > .with-errors").click(function() {
        $(this).parent().prev(".accordion").children("div").each(function() {
            if ($(this).find(".errors").length != 0) {
                $(this).slideDown();
            } else {
                $(this).slideUp();
            }
        });

        return false;
    });

    $(".accordion").each(function() {
        opr.accordion.openWithErrors($(this));
    });
});

opr.accordion = {
    openWithErrors : function(accordion, openAtLeastOne) {
        var anythingOpen = false;

        accordion.children("div").each(function() {
            if ($(this).find(".errors").length != 0) {
                $(this).show();
                anythingOpen = true;
            } else {
                $(this).hide();
            }
        });

        if (!anythingOpen && (openAtLeastOne === undefined || openAtLeastOne === true)) {
            accordion.children("div:first").show();
        }
    }
}
opr.markdown = {
    idCounter : 0
};
opr.markdown.enable = function() {
    var buttons = $('#page_content .markdownEditor-buttons');
    var editors = $('#page_content  .markdownEditor');
    var previews = $('#page_content .markdownEditor-preview');

    for (var i = 0; i < buttons.length; i++) {
        var button = $(buttons[i]);
        // check for visibility because of the field templates which are
        // located at the end of the file
        // TODO check for button visibility
        if (button.data('wmdActivated') !== true) {
            button.attr('id', 'wmd-button-bar' + opr.markdown.idCounter);
            button.data('wmdActivated', true);
            $(editors[i]).attr('id', 'wmd-input' + opr.markdown.idCounter);
            $(previews[i]).attr('id', 'wmd-preview' + opr.markdown.idCounter);

            var converter = Markdown.getSanitizingConverter();
            new Markdown.Editor(converter, opr.markdown.idCounter.toString()).run();
            opr.markdown.idCounter++;
        }
    }
}

/*#############################################################################
 ::: Manage pattern add / remove tag behaviour
 ############################################################################*/
opr.managePattern = {}

$(function() {
    $('.tag_autocomplete').autocomplete({
        minLength : 3,
        source : function(request, response) {
            var url = opr.settings.urls.suggestTag.replace("{0}",
                    request.term);

            opr.cachedJSONRequest(url, {}, function(data) {
                // remove tags that have already been added
                var tags = [];
                for (var i = data.length - 1; i >= 0; i--) {
                    var suggestedTag = data[i].name;
                    if (!opr.managePattern.containsTag(suggestedTag)) {
                        tags.push(suggestedTag);
                    }
                }

                response(tags);
            });
        }
    });

    $('#add_tag').click(opr.managePattern.addTag);

    $('#input_tag').keypress(function(event) {
        if (event.keyCode == 13) {
            $('#add_tag').click();
            return false;
        }
    });

    // reload tags after server side validation error
    var tagOut = $("#pattern_tag_list");
    if (tagOut.length == 0) {
        return;
    }
    var allTags = tagOut.val().trim().split(',');

    for (var i = 0; i < allTags.length; i++) {
        if (allTags[i].trim().length != 0) {
            opr.managePattern.addTagToList(allTags[i]);
        }
    }
});

opr.managePattern.addTag = function() {
    // retrieve the value and reset the input field
    var input = $("#input_tag");
    var newTags = input.val().trim().split(",");
    input.val("");

    var tagOut = $("#pattern_tag_list");
    var addedTags = tagOut.val().split(',');
    var tagDuplication = false;
    for (var i = 0; i < newTags.length; i++) {
        var tagComparable = newTags[i].toLowerCase();

        if (tagComparable.trim().length == 0) {
            continue;
        }

        tagDuplication = false;

        for (var j = 0; j < addedTags.length; j++) {
            if (addedTags[j].toLowerCase() == tagComparable) {
                tagDuplication = true;
                break;
            }
        }

        if (!tagDuplication) {
            addedTags.push(newTags[i]);
            opr.managePattern.addTagToList(newTags[i]);
        }
    }

    tagOut.val(addedTags.join(',').trim());

    return false;
}

opr.managePattern.addTagToList = function(tag) {
    var li = document.createElement("li");

    // jquery is good at escaping and events
    $(li).text(tag);

    var a = document.createElement("a");
    a.title = "Remove this tag";
    $(a).text("X").click(function() {
        $(this).parent().remove();
        opr.managePattern.removeTagFromInput(tag);
    });

    li.appendChild(a);

    document.getElementById("output_tag").appendChild(li);
}

opr.managePattern.removeTagFromInput = function(tag) {
    var tagOut = $("#pattern_tag_list");
    var allTags = tagOut.val().split(',');

    tag = tag.toLowerCase();

    for (var i = allTags.length - 1; i >= 0; i--) {
        if (allTags[i].toLowerCase() == tag) {
            allTags.splice(i, 1);
        }
    }

    tagOut.val(allTags.join(',').trim());
}

opr.managePattern.containsTag = function(tag) {
    var tagOut = $("#pattern_tag_list");
    var allTags = tagOut.val().split(',');

    tag = tag.toLowerCase();

    for (var i = 0; i < allTags.length; i++) {
        if (allTags[i].toLowerCase() == tag) {
            return true;
        }
    }

    return false;
}

/*#############################################################################
 ::: JSON async request caching
 ############################################################################*/
opr.cachedJSONRequest = function(url, parameter, callback, expiration) {
    if (expiration === undefined) {
        expiration = opr.settings.defaultCacheExpiration;
    }

    var urlCache = opr.vars.jsonCache[url];

    if (urlCache == undefined) {
        opr.vars.jsonCache[url] = {}
        opr.doCachedJSONRequest(url, parameter, callback)
        return;
    }

    var parameterCache = urlCache[parameter];

    var timeDelta = new Date().getTime() - parameterCache['time'].getTime();

    if (parameterCache == undefined ||
            timeDelta >= expiration) {
        opr.doCachedJSONRequest(url, parameter, callback)
    } else {
        callback(parameterCache['result']);
    }
}

opr.doCachedJSONRequest = function(url, parameter, callback) {
    var parameterCache = opr.vars.jsonCache[url][parameter] = {};

    parameterCache['time'] = new Date();
    parameterCache['xhr'] = $.getJSON(url, parameter, function(data, status, xhr) {
        parameterCache['result'] = data;
        if (xhr === parameterCache['xhr']) {
            callback(data);
        }
    });
}

/*#############################################################################
 ::: Validation
 ############################################################################*/
$(function() {
    opr.validation.init();
});

opr.validation = {};
opr.validation.init = function() {
    $("label .errors").each(function() {
        var error = $(this);
        $(this).parent().find(":input").change(function() {
            error.fadeOut();
        });
    });
};


text:
/* associative array */
void assoc_init(const int hashpower_init);
CItem *assoc_find(const char *key, const size_t nkey, const uint32_t hv);
int assoc_insert(CItem *item);
void assoc_delete(const char *key, const size_t nkey, const uint32_t hv);
void do_assoc_move_next_bucket(void);
int start_assoc_maintenance_thread(void);
void stop_assoc_maintenance_thread(void);
extern unsigned int hashpower;


text:
package net.canadensys.dataportal.occurrence.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

/**
 * Configuration class for Explorer caching.
 *
 * @author cgendreau
 *
 */
@Configuration
@EnableCaching
public class CachingConfig {

	@Bean
	public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
		EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
		ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource(
				"ehcache.xml"));
		return ehCacheManagerFactoryBean;
	}

	@Bean
	public CacheManager cacheManager() {
		EhCacheCacheManager cacheManager = new EhCacheCacheManager();
		cacheManager.setCacheManager(ehCacheManagerFactoryBean().getObject());
		return cacheManager;
	}
}


text:
package ca.corefacility.bioinformatics.irida.ria.unit.web.services;

import java.security.Principal;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.context.MessageSource;
import org.springframework.mail.MailSendException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import ca.corefacility.bioinformatics.irida.exceptions.EntityExistsException;
import ca.corefacility.bioinformatics.irida.model.user.PasswordReset;
import ca.corefacility.bioinformatics.irida.model.user.Role;
import ca.corefacility.bioinformatics.irida.model.user.User;
import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.ajax.AjaxCreateItemSuccessResponse;
import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.ajax.AjaxSuccessResponse;
import ca.corefacility.bioinformatics.irida.ria.web.exceptions.UIEmailSendException;
import ca.corefacility.bioinformatics.irida.ria.web.exceptions.UIUserFormException;
import ca.corefacility.bioinformatics.irida.ria.web.exceptions.UIUserStatusException;
import ca.corefacility.bioinformatics.irida.ria.web.services.UIUsersService;
import ca.corefacility.bioinformatics.irida.ria.web.users.dto.UserCreateRequest;
import ca.corefacility.bioinformatics.irida.ria.web.users.dto.UserDetailsModel;
import ca.corefacility.bioinformatics.irida.ria.web.users.dto.UserDetailsResponse;
import ca.corefacility.bioinformatics.irida.ria.web.users.dto.UserEditRequest;
import ca.corefacility.bioinformatics.irida.service.EmailController;
import ca.corefacility.bioinformatics.irida.service.user.PasswordResetService;
import ca.corefacility.bioinformatics.irida.service.user.UserService;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.*;import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

public class UIUsersServiceTest {
	private HttpServletRequest request;
	private UserService userService;
	private EmailController emailController;
	private MessageSource messageSource;
	private PasswordEncoder passwordEncoder;
	private UIUsersService service;
	private PasswordResetService passwordResetService;

	private final User USER1 = new User(1L, "Elsa", "elsa@arendelle.ca", "Password1!", "Elsa", "Oldenburg", "1234");
	private final User USER2 = new User(2L, "Anna", "anna@arendelle.ca", "Password2!", "Anna", "Oldenburg", "5678");
	private final PasswordReset PASSWORD_RESET = new PasswordReset(USER2);

	@BeforeEach
	void setUp() {
		request = mock(HttpServletRequest.class);
		userService = mock(UserService.class);
		emailController = mock(EmailController.class);
		messageSource = mock(MessageSource.class);
		passwordEncoder = new BCryptPasswordEncoder();
		passwordResetService = mock(PasswordResetService.class);
		service = new UIUsersService(userService, emailController, messageSource, passwordEncoder,
				passwordResetService);

		when(userService.create(any())).thenReturn(USER2);
		when(userService.read(anyLong())).thenReturn(USER2);
		when(userService.getUserByUsername(anyString())).thenReturn(USER1);
		when(userService.updateFields(anyLong(), anyMap())).thenReturn(USER2);
		when(passwordResetService.create(new PasswordReset(any()))).thenReturn(PASSWORD_RESET);
		when(messageSource.getMessage(eq("systemRole.ROLE_ADMIN"), any(), any(Locale.class))).thenReturn("Admin");
		when(messageSource.getMessage(eq("systemRole.ROLE_MANAGER"), any(), any(Locale.class))).thenReturn("Manager");
		when(messageSource.getMessage(eq("systemRole.ROLE_USER"), any(), any(Locale.class))).thenReturn("User");
		when(messageSource.getMessage(eq("systemRole.ROLE_TECHNICIAN"), any(), any(Locale.class)))
				.thenReturn("Technician");
		when(messageSource.getMessage(eq("systemRole.ROLE_SEQUENCER"), any(), any(Locale.class)))
				.thenReturn("Sequencer");
	}

	@Test
	void createUserTest() throws UIUserFormException {
		Principal principal = () -> USER1.getFirstName();
		UserCreateRequest userCreateRequest = new UserCreateRequest(USER2.getUsername(), USER2.getFirstName(),
				USER2.getLastName(), USER2.getEmail(), USER2.getPhoneNumber(), USER2.getSystemRole().getName(),
				USER2.getLocale(), false, USER2.getPassword());

		AjaxCreateItemSuccessResponse response = service.createUser(userCreateRequest, principal, Locale.ENGLISH);

		assertEquals(USER2.getId(), response.getId(), "Incorrect user id.");
	}

	@Test
	void createUserTestWithEmailFailure() {
		Principal principal = () -> USER1.getFirstName();
		UserCreateRequest userCreateRequest = new UserCreateRequest(USER2.getUsername(), USER2.getFirstName(),
				USER2.getLastName(), USER2.getEmail(), USER2.getPhoneNumber(), USER2.getSystemRole().getName(),
				USER2.getLocale(), true, "");

		when(emailController.isMailConfigured()).thenReturn(true);
		doThrow(new MailSendException("Failed to send e-mail when creating user account.")).when(emailController)
				.sendWelcomeEmail(any(), any(), any());

		assertThrows(UIEmailSendException.class,
				() -> service.createUser(userCreateRequest, principal, Locale.ENGLISH));
	}

	@Test
	void createUserTestWithConstraint() {
		Principal principal = () -> USER1.getFirstName();
		UserCreateRequest userCreateRequest = new UserCreateRequest(USER2.getUsername(), USER2.getFirstName(),
				USER2.getLastName(), USER2.getEmail(), USER2.getPhoneNumber(), USER2.getSystemRole().getName(),
				USER2.getLocale(), false, USER2.getPassword());

		when(userService.create(any())).thenThrow(new EntityExistsException("This user already exists."));

		assertThrows(UIUserFormException.class, () -> service.createUser(userCreateRequest, principal, Locale.ENGLISH));
	}

	@Test
	void updateUserStatusTest() throws UIUserStatusException {
		String successMessage = "Anna has been disabled";

		when(messageSource.getMessage(eq("server.AdminUsersService.disabled"), any(), any(Locale.class)))
				.thenReturn(successMessage);

		AjaxSuccessResponse response = service.updateUserStatus(USER2.getId(), false, Locale.ENGLISH);

		assertEquals(successMessage, response.getMessage(), "Incorrect success message.");
	}

	@Test
	void getUserTest() {
		Principal principal = () -> USER1.getFirstName();
		UserDetailsModel userDetails = new UserDetailsModel(USER2);
		UserDetailsResponse expectedResponse = new UserDetailsResponse(userDetails, false, false, true, false, false);
		UserDetailsResponse response = service.getUser(USER1.getId(), principal);
		assertEquals(expectedResponse, response, "Incorrect user details.");
	}

	@Test
	void updateUserTest() throws UIUserFormException {
		Principal principal = () -> USER1.getFirstName();
		String successMessage = "The user was successfully updated.";
		UserEditRequest userEditRequest = new UserEditRequest(USER1.getFirstName(), USER1.getLastName(),
				USER1.getEmail(), USER1.getPhoneNumber(), USER1.getSystemRole().getName(), USER1.getLocale(),
				USER1.isEnabled());

		when(messageSource.getMessage(eq("server.user.edit.success"), any(), any(Locale.class)))
				.thenReturn(successMessage);

		AjaxSuccessResponse response = service.updateUser(USER1.getId(), userEditRequest, principal, request,
				Locale.ENGLISH);
		assertEquals(successMessage, response.getMessage(), "Incorrect success message.");
	}

	@Test
	void changeUserPasswordTest() throws UIUserFormException {
		Principal principal = () -> USER1.getFirstName();
		String successMessage = "Password successfully changed.";
		User savedUser = new User(USER1.getId(), USER1.getEmail(), USER1.getUsername(),
				passwordEncoder.encode(USER1.getPassword()), USER1.getFirstName(), USER1.getLastName(),
				USER1.getPhoneNumber());

		when(userService.getUserByUsername(anyString())).thenReturn(savedUser);
		when(messageSource.getMessage(eq("server.user.edit.password.success"), any(), any(Locale.class)))
				.thenReturn(successMessage);

		AjaxSuccessResponse response = service.changeUserPassword(USER1.getId(), USER1.getPassword(), "Password3!",
				principal, request, Locale.ENGLISH);
		assertEquals(successMessage, response.getMessage(), "Incorrect success message.");
	}

	@Test
	void adminNewPasswordResetTest() {
		User user1 = new User(1L, "Elsa", "elsa@arendelle.ca", "Password1!", "Elsa", "Oldenburg", "1234");
		user1.setSystemRole(Role.ROLE_ADMIN);
		User user2 = new User(2L, "Anna", "anna@arendelle.ca", "Password2!", "Anna", "Oldenburg", "5678");
		Principal principal = () -> user1.getFirstName();
		AjaxSuccessResponse response = null;

		when(userService.read(anyLong())).thenReturn(user2);
		when(userService.getUserByUsername(anyString())).thenReturn(user1);
		when(messageSource.getMessage(anyString(), any(), any(Locale.class))).thenReturn("success");

		try {
			response = service.adminNewPasswordReset(user2.getId(), principal, Locale.ENGLISH);
		} catch (UIEmailSendException e) {
			e.printStackTrace();
		}
		assertEquals("success", response.getMessage());
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Package org.openflow.protocol
</TITLE>

<META NAME="date" CONTENT="2013-08-27">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
org.openflow.protocol

Packages that use org.openflow.protocol

net.floodlightcontroller.core

net.floodlightcontroller.core.internal

net.floodlightcontroller.core.test

net.floodlightcontroller.core.types

net.floodlightcontroller.core.web

net.floodlightcontroller.counter

net.floodlightcontroller.devicemanager.internal

net.floodlightcontroller.devicemanager.normal

net.floodlightcontroller.firewall

net.floodlightcontroller.flowcache

net.floodlightcontroller.forwarding

net.floodlightcontroller.hub

net.floodlightcontroller.learningswitch

net.floodlightcontroller.linkdiscovery

net.floodlightcontroller.linkdiscovery.internal

net.floodlightcontroller.loadbalancer

net.floodlightcontroller.perfmon

net.floodlightcontroller.routing

net.floodlightcontroller.staticflowentry

net.floodlightcontroller.staticflowentry.web

net.floodlightcontroller.test

net.floodlightcontroller.topology

net.floodlightcontroller.util

net.floodlightcontroller.virtualnetwork

org.openflow.protocol

org.openflow.protocol.action

org.openflow.protocol.factory

org.openflow.protocol.serializers

org.openflow.protocol.statistics

org.openflow.protocol.vendor

org.openflow.vendor.nicira

org.openflow.vendor.openflow

Classes in org.openflow.protocol used by net.floodlightcontroller.core

OFFeaturesReply

          Represents a features reply message

OFMessage

          The base class for all OpenFlow protocol messages.

OFPhysicalPort

          Represents ofp_phy_port

OFStatisticsRequest

          Represents an ofp_stats_request message

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.core.internal

OFError

          Represents an ofp_error_msg

OFFeaturesReply

          Represents a features reply message

OFMessage

          The base class for all OpenFlow protocol messages.

OFPortStatus

          Represents an ofp_port_status message

OFStatisticsReply

          Represents an ofp_stats_reply message

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

OFVendor

          Represents ofp_vendor_header

Classes in org.openflow.protocol used by net.floodlightcontroller.core.test

OFMessage

          The base class for all OpenFlow protocol messages.

OFPacketIn

          Represents an ofp_packet_in

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.core.types

OFMessage

          The base class for all OpenFlow protocol messages.

Classes in org.openflow.protocol used by net.floodlightcontroller.core.web

OFFeaturesReply

          Represents a features reply message

Classes in org.openflow.protocol used by net.floodlightcontroller.counter

OFMessage

          The base class for all OpenFlow protocol messages.

Classes in org.openflow.protocol used by net.floodlightcontroller.devicemanager.internal

OFPacketIn

          Represents an ofp_packet_in

Classes in org.openflow.protocol used by net.floodlightcontroller.devicemanager.normal

OFMatchWithSwDpid

OFMessage

          The base class for all OpenFlow protocol messages.

OFPacketIn

          Represents an ofp_packet_in

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.firewall

OFMessage

          The base class for all OpenFlow protocol messages.

OFPacketIn

          Represents an ofp_packet_in

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.flowcache

OFMatch

          Represents an ofp_match structure

OFMatchWithSwDpid

OFMessage

          The base class for all OpenFlow protocol messages.

OFStatisticsRequest

          Represents an ofp_stats_request message

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.forwarding

OFFeaturesReply

          Represents a features reply message

OFPacketIn

          Represents an ofp_packet_in

OFPacketOut

          Represents an ofp_packet_out message

Classes in org.openflow.protocol used by net.floodlightcontroller.hub

OFMessage

          The base class for all OpenFlow protocol messages.

OFPacketIn

          Represents an ofp_packet_in

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.learningswitch

OFFlowRemoved

          Represents an ofp_flow_removed message

OFMatch

          Represents an ofp_match structure

OFMessage

          The base class for all OpenFlow protocol messages.

OFPacketIn

          Represents an ofp_packet_in

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.linkdiscovery

OFPacketOut

          Represents an ofp_packet_out message

Classes in org.openflow.protocol used by net.floodlightcontroller.linkdiscovery.internal

OFMessage

          The base class for all OpenFlow protocol messages.

OFPacketIn

          Represents an ofp_packet_in

OFPacketOut

          Represents an ofp_packet_out message

OFPhysicalPort

          Represents ofp_phy_port

OFPortStatus

          Represents an ofp_port_status message

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.loadbalancer

OFFlowMod

          Represents an ofp_flow_mod message

OFMessage

          The base class for all OpenFlow protocol messages.

OFPacketIn

          Represents an ofp_packet_in

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.perfmon

OFMessage

          The base class for all OpenFlow protocol messages.

Classes in org.openflow.protocol used by net.floodlightcontroller.routing

OFMatch

          Represents an ofp_match structure

OFMessage

          The base class for all OpenFlow protocol messages.

OFPacketIn

          Represents an ofp_packet_in

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.staticflowentry

OFFlowMod

          Represents an ofp_flow_mod message

OFFlowRemoved

          Represents an ofp_flow_removed message

OFMessage

          The base class for all OpenFlow protocol messages.

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.staticflowentry.web

OFFlowMod

          Represents an ofp_flow_mod message

Classes in org.openflow.protocol used by net.floodlightcontroller.test

OFMessage

          The base class for all OpenFlow protocol messages.

Classes in org.openflow.protocol used by net.floodlightcontroller.topology

OFMessage

          The base class for all OpenFlow protocol messages.

OFPacketIn

          Represents an ofp_packet_in

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.util

OFEchoRequest

          Represents an ofp_echo_request message

OFFeaturesReply

          Represents a features reply message

OFHello

          Represents an ofp_hello message

OFMessage

          The base class for all OpenFlow protocol messages.

OFPhysicalPort

          Represents ofp_phy_port

OFStatisticsRequest

          Represents an ofp_stats_request message

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by net.floodlightcontroller.virtualnetwork

OFMessage

          The base class for all OpenFlow protocol messages.

OFPacketIn

          Represents an ofp_packet_in

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by org.openflow.protocol

Instantiable

OFEchoRequest

          Represents an ofp_echo_request message

OFError.OFBadActionCode

OFError.OFBadRequestCode

OFError.OFErrorType

OFError.OFFlowModFailedCode

OFError.OFHelloFailedCode

OFError.OFPortModFailedCode

OFError.OFQueueOpFailedCode

OFFeaturesReply.OFCapabilities

          Corresponds to bits on the capabilities field

OFFlowMod

          Represents an ofp_flow_mod message

OFFlowRemoved.OFFlowRemovedReason

OFMatch

          Represents an ofp_match structure

OFMatchWithSwDpid

OFMessage

          The base class for all OpenFlow protocol messages.

OFPacketIn

          Represents an ofp_packet_in

OFPacketIn.OFPacketInReason

OFPacketOut

          Represents an ofp_packet_out message

OFPacketQueue

          Represents ofp_packet_queue

OFPhysicalPort

          Represents ofp_phy_port

OFPhysicalPort.OFPortConfig

OFPhysicalPort.OFPortFeatures

OFPhysicalPort.OFPortState

OFPort

OFPortStatus.OFPortReason

OFQueueProp

OFQueueProp.OFQueuePropType

OFStatisticsMessageBase

          Base class for statistics requests/replies

OFStatisticsReply.OFStatisticsReplyFlags

OFSwitchConfig

          Base class representing ofp_switch_config based messages

OFSwitchConfig.OFConfigFlags

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

OFVendor

          Represents ofp_vendor_header

OFVendorTest.AcmeVendorData

Wildcards

          a more user friendly representation of the wildcards bits in an OpenFlow
 match.

Wildcards.Flag

          enum type for the binary flags that can be set in the wildcards field of
 an OFMatch.

Classes in org.openflow.protocol used by org.openflow.protocol.action

Instantiable

Classes in org.openflow.protocol used by org.openflow.protocol.factory

OFMessage

          The base class for all OpenFlow protocol messages.

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by org.openflow.protocol.serializers

OFFeaturesReply

          Represents a features reply message

OFMatch

          Represents an ofp_match structure

Classes in org.openflow.protocol used by org.openflow.protocol.statistics

Instantiable

OFMatch

          Represents an ofp_match structure

OFType

          List of OpenFlow types and mappings to wire protocol value and derived
 classes

Classes in org.openflow.protocol used by org.openflow.protocol.vendor

Instantiable

Classes in org.openflow.protocol used by org.openflow.vendor.nicira

Instantiable

Classes in org.openflow.protocol used by org.openflow.vendor.openflow

Instantiable

OFPacketQueue

          Represents ofp_packet_queue

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
import db from '../models';
import Helpers from '../helpers';

export default {
    fetchAll(request, response) {
        const requestQuery = Helpers.createQueryForList(request);
        let condition = {};
        let pagination;
        db.Question
        .findAndCountAll(requestQuery)
        .then((question) => {
          if (question.length === 0) {
            return response.status(404).send({
              message: 'No Question was Not Found',
            });
          }
          condition = {
            count: question.count,
            limit: requestQuery.limit,
            offset: requestQuery.offset
          };
          delete question.count;
          pagination = Helpers.pagination(condition);
          return response.status(200)
          .send({
            question,
            pagination,
            message: 'questions was retrieved successfully'
          });
        })
        .catch(error => response.status(400).send({
          error,
          message: 'Error occurred while retrieving questions'
        }));
    },
    create(request, response) {
        request.body.authorId = request.decoded.user.id
        db.Question.create(request.body)
         .then((question) => {
            response.status(200)
            .send({
              success: true,
              question,
              message: 'Your question was created successfully'
            });
         })
         .catch((error) => response.status(400).send({
            error,
            message: 'Error occurred while saving data'
          }));
    },
    fetchOne(request, response) {
        const { id } = request.params
        if (isNaN(id)) {
            return response.status(400).send({
              message: 'Question should be an integer'
            });
          }
        db.Question.findOne({
          where: {
            id
          },
          include: [{
            model: db.User,
            attributes: [
              'id',
              'username',
              'fullname',
              'email',
              'points'
            ]
          }]
        })
        .then((question) => {
            if (!question) {
                return response.status(404)
                .send(
                  {
                    success: false,
                    message: 'Question Not found'
                  }
                );
              }
              question.getAnswers()
              .then((answer) => {
                const allAnswers = answer;
                return response.status(200)
                .send(
                  {
                    question,
                    allAnswers
                  });
              });
        })
        .catch((error) => response.status(400).send({
            error,
            message: 'Error occurred while retrieving documents'
          }))
    },
    delete(request, response) {
        const { id } = request.params;
        db.Question.findById(id)
        .then((question) => {
            if(!question) {
                return response.status(404).send({
                    message: 'Question not found'
                  });
            }
            if(request.decoded.user.id !== question.authorId) {
                return response.status(403).send({
                    message: 'You are not allow to delete this document'
                  });
            }
            question.destroy(
                {
                  where: {
                    id
                  }
                })
                .then(() => response.status(200)
                .send(
                {
                  message: 'Question was deleted successfully'
                }
                ));
        })
        .catch((error) => response.status(400).send({
            error,
            message: 'Error occurred while deleting documents'
          }))
    },
    edit(request, response) {
        const { id } = request.params;
        db.Question.findById(id)
        .then((question) => {
            if(!question) {
                return response.status(404).send({
                    message: 'Question not found'
                  });
            }
            if(request.decoded.user.id !== question.authorId) {
                return response.status(403).send({
                    message: 'You are not allow to delete this document'
                  });
            }
            question.update(request.body)
                .then(() => response.status(200)
                .send(
                {
                  message: 'Question was updated successfully'
                }
                ));
        })
        .catch((error) => response.status(400).send({
            error,
            message: 'Error occurred while deleting documents'
          }))
    },
    /**
    * Search document
    * Route: GET: /searchs?query={}
    * @param {Object} req request object
    * @param {Object} res response object
    */
  search(req, res) {
    req.searchFilter.attributes = [
      'id',
      'title',
      'body',
      'answerId',
      'authorId',
      'createdAt',
      'updatedAt'
    ];
    db.Question
      .findAndCountAll(req.searchFilter)
      .then((questions) => {
        const condition = {
          count: questions.count,
          limit: req.searchFilter.limit,
          offset: req.searchFilter.offset
        };
        delete questions.count;
        const pagination = Helpers.pagination(condition);
        let message;
        if (questions.rows.length === 0) {
          message = 'Document not Found';
        } else {
          message = 'Your search was successful';
        }
        res.status(200)
          .send({
            message,
            questions,
            pagination
          });
      });
  },
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="A front-end template that helps you build fast, modern mobile web apps.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <title>Display Recipes - RecipeFinder</title>

    <meta name="mobile-web-app-capable" content="yes">
    <link rel="icon" sizes="192x192" href="img/android-desktop.png">

    <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="Material Design Lite">
    <link rel="apple-touch-icon-precomposed" href="img/ios-desktop.png">

    <meta name="msapplication-TileImage" content="img/touch/ms-touch-icon-144x144-precomposed.png">
    <meta name="msapplication-TileColor" content="#3372DF">

    <link rel="shortcut icon" href="img/favicon.ico">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.light_green-orange.min.css" />
    <link rel="stylesheet" href="css/styles.css">

          Saved Recipes

            hello@example.com

            <button id="accbtn" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon">
              arrow_drop_down
              Accounts
            </button>

hello@example.com

info@example.com

addAdd another account...

          account_circleUser Profile
          restaurant_menuRecipes
          bookSaved Recipes
          assignment7 Day Planner
          assessmentHealth Tracker
          groupGroup Meal Planner
          help_outlineHelp & Support

          cancelLog Out
            <dialog class="mdl-dialog">

Are you sure you want to log out?

                <button type="button" class="mdl-button mdl-button--accent" onclick="dialog.close()">No</button>
                <button type="button" class="mdl-button close">Yes</button>

            </dialog>

          <form action="#">

              <input class="mdl-textfield__input" type="text" id="sample3">
              Type Name of Recipe

           sort_by_alpha
           sort
          </form>

                  Sweet and Sour Pork

                clear

                  Chicken Breast

                clear

                  Baklava

                  clear

                  Spicy Chicken Strips

                  clear

                  Thai Noodle Soup

                  clear

                  Lasagna

                  clear

      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" style="position: fixed; left: -1000px; height: -1000px;">
        <defs>
          <mask id="piemask" maskContentUnits="objectBoundingBox">
            <circle cx=0.5 cy=0.5 r=0.49 fill="white" />
            <circle cx=0.5 cy=0.5 r=0.40 fill="black" />
          </mask>
          <g id="piechart">
            <circle cx=0.5 cy=0.5 r=0.5 />
            <path d="M 0.5 0.5 0.5 0 A 0.5 0.5 0 0 1 0.95 0.28 z" stroke="none" fill="rgba(255, 255, 255, 0.75)" />
          </g>
        </defs>
      </svg>
      <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 500 250" style="position: fixed; left: -1000px; height: -1000px;">
        <defs>
          <g id="chart">
            <g id="Gridlines">
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="27.3" x2="468.3" y2="27.3" />
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="66.7" x2="468.3" y2="66.7" />
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="105.3" x2="468.3" y2="105.3" />
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="144.7" x2="468.3" y2="144.7" />
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="184.3" x2="468.3" y2="184.3" />
            </g>
            <g id="Numbers">
              <text transform="matrix(1 0 0 1 485 29.3333)" fill="#888888" font-family="'Roboto'" font-size="9">500</text>
              <text transform="matrix(1 0 0 1 485 69)" fill="#888888" font-family="'Roboto'" font-size="9">400</text>
              <text transform="matrix(1 0 0 1 485 109.3333)" fill="#888888" font-family="'Roboto'" font-size="9">300</text>
              <text transform="matrix(1 0 0 1 485 149)" fill="#888888" font-family="'Roboto'" font-size="9">200</text>
              <text transform="matrix(1 0 0 1 485 188.3333)" fill="#888888" font-family="'Roboto'" font-size="9">100</text>
              <text transform="matrix(1 0 0 1 0 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">1</text>
              <text transform="matrix(1 0 0 1 78 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">2</text>
              <text transform="matrix(1 0 0 1 154.6667 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">3</text>
              <text transform="matrix(1 0 0 1 232.1667 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">4</text>
              <text transform="matrix(1 0 0 1 309 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">5</text>
              <text transform="matrix(1 0 0 1 386.6667 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">6</text>
              <text transform="matrix(1 0 0 1 464.3333 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">7</text>
            </g>
            <g id="Layer_5">
              <polygon opacity="0.36" stroke-miterlimit="10" points="0,223.3 48,138.5 154.7,169 211,88.5
              294.5,80.5 380,165.2 437,75.5 469.5,223.3 	"/>
            </g>
            <g id="Layer_4">
              <polygon stroke-miterlimit="10" points="469.3,222.7 1,222.7 48.7,166.7 155.7,188.3 212,132.7
              296.7,128 380.7,184.3 436.7,125 	"/>
            </g>
          </g>
        </defs>
      </svg>


text:
<ion-view>
    <ion-pane>

        <ion-header-bar class="bar-stable">

                <button class="button button-icon button-withtext ion-chevron-left" ui-sref="cache">Back</button>

Cache Storage

        </ion-header-bar>

        <ion-content class="padded center">

                This shows how much storage space is used by the offline map cache.

                {{ viewdata.cachemegs }} MB

                {{ viewdata.cachetiles }} files

            <button class="button button-full button-assertive" ng-click="emptyCache()">Clear Cache</button>
        </ion-content>

    </ion-pane>
</ion-view>


text:
class CreateBudgets < ActiveRecord::Migration
  def change
    create_table :budgets do |t|
      t.string :name

      t.timestamps
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Coniothyrium ginkgoina Schwarzman

### Remarks
null


text:
@echo off >NUL 2>NUL

SET VS_VERSION=12.0
SET VERBOSITY=FALSE

echo Setting up environment variables
echo ================================================================

SET UTILS_ROOT=%CD%

SET VS_NAME=VSPATH

VisualStudioIdentifier %VS_VERSION% %VS_NAME% vs.bat"
call vs.bat
if "%VERBOSITY%"=="TRUE" (
    del /q vs.bat
) ELSE (
    del /q vs.bat >NUL 2>NUL
)
Cd ..
SET CURRENT_DIR=%CD%
SET SOLUTION_DIR=%CD%
SET NUGET_DIR=%CURRENT_DIR%\.nuget

cd %VSPATH%
cd..
SET VSPATH=%CD%
CD %CURRENT_DIR%

call "%VSPATH%\Tools\VsDevCmd.bat"

echo @echo off ^>NUL 2^>NUL > %UTILS_ROOT%\cleanup.bat

REM mkdir tmp_nuget
CD %UTILS_ROOT%
echo.


text:
({
    //详见https://github.com/jrburke/r.js/blob/master/build/example.build.js
    appDir: "./static",
    baseUrl: "js",
    dir: "./build/static/",
    optimize: "uglify2",
    generateSourceMaps:true,
     removeCombined:true,
     preserveLicenseComments:false,
     keepBuildDir:false,
     skipDirOptimize:true,
     optimizeCss:'standard',
     fileExclusionRegExp:/less/,
    modules: [
        {
            name: "main"
        }
    ]
})


text:
<?php
namespace Elastification\Client\Tests\Integration\Request\V1x\Cat;

use Elastification\Client\Request\V1x\Cat\PendingTasksCatRequest;
use Elastification\Client\Response\Response;
use Elastification\Client\Tests\Integration\Repository\V1x\AbstractElastic;

class PendingTasksCatRequestTest extends AbstractElastic
{
    public function testHealthCat()
    {
        $countCatRequest = new PendingTasksCatRequest(null, null, $this->getSerializer());
        /** @var Response $response */
        $response = $this->getClient()->send($countCatRequest);

        $data = $response->getData()->getGatewayValue();

        $this->assertTrue(is_array($data));
    }

}


text:
import styled from '@emotion/styled';
import { space, SpaceProps } from 'styled-system';

type ISpacerProps = SpaceProps;

const Spacer = styled.div<ISpacerProps>`
  ${space}
`;

/** @component */
export default Spacer;


text:
@interface ChicagoCheesePizza : Pizza

@end


text:
ConfigurePidState::ConfigurePidState(Adafruit_PCD8544* display, PID* pid) : display(display), pid(pid), renderer(display) {}

int ConfigurePidState::step(float dt) {
  display->clearDisplay();

  display->setTextColor(BLACK);

  String pText = "P: ";
  String iText = "I: ";
  String dText = "D: ";

  int valueWidth = 7;
  int valuePrecision = 4;
  char pValue[10], iValue[10], dValue[10];

  dtostrf(pid->profile.p, valueWidth, valuePrecision, pValue);
  dtostrf(pid->profile.i, valueWidth, valuePrecision, iValue);
  dtostrf(pid->profile.d, valueWidth, valuePrecision, dValue);

  renderer.renderTextRow("Configuration", 0, 0, WHITE);
  renderer.renderTextRow(pText + pValue, 0, 0, BLACK, 11, 13);
  renderer.renderTextRow(iText + iValue, 1, 0, BLACK, 11, 13);
  renderer.renderTextRow(dText + dValue, 2, 0, BLACK, 11, 13);

  display->display();

  return popLastIntent();
}

void ConfigurePidState::onKeyPress(int btn, unsigned long duration, boolean repeated) {
  setIntent(INTENT_MAIN_MENU);
}