hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
1089c94399fc002f6dc3e710abf4d37c60dfa06a | 489 | package br.unicamp.ic.mc302.dataHora;
public class Data {
private int dia;
private int mes;
private int ano;
public Data(int dia, int mes, int ano) {
this.dia = dia;
this.mes = mes;
this.ano = ano;
}
public int dia(){
return dia;
}
public int mes(){
return mes;
}
public int ano(){
return ano;
}
public int diferenca(Data d){
return 365*ano+31*mes+dia-(365*d.ano+31*d.mes+d.dia);
}
public String toString(){
return dia+"/"+mes+"/"+ano;
}
}
| 13.216216 | 55 | 0.615542 |
9739787908174ab24a55d8cd7eeb8ce165c9b4c7 | 23,869 | package com.quinn.framework.activiti.component;
import com.quinn.framework.activiti.model.CustomProcessDiagramGenerator;
import com.quinn.framework.activiti.util.ImageUtil;
import com.quinn.framework.api.*;
import com.quinn.framework.util.SessionUtil;
import com.quinn.framework.util.enums.*;
import com.quinn.util.base.CollectionUtil;
import com.quinn.util.base.StreamUtil;
import com.quinn.util.base.StringUtil;
import com.quinn.util.base.api.FileAdapter;
import com.quinn.util.constant.enums.CommonMessageEnum;
import com.quinn.util.base.exception.BaseBusinessException;
import com.quinn.util.base.exception.file.FileFormatException;
import com.quinn.util.base.model.BaseResult;
import com.quinn.util.base.model.StringKeyValue;
import com.quinn.util.constant.CharConstant;
import com.quinn.util.constant.NumberConstant;
import com.quinn.util.constant.StringConstant;
import lombok.SneakyThrows;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.*;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.ProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
/**
* 流程模板工具类
*
* @author Simon.z
* @since 2020/5/29
*/
public final class ActivitiInfoFiller implements BpmInfoFiller {
private static final String ACTIVITY_NAMESPACE = "http://activiti.org/bpmn";
private static final String ACTIVITY_NAMESPACE_PREFIX = "activiti";
private static final String SERVICE_TASK_EXPRESSION_ATTR_NAME = "delegateExpression";
private static final String TASK_ATTR_NAME_COUNTERSIGN_COLLECTION = "collection";
private static final String TASK_EXPRESSION_COUNTERSIGN_USERS = "countersignUsers";
private static final String TASK_EXPRESSION_COUNTERSIGN_ELEMENT = "countersignAssignee";
private static final String TASK_EXPRESSION_COUNTERSIGN_TASK_ASSIGNEE = "${" + TASK_EXPRESSION_COUNTERSIGN_ELEMENT + "}";
private static final String SERVICE_TASK_EXPRESSION_ATTR_VALUE = "${serviceTaskDelegate}";
@Value("${com.ming-cloud.bpm.diagram.font-name.activity:宋体}")
private String activityFontName;
@Value("${com.ming-cloud.bpm.diagram.font-name.label:宋体}")
private String labelFontName;
@Value("${com.ming-cloud.bpm.diagram.font-name.annotation:宋体}")
private String annotationFontName;
@Value("${com.ming-cloud.bpm.diagram.image.type:png}")
private String imageType;
@Value("${com.ming-cloud.bpm.diagram.color.active:-7667712}")
private int activeColor;
@Value("${com.ming-cloud.bpm.diagram.color.history:-12799119}")
private int historyColor;
@Resource
private RepositoryService repositoryService;
@Resource
private RuntimeService runtimeService;
@Resource
private HistoryService historyService;
@Resource
private TaskService taskService;
@Resource
private BpmModelSupplier modelSupplier;
@Resource
private BpmInstHelpService bpmInstHelpService;
@Override
public void generateModelInfo(FileAdapter adapter, BpmModelInfo modelInfo) {
// 解析获取BpmModel
String designContent = StringUtil.forBytes(adapter.getBytes());
try {
// STEP1:创建转换对象
BpmnXMLConverter converter = new BpmnXMLConverter();
// STEP2:读取xml文件
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(adapter.getInputStream());
// STEP3:将xml文件转换成BpmModel
BpmnModel bpmnModel = converter.convertToBpmnModel(streamReader);
Process mainProcess = bpmnModel.getMainProcess();
String modelKey = mainProcess.getId();
String modelName = mainProcess.getName();
if (StringUtil.isEmpty(modelName)) {
modelName = modelKey;
}
modelInfo.setModelKey(modelKey);
modelInfo.setModelName(modelName);
modelInfo.setDesignContent(designContent);
} catch (XMLStreamException e) {
throw new FileFormatException()
.addParam(CommonMessageEnum.FILE_FORMAT_NOT_CORRECT.paramNames[0], "xml")
.exception();
}
}
@Override
public void deployModel(BpmModelInfo data) {
// 使用输入流部署流程定义
String fileName = data.fileName();
Deployment deployment = repositoryService.createDeployment()
.addInputStream(fileName, StreamUtil.asStream(data.getDesignContent()))
.name(data.getModelName())
.key(data.getModelKey())
.deploy();
// 根据deploymentId查询单个流程实例
String deploymentId = deployment.getId();
ProcessDefinition processDefinition = repositoryService
.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
data.setBpmDeployKey(deploymentId);
data.setBpmKey(processDefinition.getId());
data.setBpmVersion(processDefinition.getVersion());
}
@Override
public void downloadModelPng(HttpServletResponse response, String bpmKey) {
// 获取Bpm Model
InputStream inputStream;
BpmnModel model = repositoryService.getBpmnModel(bpmKey);
if (model == null || model.getLocationMap().size() == 0) {
throw new BaseBusinessException();
}
ProcessDiagramGenerator generator = new CustomProcessDiagramGenerator(activeColor, historyColor);
// 生成流程图 都不高亮
inputStream = generator.generateDiagram(model, activityFontName, labelFontName, annotationFontName);
showBpmImage(response, bpmKey, inputStream);
}
/**
* 显示图片
*
* @param response 响应体
* @param bpmKey BPM编码
* @param inputStream 数据流
*/
private void showBpmImage(HttpServletResponse response, String bpmKey, InputStream inputStream) {
response.setContentType("application/octet-stream; charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + bpmKey + CharConstant.DOT + imageType);
try {
ImageUtil.convertSvg2Png(inputStream, response.getOutputStream());
} catch (IOException e) {
throw new BaseBusinessException();
} finally {
StreamUtil.closeQuietly(inputStream);
}
}
@Override
@SneakyThrows
public void resolveNodeInfo(BpmModelInfo data, BpmNodeRelateBO relateInfo) {
// 获取bpmn2.0规范的xml
InputStream bpmnStream = new ByteArrayInputStream(data.getDesignContent().getBytes());
XMLInputFactory xif = XMLInputFactory.newInstance();
InputStreamReader in = new InputStreamReader(bpmnStream, StringConstant.SYSTEM_DEFAULT_CHARSET);
XMLStreamReader xtr = xif.createXMLStreamReader(in);
// 然后转为bpmnModel
BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);
bpmnModel.addNamespace(ACTIVITY_NAMESPACE_PREFIX, ACTIVITY_NAMESPACE);
Process mainProcess = bpmnModel.getMainProcess();
mainProcess.setExecutable(true);
mainProcess.setId(data.getModelKey());
Collection<FlowElement> elements = mainProcess.getFlowElements();
Long modelId = data.getId();
String modelKey = data.getModelKey();
Integer modelVersion = data.getModelVersion();
for (FlowElement element : elements) {
if (element instanceof SequenceFlow) {
SequenceFlow sequence = (SequenceFlow) element;
BpmNodeRelateInfo relate = generateNodeRelate(sequence);
relate.setModelId(modelId);
relate.setModelKey(modelKey);
relate.setModelVersion(modelVersion);
relateInfo.addRelate(relate);
} else {
BpmNodeInfo nodeInfo = generateNodeInfo(element);
nodeInfo.setModelId(modelId);
nodeInfo.setModelKey(modelKey);
nodeInfo.setModelVersion(modelVersion);
nodeInfo.initForSeq();
relateInfo.addNode(nodeInfo);
if (element instanceof StartEvent) {
relateInfo.setStartNode(nodeInfo);
}
if (element instanceof Task) {
Task task = (Task) element;
if (element instanceof ServiceTask) {
ServiceTask serviceTask = (ServiceTask) element;
serviceTask.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_EXPRESSION);
serviceTask.setImplementation(SERVICE_TASK_EXPRESSION_ATTR_VALUE);
}
MultiInstanceLoopCharacteristics loopCharacteristics = task.getLoopCharacteristics();
if (loopCharacteristics != null) {
String inputDataItem = loopCharacteristics.getInputDataItem();
if (StringUtil.isEmpty(inputDataItem)) {
loopCharacteristics.setInputDataItem(TASK_EXPRESSION_COUNTERSIGN_USERS);
}
String completionCondition = loopCharacteristics.getCompletionCondition();
if (StringUtil.isEmpty(completionCondition)) {
loopCharacteristics.setCompletionCondition("${nrOfCompletedInstances/nrOfInstances >= 0.99 }");
}
String elementVariable = loopCharacteristics.getElementVariable();
if (StringUtil.isEmpty(elementVariable)) {
loopCharacteristics.setElementVariable(TASK_EXPRESSION_COUNTERSIGN_ELEMENT);
if (task instanceof UserTask) {
UserTask userTask = (UserTask) task;
String assignee = userTask.getAssignee();
if (StringUtil.isEmpty(assignee)) {
userTask.setAssignee(TASK_EXPRESSION_COUNTERSIGN_TASK_ASSIGNEE);
}
}
}
}
}
}
}
BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
data.setDesignContent(StringUtil.forBytes(
xmlConverter.convertToXML(bpmnModel, StringConstant.SYSTEM_DEFAULT_CHARSET)));
}
@Override
public BaseResult start(BpmInstInfo bpmInstInfo, Map<String, Object> param) {
Authentication.setAuthenticatedUserId(bpmInstInfo.getStartUser());
ProcessInstance processInstance = runtimeService.createProcessInstanceBuilder()
.processDefinitionId(bpmInstInfo.getBpmModelKey())
.businessKey(bpmInstInfo.getId() + "")
.tenantId(SessionUtil.getOrgKey())
.processDefinitionKey(bpmInstInfo.getModelKey())
.name(bpmInstInfo.getSubject())
.variables(param)
.start();
// 信心流程状态-关联BPM和Act (数据库的关联动作交给监听机制)
String processInstanceId = processInstance.getProcessInstanceId();
bpmInstInfo.setInstStatus(BpmInstStatusEnum.RUNNING.name());
bpmInstInfo.setBpmKey(processInstanceId);
return BaseResult.SUCCESS;
}
@Override
public void addCandidates(String taskBpmId, Set<String> userCandidates, Set<String> roleCandidates) {
if (!CollectionUtil.isEmpty(userCandidates)) {
if (userCandidates.size() == NumberConstant.INT_ONE && CollectionUtil.isEmpty(roleCandidates)) {
taskService.setAssignee(taskBpmId, userCandidates.iterator().next());
} else {
for (String candidate : userCandidates) {
taskService.addCandidateUser(taskBpmId, candidate);
}
}
}
if (!CollectionUtil.isEmpty(roleCandidates)) {
for (String candidate : roleCandidates) {
taskService.addCandidateGroup(taskBpmId, candidate);
}
}
}
@Override
public void complete(String taskBpmId, Map<String, Object> param) {
taskService.complete(taskBpmId, param);
}
@Override
public void setAssignee(String taskBpmId, String assignee) {
taskService.setAssignee(taskBpmId, assignee);
}
@Override
public void deleteProcessInstance(String bpmKey, String suggestion) {
runtimeService.deleteProcessInstance(bpmKey, suggestion);
}
@Override
@SneakyThrows
public BaseResult validate(String designContent) {
if (StringUtil.isEmptyInFrame(designContent)) {
return BaseResult.fail()
.buildMessage(CommonMessageEnum.PARAM_SHOULD_NOT_NULL.name(), 1, 0)
.addParam(CommonMessageEnum.PARAM_SHOULD_NOT_NULL.paramNames[0], "designContent")
.result();
}
BpmnXMLConverter converter = new BpmnXMLConverter();
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
XMLStreamReader streamReader = inputFactory.createXMLStreamReader(StreamUtil.asStream(designContent));
BpmnModel bpmnModel = converter.convertToBpmnModel(streamReader);
return BaseResult.success(bpmnModel);
}
@Override
public String downloadModelXml(String bpmKey) {
if (StringUtil.isEmptyInFrame(bpmKey)) {
return StringConstant.STRING_EMPTY;
}
BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmKey);
if (bpmnModel == null) {
return StringConstant.STRING_EMPTY;
}
BpmnXMLConverter converter = new BpmnXMLConverter();
return StringUtil.forBytes(converter.convertToXML(bpmnModel, StringConstant.SYSTEM_DEFAULT_CHARSET));
}
@Override
public BaseResult actBack(BpmTaskInfo taskInfo, String backNodeCode) {
// 取得所有历史任务按时间降序排序
List<HistoricTaskInstance> htiList = historyService.createHistoricTaskInstanceQuery()
.processInstanceId(taskInfo.getBpmInstKey())
.orderByTaskCreateTime()
.desc()
.list();
if (ObjectUtils.isEmpty(htiList) || htiList.size() < NumberConstant.INT_TWO) {
throw new BaseBusinessException()
.buildParam(BpmMessageEnum.INSTANCE_DATA_LOST.key(), 1, 1)
.addParam(BpmMessageEnum.INSTANCE_DATA_LOST.params[0], taskInfo.getInstanceId())
.addParamI8n(BpmMessageEnum.INSTANCE_DATA_LOST.params[1], BpmInstanceDataTypeEnum.TaskInfoVO.key())
.exception();
}
HistoricTaskInstance lastActNode = null;
for (HistoricTaskInstance historicTaskInstance : htiList) {
if (historicTaskInstance.getTaskDefinitionKey().equals(backNodeCode)) {
lastActNode = historicTaskInstance;
break;
}
}
if (lastActNode == null) {
throw new BaseBusinessException()
.buildParam(BpmMessageEnum.NODE_HISTORY_TASK_NOT_EXISTS.key(), 1, 0)
.addParam(BpmMessageEnum.NODE_HISTORY_TASK_NOT_EXISTS.params[0], backNodeCode)
.exception();
}
BpmnModel bpmnModel = repositoryService.getBpmnModel(taskInfo.getBpmModelKey());
FlowNode lastFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(backNodeCode);
FlowNode curFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(taskInfo.getNodeCode());
//记录当前节点的原活动方向
List<SequenceFlow> oriSequenceFlows = new ArrayList<>();
oriSequenceFlows.addAll(curFlowNode.getOutgoingFlows());
//清理活动方向
curFlowNode.getOutgoingFlows().clear();
//建立新方向
List<SequenceFlow> newSequenceFlowList = new ArrayList<>();
curFlowNode.setOutgoingFlows(newSequenceFlowList);
SequenceFlow newSequenceFlow = new SequenceFlow();
newSequenceFlowList.add(newSequenceFlow);
newSequenceFlow.setId("newSequenceFlowId");
newSequenceFlow.setSourceFlowElement(curFlowNode);
newSequenceFlow.setTargetFlowElement(lastFlowNode);
// 完成任务
taskService.complete(taskInfo.getBpmKey());
//恢复原方向
curFlowNode.setOutgoingFlows(oriSequenceFlows);
return BaseResult.SUCCESS;
}
@Override
public void downloadInstPng(HttpServletResponse response, String bpmKey) {
// 获取历史流程实例
HistoricProcessInstance historicProcessInstance = historyService
.createHistoricProcessInstanceQuery()
.processInstanceId(bpmKey)
.singleResult();
// 获取bpmnModel
String definitionId = historicProcessInstance.getProcessDefinitionId();
BpmnModel bpmnModel = repositoryService.getBpmnModel(definitionId);
// 使用默认的程序图片生成器
ProcessDiagramGenerator generator = new CustomProcessDiagramGenerator(activeColor, historyColor);
List<String> highLightedActivityIds = new ArrayList<>();
List<String> highLightedFlowIds = new ArrayList<>();
BaseResult<List<StringKeyValue>> historyRes = bpmInstHelpService.selectActiveNodeCodeAndFlows(bpmKey);
if (historyRes.isSuccess()) {
for (StringKeyValue kv : historyRes.getData()) {
highLightedActivityIds.add(kv.getDataKey());
if (!StringUtil.isEmptyInFrame(kv.getDataValue())) {
highLightedFlowIds.add(kv.getDataValue());
}
}
}
InputStream inputStream = generator.generateDiagram(bpmnModel, highLightedActivityIds, highLightedFlowIds,
activityFontName, labelFontName, annotationFontName);
showBpmImage(response, definitionId, inputStream);
}
/**
* 获取高亮线
*
* @param bpmModel 流程模型
* @param historicInstanceList 历史节点
* @return 高亮节点
*/
private List<String> getHighLightedFlows(BpmnModel bpmModel, List<HistoricActivityInstance> historicInstanceList) {
// 流转线ID集合
List<String> flowIdList = new ArrayList<>();
// 全部活动实例
List<FlowNode> historicFlowNodeList = new LinkedList<>();
// 已完成的历史活动节点
List<HistoricActivityInstance> finishedActivityInstanceList = new LinkedList<>();
for (HistoricActivityInstance historicInstance : historicInstanceList) {
historicFlowNodeList.add((FlowNode) bpmModel.getMainProcess()
.getFlowElement(historicInstance.getActivityId(), true));
if (historicInstance.getEndTime() != null) {
finishedActivityInstanceList.add(historicInstance);
}
}
// 遍历已完成的活动实例,从每个实例的outgoingFlows中找到已执行的
FlowNode currentFlowNode = null;
for (HistoricActivityInstance currentActivityInstance : finishedActivityInstanceList) {
// 获得当前活动对应的节点信息及outgoingFlows信息
currentFlowNode = (FlowNode) bpmModel.getMainProcess().getFlowElement(currentActivityInstance.getActivityId(), true);
List<SequenceFlow> sequenceFlowList = currentFlowNode.getOutgoingFlows();
/**
* 遍历outgoingFlows并找到已流转的
* 满足如下条件认为已流转:
* 1.当前节点是并行网关或包含网关,则通过outgoingFlows能够在历史活动中找到的全部节点均为已流转
* 2.当前节点是以上两种类型之外的,通过outgoingFlows查找到的时间最近的流转节点视为有效流转
*/
FlowNode targetFlowNode = null;
if (NodeTypeEnum.parallelGateway.toString().equals(currentActivityInstance.getActivityType())
|| NodeTypeEnum.inclusiveGateway.toString().equals(currentActivityInstance.getActivityType())) {
// 遍历历史活动节点,找到匹配Flow目标节点的
for (SequenceFlow sequenceFlow : sequenceFlowList) {
targetFlowNode = (FlowNode) bpmModel.getMainProcess()
.getFlowElement(sequenceFlow.getTargetRef(), true);
if (historicFlowNodeList.contains(targetFlowNode)) {
flowIdList.add(sequenceFlow.getId());
}
}
} else {
List<Map<String, String>> tempMapList = new LinkedList<>();
// 遍历历史活动节点,找到匹配Flow目标节点的
for (SequenceFlow sequenceFlow : sequenceFlowList) {
for (HistoricActivityInstance historicInstance : historicInstanceList) {
if (historicInstance.getActivityId().equals(sequenceFlow.getTargetRef())) {
tempMapList.add(CollectionUtil.toMap(
"flowId", sequenceFlow.getId(), "activityStartTime",
String.valueOf(historicInstance.getStartTime().getTime())));
}
}
}
// 遍历匹配的集合,取得开始时间最早的一个
long earliestStamp = 0L;
String flowId = null;
for (Map<String, String> map : tempMapList) {
long activityStartTime = Long.parseLong(map.get("activityStartTime"));
if (earliestStamp == 0 || earliestStamp >= activityStartTime) {
earliestStamp = activityStartTime;
flowId = map.get("flowId");
}
}
flowIdList.add(flowId);
}
}
return flowIdList;
}
/**
* 节点连线解析
*
* @param sequence 节点连线实体类
* @return map
*/
public BpmNodeRelateInfo generateNodeRelate(SequenceFlow sequence) {
BpmNodeRelateInfo relateInfo = modelSupplier.newBpmNodeRelateInfo();
relateInfo.setBpmKey(sequence.getId());
String leadNodeCode = sequence.getSourceRef();
String followNodeCode = sequence.getTargetRef();
FlowElement sourceElement = sequence.getSourceFlowElement();
relateInfo.setLeadNodeCode(leadNodeCode);
relateInfo.setFollowNodeCode(followNodeCode);
// 判断节点关系类型
if (sourceElement instanceof ExclusiveGateway) {
relateInfo.setRelateType(NodeRelateTypeEnum.CONDITION.name());
} else {
relateInfo.setRelateType(NodeRelateTypeEnum.AGREE.name());
}
return relateInfo;
}
/**
* 节点解析
*
* @param flowElement 流程节点实体类(非连线)
* @return map
*/
public BpmNodeInfo generateNodeInfo(FlowElement flowElement) {
BpmNodeInfo nodeInfo = modelSupplier.newBpmNodeInfo();
nodeInfo.setNodeType(StringUtil.firstCharUppercase(flowElement.getClass().getSimpleName()));
nodeInfo.setNodeCode(flowElement.getId());
String name = flowElement.getName();
nodeInfo.setNodeName(StringUtil.isEmpty(name) ? flowElement.getId() : name);
return nodeInfo;
}
}
| 40.871575 | 129 | 0.653065 |
7aec643468505fc29174ae5cd9322ebd92deb7d9 | 4,108 | package bitchat.android.com.bitstore.bean;
import com.android.base.net.AppConst;
import java.io.Serializable;
import java.util.List;
public class AppDetailBean implements Serializable {
private String _id;
private String account;
private String lang;
private String appname;
private String version;
private String appsize;
private int categary;
private String appicon;
private String source;
private String developer;
private String describe;
private String tag;
private String associate;
private String introduce;
private String downloadurl;
private long c_time;
private long u_time;
private int commentcount;
private int downcount;
private int recommendlevel;
private String id;
private List<?> release;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getAppname() {
return appname;
}
public void setAppname(String appname) {
this.appname = appname;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getAppsize() {
return appsize;
}
public void setAppsize(String appsize) {
this.appsize = appsize;
}
public int getCategary() {
return categary;
}
public void setCategary(int categary) {
this.categary = categary;
}
public String getAppicon() {
return AppConst.BASE_URL +appicon;
}
public void setAppicon(String appicon) {
this.appicon = appicon;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDeveloper() {
return developer;
}
public void setDeveloper(String developer) {
this.developer = developer;
}
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getAssociate() {
return associate;
}
public void setAssociate(String associate) {
this.associate = associate;
}
public String getIntroduce() {
return introduce;
}
public void setIntroduce(String introduce) {
this.introduce = introduce;
}
public String getDownloadurl() {
return AppConst.BASE_URL+downloadurl;
}
public void setDownloadurl(String downloadurl) {
this.downloadurl = downloadurl;
}
public long getC_time() {
return c_time;
}
public void setC_time(long c_time) {
this.c_time = c_time;
}
public long getU_time() {
return u_time;
}
public void setU_time(long u_time) {
this.u_time = u_time;
}
public int getCommentcount() {
return commentcount;
}
public void setCommentcount(int commentcount) {
this.commentcount = commentcount;
}
public int getDowncount() {
return downcount;
}
public void setDowncount(int downcount) {
this.downcount = downcount;
}
public int getRecommendlevel() {
return recommendlevel;
}
public void setRecommendlevel(int recommendlevel) {
this.recommendlevel = recommendlevel;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<?> getRelease() {
return release;
}
public void setRelease(List<?> release) {
this.release = release;
}
}
| 19.377358 | 55 | 0.611977 |
33ad89d2ee16003ed7324ef49f42ca9d248e534f | 2,174 | package com.autuan.project.front.controller;
import com.autuan.project.front.entity.GeneratorQrCodeVO;
import com.autuan.project.front.entity.ReceiveAO;
import com.autuan.project.front.entity.ReturnResult;
import com.autuan.project.promote.task.service.ITaskCustomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author : Autuan.Yu
* @description : 描述
* @remark : 备注
* @date : 2020/6/23 16:22
* @company : 上海奥若拉信息科技集团有限公司
*/
@RestController
@RequestMapping("/front/task")
public class TaskFrontController {
@Autowired
ITaskCustomService taskCustomService;
/***
* 获取二维码
* @param taskId
* @param response
* @throws Throwable
* @description:
* @author: sen.zhou
* @return : void
* @since: 19:32 2020/6/23
*/
@RequestMapping(value = "/qrcode/{taskId}/{salesmanId}",produces = MediaType.IMAGE_JPEG_VALUE)
// @ResponseBody
public void qrcode(@PathVariable("taskId") String taskId,
@PathVariable("salesmanId") String salesmanId,
HttpServletResponse response) throws IOException {
ServletOutputStream outputStream = response.getOutputStream();
// return taskCustomService.generatorQrcode(outputStream);
GeneratorQrCodeVO vo = GeneratorQrCodeVO.builder()
.salesmanId(salesmanId)
.taskId(taskId)
.build();
taskCustomService.generatorQrcode(vo,outputStream);
}
/***
* 领取任务
* @param
* @throws Throwable
* @description:
* @author: sen.zhou
* @return : com.autuan.project.front.entity.ReturnResult
* @since: 19:33 2020/6/28
*/
@PostMapping("/receive")
@ResponseBody
public ReturnResult receive(@RequestBody ReceiveAO ao){
taskCustomService.receive(ao);
return ReturnResult.ok();
}
}
| 30.194444 | 98 | 0.683993 |
137f544beeec02182b3e40fb231b5e15ae0f4755 | 210 | package org.jspare.core.helpers;
import org.jspare.core.Application;
public class DummyInvalidBoostrap extends Application {
private DummyInvalidBoostrap() {
}
@Override
public void start() {
}
}
| 15 | 55 | 0.742857 |
f63c8fd6f7ecc9ce1b5d1cdfe8dfa69607e9ebb9 | 572 | package com.development.backend.ng.springmvc.bean;
import java.util.List;
public class ResultBean {
private String Description;
private String text;
private String code;
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
| 15.459459 | 51 | 0.667832 |
e13542d6c5d916b9d20f196d1f1301986c44c848 | 1,025 | /*
* Created on Nov 9, 2007
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.ai.db.ps;
import com.ai.application.interfaces.RequestExecutionException;
import com.ai.application.utils.AppObjects;
import com.ai.data.DataException;
/**
* @author Satya
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class TypeConverterUtility
{
static ITypeConverter genericTypeConverter = null;
static
{
try
{
genericTypeConverter =
(ITypeConverter)
AppObjects.getObject("aspire.generictypeconverter",null);
}
catch(RequestExecutionException x)
{
throw new RuntimeException("Error:can not obtain generic type converter",x);
}
}
public static Object convert(Object srcObject, String hint)
throws DataException
{
return genericTypeConverter.convert(srcObject,hint);
}
}
| 24.404762 | 80 | 0.710244 |
dd0b07284e993b62dcfcae40401c234967f97bbd | 31,048 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.11.17 at 03:30:58 PM EET
//
package oasis.names.specification.ubl.schema.xsd.commonaggregatecomponents_2;
import oasis.names.specification.ubl.schema.xsd.commonbasiccomponents_2.*;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import java.util.ArrayList;
import java.util.List;
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>ABIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Details</ccts:DictionaryEntryName>
* <ccts:Definition>A class to describe a location.</ccts:Definition>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* </ccts:Component>
* </pre>
*
*
*
* <p>Java class for LocationType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="LocationType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2}ID" minOccurs="0"/>
* <element ref="{urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2}Description" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2}Conditions" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2}CountrySubentity" minOccurs="0"/>
* <element ref="{urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2}CountrySubentityCode" minOccurs="0"/>
* <element ref="{urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2}LocationTypeCode" minOccurs="0"/>
* <element ref="{urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2}InformationURI" minOccurs="0"/>
* <element ref="{urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2}Name" minOccurs="0"/>
* <element ref="{urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2}ValidityPeriod" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2}Address" minOccurs="0"/>
* <element ref="{urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2}SubsidiaryLocation" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2}LocationCoordinate" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LocationType", propOrder = {
"id",
"description",
"conditions",
"countrySubentity",
"countrySubentityCode",
"locationTypeCode",
"informationURI",
"name",
"validityPeriod",
"address",
"subsidiaryLocation",
"locationCoordinate"
})
public class LocationType {
@XmlElement(name = "ID", namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")
protected IDType id;
@XmlElement(name = "Description", namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")
protected List<DescriptionType> description;
@XmlElement(name = "Conditions", namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")
protected List<ConditionsType> conditions;
@XmlElement(name = "CountrySubentity", namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")
protected CountrySubentityType countrySubentity;
@XmlElement(name = "CountrySubentityCode", namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")
protected CountrySubentityCodeType countrySubentityCode;
@XmlElement(name = "LocationTypeCode", namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")
protected LocationTypeCodeType locationTypeCode;
@XmlElement(name = "InformationURI", namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")
protected InformationURIType informationURI;
@XmlElement(name = "Name", namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")
protected NameType name;
@XmlElement(name = "ValidityPeriod")
protected List<PeriodType> validityPeriod;
@XmlElement(name = "Address")
protected AddressType address;
@XmlElement(name = "SubsidiaryLocation")
protected List<LocationType> subsidiaryLocation;
@XmlElement(name = "LocationCoordinate")
protected List<LocationCoordinateType> locationCoordinate;
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>BBIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Identifier</ccts:DictionaryEntryName>
* <ccts:Definition>An identifier for this location, e.g., the EAN Location Number, GLN.</ccts:Definition>
* <ccts:Cardinality>0..1</ccts:Cardinality>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* <ccts:PropertyTerm>Identifier</ccts:PropertyTerm>
* <ccts:RepresentationTerm>Identifier</ccts:RepresentationTerm>
* <ccts:DataType>Identifier. Type</ccts:DataType>
* <ccts:Examples>5790002221134</ccts:Examples>
* </ccts:Component>
* </pre>
*
*
*
* @return
* possible object is
* {@link IDType }
*
*/
public IDType getID() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link IDType }
*
*/
public void setID(IDType value) {
this.id = value;
}
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>BBIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Description. Text</ccts:DictionaryEntryName>
* <ccts:Definition>Text describing this location.</ccts:Definition>
* <ccts:Cardinality>0..n</ccts:Cardinality>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* <ccts:PropertyTerm>Description</ccts:PropertyTerm>
* <ccts:RepresentationTerm>Text</ccts:RepresentationTerm>
* <ccts:DataType>Text. Type</ccts:DataType>
* </ccts:Component>
* </pre>
*
* Gets the value of the description property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the description property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDescription().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DescriptionType }
*
*
*/
public List<DescriptionType> getDescription() {
if (description == null) {
description = new ArrayList<DescriptionType>();
}
return this.description;
}
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>BBIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Conditions. Text</ccts:DictionaryEntryName>
* <ccts:Definition>Free-form text describing the physical conditions of the location.</ccts:Definition>
* <ccts:Cardinality>0..n</ccts:Cardinality>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* <ccts:PropertyTerm>Conditions</ccts:PropertyTerm>
* <ccts:RepresentationTerm>Text</ccts:RepresentationTerm>
* <ccts:DataType>Text. Type</ccts:DataType>
* </ccts:Component>
* </pre>
*
* Gets the value of the conditions property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the conditions property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getConditions().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ConditionsType }
*
*
*/
public List<ConditionsType> getConditions() {
if (conditions == null) {
conditions = new ArrayList<ConditionsType>();
}
return this.conditions;
}
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>BBIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Country Subentity. Text</ccts:DictionaryEntryName>
* <ccts:Definition>A territorial division of a country, such as a county or state, expressed as text.</ccts:Definition>
* <ccts:Cardinality>0..1</ccts:Cardinality>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* <ccts:PropertyTerm>Country Subentity</ccts:PropertyTerm>
* <ccts:RepresentationTerm>Text</ccts:RepresentationTerm>
* <ccts:DataType>Text. Type</ccts:DataType>
* <ccts:AlternativeBusinessTerms>AdministrativeArea, State, Country, Shire, Canton</ccts:AlternativeBusinessTerms>
* <ccts:Examples>Florida , Tamilnadu </ccts:Examples>
* </ccts:Component>
* </pre>
*
*
*
* @return
* possible object is
* {@link CountrySubentityType }
*
*/
public CountrySubentityType getCountrySubentity() {
return countrySubentity;
}
/**
* Sets the value of the countrySubentity property.
*
* @param value
* allowed object is
* {@link CountrySubentityType }
*
*/
public void setCountrySubentity(CountrySubentityType value) {
this.countrySubentity = value;
}
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>BBIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Country Subentity Code. Code</ccts:DictionaryEntryName>
* <ccts:Definition>A territorial division of a country, such as a county or state, expressed as a code.</ccts:Definition>
* <ccts:Cardinality>0..1</ccts:Cardinality>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* <ccts:PropertyTerm>Country Subentity Code</ccts:PropertyTerm>
* <ccts:RepresentationTerm>Code</ccts:RepresentationTerm>
* <ccts:DataType>Code. Type</ccts:DataType>
* <ccts:AlternativeBusinessTerms>AdministrativeAreaCode, State Code</ccts:AlternativeBusinessTerms>
* </ccts:Component>
* </pre>
*
*
*
* @return
* possible object is
* {@link CountrySubentityCodeType }
*
*/
public CountrySubentityCodeType getCountrySubentityCode() {
return countrySubentityCode;
}
/**
* Sets the value of the countrySubentityCode property.
*
* @param value
* allowed object is
* {@link CountrySubentityCodeType }
*
*/
public void setCountrySubentityCode(CountrySubentityCodeType value) {
this.countrySubentityCode = value;
}
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>BBIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Location Type Code. Code</ccts:DictionaryEntryName>
* <ccts:Definition>A code signifying the type of location.</ccts:Definition>
* <ccts:Cardinality>0..1</ccts:Cardinality>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* <ccts:PropertyTerm>Location Type Code</ccts:PropertyTerm>
* <ccts:RepresentationTerm>Code</ccts:RepresentationTerm>
* <ccts:DataType>Code. Type</ccts:DataType>
* </ccts:Component>
* </pre>
*
*
*
* @return
* possible object is
* {@link LocationTypeCodeType }
*
*/
public LocationTypeCodeType getLocationTypeCode() {
return locationTypeCode;
}
/**
* Sets the value of the locationTypeCode property.
*
* @param value
* allowed object is
* {@link LocationTypeCodeType }
*
*/
public void setLocationTypeCode(LocationTypeCodeType value) {
this.locationTypeCode = value;
}
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>BBIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Information_ URI. Identifier</ccts:DictionaryEntryName>
* <ccts:Definition>The Uniform Resource Identifier (URI) of a document providing information about this location.</ccts:Definition>
* <ccts:Cardinality>0..1</ccts:Cardinality>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* <ccts:PropertyTermQualifier>Information</ccts:PropertyTermQualifier>
* <ccts:PropertyTerm>URI</ccts:PropertyTerm>
* <ccts:RepresentationTerm>Identifier</ccts:RepresentationTerm>
* <ccts:DataType>Identifier. Type</ccts:DataType>
* </ccts:Component>
* </pre>
*
*
*
* @return
* possible object is
* {@link InformationURIType }
*
*/
public InformationURIType getInformationURI() {
return informationURI;
}
/**
* Sets the value of the informationURI property.
*
* @param value
* allowed object is
* {@link InformationURIType }
*
*/
public void setInformationURI(InformationURIType value) {
this.informationURI = value;
}
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>BBIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Name</ccts:DictionaryEntryName>
* <ccts:Definition>The name of this location.</ccts:Definition>
* <ccts:Cardinality>0..1</ccts:Cardinality>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* <ccts:PropertyTerm>Name</ccts:PropertyTerm>
* <ccts:RepresentationTerm>Name</ccts:RepresentationTerm>
* <ccts:DataType>Name. Type</ccts:DataType>
* <ccts:Examples>winter 2005 collection </ccts:Examples>
* </ccts:Component>
* </pre>
*
*
*
* @return
* possible object is
* {@link NameType }
*
*/
public NameType getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link NameType }
*
*/
public void setName(NameType value) {
this.name = value;
}
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>ASBIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Validity_ Period. Period</ccts:DictionaryEntryName>
* <ccts:Definition>A period during which this location can be used (e.g., for delivery).</ccts:Definition>
* <ccts:Cardinality>0..n</ccts:Cardinality>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* <ccts:PropertyTermQualifier>Validity</ccts:PropertyTermQualifier>
* <ccts:PropertyTerm>Period</ccts:PropertyTerm>
* <ccts:AssociatedObjectClass>Period</ccts:AssociatedObjectClass>
* <ccts:RepresentationTerm>Period</ccts:RepresentationTerm>
* </ccts:Component>
* </pre>
*
* Gets the value of the validityPeriod property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the validityPeriod property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getValidityPeriod().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PeriodType }
*
*
*/
public List<PeriodType> getValidityPeriod() {
if (validityPeriod == null) {
validityPeriod = new ArrayList<PeriodType>();
}
return this.validityPeriod;
}
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>ASBIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Address</ccts:DictionaryEntryName>
* <ccts:Definition>The address of this location.</ccts:Definition>
* <ccts:Cardinality>0..1</ccts:Cardinality>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* <ccts:PropertyTerm>Address</ccts:PropertyTerm>
* <ccts:AssociatedObjectClass>Address</ccts:AssociatedObjectClass>
* <ccts:RepresentationTerm>Address</ccts:RepresentationTerm>
* </ccts:Component>
* </pre>
*
*
*
* @return
* possible object is
* {@link AddressType }
*
*/
public AddressType getAddress() {
return address;
}
/**
* Sets the value of the address property.
*
* @param value
* allowed object is
* {@link AddressType }
*
*/
public void setAddress(AddressType value) {
this.address = value;
}
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>ASBIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Subsidiary_ Location. Location</ccts:DictionaryEntryName>
* <ccts:Definition>A location subsidiary to this location.</ccts:Definition>
* <ccts:Cardinality>0..n</ccts:Cardinality>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* <ccts:PropertyTermQualifier>Subsidiary</ccts:PropertyTermQualifier>
* <ccts:PropertyTerm>Location</ccts:PropertyTerm>
* <ccts:AssociatedObjectClass>Location</ccts:AssociatedObjectClass>
* <ccts:RepresentationTerm>Location</ccts:RepresentationTerm>
* </ccts:Component>
* </pre>
*
* Gets the value of the subsidiaryLocation property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the subsidiaryLocation property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSubsidiaryLocation().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link LocationType }
*
*
*/
public List<LocationType> getSubsidiaryLocation() {
if (subsidiaryLocation == null) {
subsidiaryLocation = new ArrayList<LocationType>();
}
return this.subsidiaryLocation;
}
/**
*
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><ccts:Component xmlns:ccts="urn:un:unece:uncefact:documentation:2" xmlns="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* <ccts:ComponentType>ASBIE</ccts:ComponentType>
* <ccts:DictionaryEntryName>Location. Location Coordinate</ccts:DictionaryEntryName>
* <ccts:Definition>The geographical coordinates of this location.</ccts:Definition>
* <ccts:Cardinality>0..n</ccts:Cardinality>
* <ccts:ObjectClass>Location</ccts:ObjectClass>
* <ccts:PropertyTerm>Location Coordinate</ccts:PropertyTerm>
* <ccts:AssociatedObjectClass>Location Coordinate</ccts:AssociatedObjectClass>
* <ccts:RepresentationTerm>Location Coordinate</ccts:RepresentationTerm>
* </ccts:Component>
* </pre>
*
* Gets the value of the locationCoordinate property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the locationCoordinate property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLocationCoordinate().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link LocationCoordinateType }
*
*
*/
public List<LocationCoordinateType> getLocationCoordinate() {
if (locationCoordinate == null) {
locationCoordinate = new ArrayList<LocationCoordinateType>();
}
return this.locationCoordinate;
}
}
| 51.065789 | 417 | 0.600167 |
ea6eaedd7d50c322583c8e5d5fafbc8e5c2522f8 | 310 | package co.lucz.binancetraderbot.repositories;
import co.lucz.binancetraderbot.entities.ErrorLogEntry;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ErrorLogRepository extends CrudRepository<ErrorLogEntry, Long> {
}
| 31 | 81 | 0.86129 |
0fcec7569f19677d844dcc18711afbfa4c4862ee | 2,829 | package com.hereblock.wallet.provider.service.impl;
import com.hereblock.wallet.api.model.WalletTransferBO;
import com.hereblock.wallet.api.model.WalletTransferVO;
import com.hereblock.wallet.provider.entity.WalletTransfer;
import com.hereblock.wallet.provider.mapper.WalletTransferMapper;
import com.hereblock.wallet.provider.service.WalletTransferService;
import com.hereblock.wallet.provider.util.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class WalletTransferServiceImpl implements WalletTransferService {
@Autowired
private WalletTransferMapper walletTransferMapper;
@Transactional
@Override
public int insertWalletTransfer(WalletTransferBO walletTransfer) {
if (walletTransfer == null) return 0;
WalletTransfer transfer = new WalletTransfer();
BeanUtil.copyProperties(walletTransfer, transfer);
return walletTransferMapper.insertWalletTransfer(transfer);
}
@Transactional
@Override
public int updateWalletTransfer(WalletTransferBO walletTransfer) {
if (walletTransfer == null) return 0;
WalletTransfer transfer = new WalletTransfer();
BeanUtil.copyProperties(walletTransfer, transfer);
return walletTransferMapper.updateWalletTransfer(transfer);
}
@Override
public List<WalletTransferVO> selectWalletTransfer(WalletTransferBO walletTransfer) {
if (walletTransfer == null) return null;
WalletTransfer transfer = new WalletTransfer();
BeanUtils.copyProperties(walletTransfer, transfer);
List<WalletTransfer> transfers = walletTransferMapper.selectWalletTransfer(transfer);
return BeanUtil.copyListProperties(transfers, WalletTransferVO.class);
}
@Override
public int insertTransferRecord(WalletTransferBO walletTransfer) {
if (walletTransfer == null) return 0;
return this.insertWalletTransfer(walletTransfer);
}
@Override
public int updateWalletTransferByTransferNo(WalletTransferBO walletTransfer) {
if (walletTransfer == null) return 0;
WalletTransfer transfer = new WalletTransfer();
BeanUtils.copyProperties(walletTransfer, transfer);
return walletTransferMapper.updateWalletTransferByTransferNo(transfer);
}
@Override
public WalletTransfer selectWalletTransferByTxId(WalletTransferBO walletTransfer) {
if (walletTransfer == null) return null;
WalletTransfer transfer = new WalletTransfer();
BeanUtils.copyProperties(walletTransfer, transfer);
return walletTransferMapper.selectWalletTransferByTxId(transfer);
}
}
| 40.414286 | 93 | 0.766702 |
a65779f43480570383205a66c6d9950d19e48fe4 | 1,618 | package vkaretko.models;
/**
* Class Figure.
*
* @author Karetko Victor.
* @version 1.00.
* @since 05.02.2017.
*/
public abstract class Figure {
/**
* X coordinate.
*/
private int x;
/**
* Y coordinate.
*/
private int y;
/**
* Game field.
*/
private Cell[][] field;
/**
* COnstructor of class Figure.
* @param x x coord.
* @param y y coord.
* @param field game field.
*/
public Figure(Cell[][] field, int x, int y) {
this.x = x;
this.y = y;
this.field = field;
}
/**
* Method for makeing steps of figures.
* @param dir direction to go.
* @return true if figure made step, false otherwise.
*/
public boolean makeStep(Direction dir) {
boolean result;
final int destX = this.x + dir.get()[0];
final int destY = this.y + dir.get()[1];
if (destX >= field.length || destY >= field.length || destX < 0 || destY < 0) {
result = false;
} else {
synchronized (field[destX][destY]) {
if (field[destX][destY].getFigure() == null) {
field[destX][destY].setFigure(this);
System.out.println(String.format("%s %s:%s", Thread.currentThread().getName(), destX, destY));
field[x][y].setFigure(null);
this.x = destX;
this.y = destY;
result = true;
} else {
result = false;
}
}
}
return result;
}
}
| 23.794118 | 114 | 0.474042 |
5a7524edb8a2c3ee715384c17d63ab12798d2b0e | 599 | package com.android.abstactfactorypattern.factory;
import com.android.abstactfactorypattern.button.IButton;
import com.android.abstactfactorypattern.button.MacOSButton;
import com.android.abstactfactorypattern.text.IText;
import com.android.abstactfactorypattern.text.MacOSText;
/**
* Description: #TODO
*
* @author zzp(zhao_zepeng@hotmail.com)
* @since 2016-05-22
*/
public class MacOSFactory implements IFactory{
@Override
public IButton createButton() {
return new MacOSButton();
}
@Override
public IText createText() {
return new MacOSText();
}
}
| 23.96 | 60 | 0.741235 |
09c0cf6d8b4af088e74c2f283b806f2549f3c5fa | 8,570 | package com.hotel.controller.backend;
import com.google.common.collect.Maps;
import com.hotel.common.Const;
import com.hotel.common.ResponseCode;
import com.hotel.common.ServerResponse;
import com.hotel.pojo.Hotels;
import com.hotel.pojo.User;
import com.hotel.service.IFileService;
import com.hotel.service.IHotelService;
import com.hotel.service.IUserService;
import com.hotel.util.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
/**
* @program: HotelOrder1
* @description:
* @author: yhh
* @create: 2020-04-22 09:21
**/
@Controller
@RequestMapping(value = "/manage/hotels")
public class HotelManageController {
@Autowired
private IUserService iUserService;
@Autowired
private IHotelService iHotelService;
@Autowired
private IFileService iFileService;
@RequestMapping("addOrUpdate_hotel.do")
@ResponseBody
public ServerResponse addOrUpdateHotel(HttpSession session, Hotels hotels){
User user=(User)session.getAttribute(Const.CURRENT_USER);
if (user==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录");
}
if (iUserService.checkAdminRole(user).isSuccess()){
//管理员
return iHotelService.addOrUpdateHotel(hotels);
}else {
return ServerResponse.createByErrorMessage("无权限操作,需管理员权限");
}
}
@RequestMapping("set_hotel_name.do")
@ResponseBody
public ServerResponse setHotelName(HttpSession session,Integer hotelId,String hotelname){
User user=(User)session.getAttribute(Const.CURRENT_USER);
if (user==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录");
}
if (iUserService.checkAdminRole(user).isSuccess()){
//管理员
return iHotelService.updateHotelName(hotelId,hotelname);
}else {
return ServerResponse.createByErrorMessage("无权限操作,需管理员权限");
}
}
// @RequestMapping("get_Rooms.do")
// @ResponseBody
// public ServerResponse getRoomsParallelHotel(HttpSession session, Integer hotelId){
// User user=(User)session.getAttribute(Const.CURRENT_USER);
// if (user==null){
// return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录");
// }
// if (iUserService.checkAdminRole(user).isSuccess()){
// //管理员
//
// }else {
// return ServerResponse.createByErrorMessage("无权限操作,需管理员权限");
// }
// }
@RequestMapping("set_hotel_status.do")
@ResponseBody
public ServerResponse getRoomsParallelHotel(HttpSession session, Integer hotelId,Integer status){
User user=(User)session.getAttribute(Const.CURRENT_USER);
if (user==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录");
}
if (iUserService.checkAdminRole(user).isSuccess()){
//管理员
return iHotelService.setHotelStatus(hotelId,status);
}else {
return ServerResponse.createByErrorMessage("无权限操作,需管理员权限");
}
}
@RequestMapping("detail.do")
@ResponseBody
public ServerResponse getHotelDetails(HttpSession session,Integer hostId){
User user=(User)session.getAttribute(Const.CURRENT_USER);
if (user==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录");
}
if (iUserService.checkAdminRole(user).isSuccess()){
//管理员
return iHotelService.manageHotelDetail(hostId);
}else {
return ServerResponse.createByErrorMessage("无权限操作,需管理员权限");
}
}
@RequestMapping("list.do")
@ResponseBody
public ServerResponse getList(HttpSession session, @RequestParam(value = "pageNum",defaultValue = "1") int pageNum, @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
User user=(User)session.getAttribute(Const.CURRENT_USER);
if (user==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录");
}
if (iUserService.checkAdminRole(user).isSuccess()){
//管理员
return iHotelService.manageHotelList(pageNum,pageSize);
}else {
return ServerResponse.createByErrorMessage("无权限操作,需管理员权限");
}
}
@RequestMapping("search.do")
@ResponseBody
public ServerResponse getList(HttpSession session,String hotelName, Integer hotelId,@RequestParam(value = "pageNum",defaultValue = "1") int pageNum, @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
User user=(User)session.getAttribute(Const.CURRENT_USER);
if (user==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录");
}
if (iUserService.checkAdminRole(user).isSuccess()){
//管理员
return iHotelService.searchHotel(hotelName,hotelId,pageNum,pageSize);
}else {
return ServerResponse.createByErrorMessage("无权限操作,需管理员权限");
}
}
@RequestMapping("upload.do")
@ResponseBody
public ServerResponse upload(HttpSession session,@RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request){
User user=(User)session.getAttribute(Const.CURRENT_USER);
if (user==null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录");
}
if (iUserService.checkAdminRole(user).isSuccess()){
//管理员
String path=request.getSession().getServletContext().getRealPath("upload");
String targetFileName=iFileService.upload(file,path);
String url= PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
Map fileMap= Maps.newHashMap();
fileMap.put("uri",targetFileName);
fileMap.put("url",url);
return ServerResponse.createBySuccess(fileMap);
}else {
return ServerResponse.createByErrorMessage("无权限操作,需管理员权限");
}
}
@RequestMapping("richtext_img_upload.do")
@ResponseBody
public Map richTextImgUpload(HttpSession session, @RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response){
Map resultMap=Maps.newHashMap();
User user=(User)session.getAttribute(Const.CURRENT_USER);
if (user==null){
resultMap.put("success",false);
resultMap.put("msg","请登录管理员");
return resultMap;
}
//富文本中对返回值有要求,按照simditor要求返回
// {
// "success": true/false,
// "msg": "error message", # optional
// "file_path": "[real file path]"
// }
if (iUserService.checkAdminRole(user).isSuccess()){
//管理员
String path=request.getSession().getServletContext().getRealPath("upload");
String targetFileName=iFileService.upload(file,path);
if(StringUtils.isBlank(targetFileName)){
resultMap.put("success",false);
resultMap.put("msg","上传失败");
return resultMap;
}
String url= PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
resultMap.put("success",true);
resultMap.put("msg","上传成功");
resultMap.put("file_path",url);
response.addHeader("Access-Control-Allow-Headers","X-File-Name");
return resultMap;
}else {
resultMap.put("success",false);
resultMap.put("msg","无权限操作");
return resultMap;
}
}
}
| 40.809524 | 222 | 0.651692 |
f5738873124f0045034fc54ec78c545eabad36e4 | 123 | package com.jbm.util.bean.queue;
/**
* 分拣器的状态
*
* @author wesley
*
*/
public enum ForwardState {
RUNING, DESTROY
}
| 10.25 | 32 | 0.642276 |
7eec784107d35ad998d32cd9f6086590abc93417 | 1,200 | import de.tuda.stg.consys.annotations.methods.StrongOp;
import de.tuda.stg.consys.annotations.methods.WeakOp;
import de.tuda.stg.consys.checker.qual.Mixed;
import de.tuda.stg.consys.checker.qual.Strong;
import de.tuda.stg.consys.checker.qual.Weak;
import java.util.LinkedList;
/**
* Tests that the default operation level in the Mixed annotation are included during field inference.
*/
public class DefaultTest {
// explicit StrongOp default
static @Mixed(StrongOp.class) class MixedStrong {
private int i; // inferred strong
void setI(@Weak int j, @Strong int k) {
k = i;
// :: error: assignment
i = j;
}
}
// explicit WeakOp default
static @Mixed(WeakOp.class) class MixedWeak {
private int i; // inferred weak
void setI(@Weak int j, @Strong int k) {
// :: error: assignment
k = i;
i = j;
}
}
// implicit WeakOp default
static @Mixed class MixedNoDefault {
private int i; // inferred weak
void setI(@Weak int j, @Strong int k) {
// :: error: assignment
k = i;
i = j;
}
}
}
| 26.086957 | 102 | 0.591667 |
62c7a5de289cf648b79a45d42919b58bda75dd6c | 4,154 | package com.jonatans.ppmtool.services;
import com.jonatans.ppmtool.domain.Backlog;
import com.jonatans.ppmtool.domain.ProjectTask;
import com.jonatans.ppmtool.exception.ProjectNotFoundException;
import com.jonatans.ppmtool.repositories.BacklogRepository;
import com.jonatans.ppmtool.repositories.ProjectRepository;
import com.jonatans.ppmtool.repositories.ProjectTaskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ProjectTaskService {
@Autowired
private BacklogRepository backlogRepository;
@Autowired
private ProjectTaskRepository projectTaskRepository;
@Autowired
private ProjectRepository projectRepository;
@Autowired
private ProjectService projectService;
public ProjectTask addProjectTask(String projectIdentifier, ProjectTask projectTask, String email){
try {
//PTs to be added to a specific project, project != null, BL exists
Backlog backlog = projectService.findProjectByIdentifier(projectIdentifier, email).getBacklog(); //backlogRepository.findByProjectIdentifier(projectIdentifier);
//set the bl to pt
System.out.println(backlog);
projectTask.setBacklog(backlog);
//we want our project sequence to be like this: IDPRO-1 IDPRO-2 ...100 101
Integer BacklogSequence = backlog.getPTSequence();
// Update the BL SEQUENCE
BacklogSequence++;
backlog.setPTSequence(BacklogSequence);
//Add Sequence to Project Task
projectTask.setProjectSequence(backlog.getProjectIdentifier()+"-"+BacklogSequence);
projectTask.setProjectIdentifier(projectIdentifier);
//INITIAL priority when priority null
//INITIAL status when status is null
//INITIAL priority when priority null
//INITIAL status when status is null
if(projectTask.getStatus()==""|| projectTask.getStatus()==null){
projectTask.setStatus("TO_DO");
}
//Fix bug with priority in Spring Boot Server, needs to check null first
if(projectTask.getPriority()==null||projectTask.getPriority()==0){ //In the future we need projectTask.getPriority()== 0 to handle the form
projectTask.setPriority(3);
}
return projectTaskRepository.save(projectTask);
}catch (Exception e){
throw new ProjectNotFoundException("Project not Found");
}
}
public Iterable<ProjectTask>findBacklogById(String id, String email){
projectService.findProjectByIdentifier(id, email);
return projectTaskRepository.findByProjectIdentifierOrderByPriority(id);
}
public ProjectTask findPTByProjectSequence(String backlog_id, String pt_id, String email){
//make sure we are searching on an existing backlog
projectService.findProjectByIdentifier(backlog_id, email);
//make sure that our task exists
ProjectTask projectTask = projectTaskRepository.findByProjectSequence(pt_id);
if(projectTask == null){
throw new ProjectNotFoundException("Project Task '"+pt_id+"' not found");
}
//make sure that the backlog/project id in the path corresponds to the right project
if(!projectTask.getProjectIdentifier().equals(backlog_id)){
throw new ProjectNotFoundException("Project Task '"+pt_id+"' does not exist in project: '"+backlog_id);
}
return projectTask;
}
public ProjectTask updateByProjectSequence(ProjectTask updatedTask, String backlog_id, String pt_id, String email){
ProjectTask projectTask = findPTByProjectSequence(backlog_id, pt_id, email);
projectTask = updatedTask;
return projectTaskRepository.save(projectTask);
}
public void deletePTByProjectSequence(String backlog_id, String pt_id, String email){
ProjectTask projectTask = findPTByProjectSequence(backlog_id, pt_id, email);
projectTaskRepository.delete(projectTask);
}
} | 36.121739 | 173 | 0.703418 |
11a3848f7184d79209adb608f58c752d0dcdcb01 | 1,210 | /*
* Copyright (C) 2012 RoboVM AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bugvm.objc;
import com.bugvm.rt.bro.Struct;
import com.bugvm.rt.bro.annotation.StructMember;
/**
*
*/
public final class ObjCSuper extends Struct<ObjCSuper> {
public ObjCSuper(ObjCObject receiver, ObjCClass objcClass) {
receiver(receiver);
objCClass(objcClass);
}
@StructMember(0)
public native ObjCObject receiver();
@StructMember(0)
public native ObjCSuper receiver(ObjCObject receiver);
@StructMember(1)
public native ObjCClass objCClass();
@StructMember(1)
public native ObjCSuper objCClass(ObjCClass objCClass);
}
| 28.139535 | 75 | 0.712397 |
050466f90567b55a2e6738ab1cf0241a3f693579 | 67 | package com.example.instagramclone;
public class PostsAdapter {
}
| 13.4 | 35 | 0.80597 |
1c4c42b8835ffb3a059a13530054130f790b1716 | 358 | package lzt.xiaodai.cn.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
/**
* @author luoyong
* @Date: 2019/4/10 11:51
* @Description:
*/
@Data
public class TApp {
private Integer id;
@TableField("versioncode")
private String versionCode;
@TableField("versionname")
private String versionName;
}
| 17.047619 | 54 | 0.706704 |
2d487c0d5ef304244e5442dda716299cdf47054a | 5,837 | package com.webcheckers.ui;
import com.webcheckers.application.GameManager;
import com.webcheckers.application.PlayerLobby;
import com.webcheckers.model.Player;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.Session;
import java.util.logging.Logger;
import static com.webcheckers.ui.GetHomeRoute.CHALLENGE_USER_KEY;
/**
* The {@code POST /requestResponse} route handler.
*
* @author Mario Castano
*/
public class PostRequestResponseRoute implements Route
{
private static final Logger LOG = Logger.getLogger(GetHomeRoute.class.getName());
static final String GAME_ACCEPT = "gameAccept";
private final PlayerLobby lobby;
private static final String KING_JUMP = "src/test/java/com/webcheckers/test" +
"-boards/multiJumpLongAfterKing.JSON";
private static final String REQUIRE_JUMP = "src/test/java/com/webcheckers" +
"/test-boards/requireJumpBoard.JSON";
private static final String NECESSARY_JUMP_WHITE = "src/test/java/com" +
"/webcheckers/test-boards/necesssaryJumpWhite.JSON";
private static final String MULTI_JUMP_STILL_REQUIRED_WRONG = "src/test" +
"/java/com/webcheckers/test-boards/multiJumpBoardStillJump.JSON";
public static final String NO_MORE_MOVES = "src/test/java/com/webcheckers" +
"/test-boards/no-more-moves.JSON";
private static final String ABOUT_JUMP_ALL = "src/test/java/com/webcheckers" +
"/test-boards/about-to-all-pieces-jumped.JSON";
private static final String DEMO_1 = "src/test/java/com/webcheckers/test" +
"-boards/test-demo-1.JSON";
private static final String ABOUT_MOVES_NONE = "src/test/java/com" +
"/webcheckers/test-boards/about-to-no-more-moves";
private static final String KING_BACK_AGAIN = "src/test/java/com" +
"/webcheckers/test-boards/kingBackOnSelf.JSON";
/*
This is all of the names to start preloaded games.
*/
public static final String MULTI_KING = "TEST MULTI KING JUMP";
public static final String REQUIRE_JUMP_ = "TEST REQUIRE JUMP";
public static final String NEC_WHITE = "TEST NECESSARY WHITE";
public static final String NO_MOVES = "TEST NO MORE MOVES";
public static final String MULTI_JUMP_REQ = "TEST MULTI JUMP REQUIRE";
public static final String ABOUTA_JUMP = "ABOUT TO JUMP ALL";
public static final String ABOUT_NO_MORE_MOVES = "ABOUT NO MOVES";
public static final String TEST_DEM1 = "TEST DEMO 1";
public static final String KING_BACK = "KING BACK AGAIN";
/**
* Constructor for the {@code GET/game} route handler.
*
* @param lobby: the player lobby for the Response.
*/
PostRequestResponseRoute(final PlayerLobby lobby)
{
//validation
this.lobby = lobby;
}
private void startGameOrTest(String username, String opponent,
GameManager manager)
{
switch (username)
{
case MULTI_KING:
manager.startTestGame(username, opponent, KING_JUMP, 1);
break;
case REQUIRE_JUMP_:
manager.startTestGame(username, opponent, REQUIRE_JUMP, 1);
break;
case NEC_WHITE:
manager.startTestGame(username, opponent, NECESSARY_JUMP_WHITE, 2);
break;
case NO_MOVES:
manager.startTestGame(username, opponent, NO_MORE_MOVES, 1);
break;
case MULTI_JUMP_REQ:
manager.startTestGame(username, opponent,
MULTI_JUMP_STILL_REQUIRED_WRONG, 1);
break;
case ABOUTA_JUMP:
manager.startTestGame(username, opponent, ABOUT_JUMP_ALL, 1);
break;
case TEST_DEM1:
manager.startTestGame(username, opponent, DEMO_1, 1);
break;
case ABOUT_NO_MORE_MOVES:
manager.startTestGame(username, opponent, ABOUT_MOVES_NONE, 1);
break;
case KING_BACK:
manager.startTestGame(username, opponent, KING_BACK_AGAIN, 1);
break;
default:
manager.startGame(username, opponent);
break;
}
}
/**
* {@inheritDoc}
* <p>
* The handler for player response to game request that has been sent. First, a user challenges another user,
* and a request is sent consists of the player's username and the challengee's username from
* the list of users logged onto the playerLobby.
*/
@Override
public String handle(Request request, Response response)
{
LOG.config("Post Request Response has been invoked.");
//retrieve the playerLobby object to verify that no time out has occurred
final Session httpSession = request.session();
final Player player = httpSession.attribute(GetHomeRoute.PLAYER_KEY);
/* A null playerLobby indicates a timed out session or an illegal request on this URL.
* In either case, we will redirect back to home.
*/
if (player != null)
{
final String usernameStr = player.getUsername();
final String accept = request.queryParams(GAME_ACCEPT);
String oppPlayer = httpSession.attribute(CHALLENGE_USER_KEY);
oppPlayer = oppPlayer.replace('-', ' ');
GameManager gameManager = httpSession.attribute(GetHomeRoute.GAME_MANAGER_KEY);
LOG.config("Response to: " + oppPlayer);
switch (accept)
{
case "yes":
lobby.removeChallenger(oppPlayer);
lobby.removeChallenger(usernameStr);
startGameOrTest(oppPlayer, usernameStr, gameManager);
response.redirect(WebServer.GAME_URL);
return "Game redirect";
case "no":
lobby.removeChallenger(oppPlayer);
lobby.removeChallenger(usernameStr);
response.redirect(WebServer.HOME_URL);
return "Home Redirect";
//Act upon the player's response to a game request
}
} else
{
response.redirect(WebServer.HOME_URL);
return "Home Redirect";
}
return null;
}
}
| 36.48125 | 111 | 0.691451 |
1e0b6a04a220fa31fc0ecc3567713ab43f8c5771 | 3,212 | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.socket.adapter.standard;
import java.util.HashMap;
import java.util.Map;
import javax.websocket.Session;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.http.HttpHeaders;
import org.springframework.web.socket.handler.TestPrincipal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Unit tests for {@link org.springframework.web.socket.adapter.standard.StandardWebSocketSession}.
*
* @author Rossen Stoyanchev
*/
public class StandardWebSocketSessionTests {
private final HttpHeaders headers = new HttpHeaders();
private final Map<String, Object> attributes = new HashMap<>();
@Test
@SuppressWarnings("resource")
public void getPrincipalWithConstructorArg() {
TestPrincipal user = new TestPrincipal("joe");
StandardWebSocketSession session = new StandardWebSocketSession(this.headers, this.attributes, null, null, user);
assertThat(session.getPrincipal()).isSameAs(user);
}
@Test
@SuppressWarnings("resource")
public void getPrincipalWithNativeSession() {
TestPrincipal user = new TestPrincipal("joe");
Session nativeSession = Mockito.mock(Session.class);
given(nativeSession.getUserPrincipal()).willReturn(user);
StandardWebSocketSession session = new StandardWebSocketSession(this.headers, this.attributes, null, null);
session.initializeNativeSession(nativeSession);
assertThat(session.getPrincipal()).isSameAs(user);
}
@Test
@SuppressWarnings("resource")
public void getPrincipalNone() {
Session nativeSession = Mockito.mock(Session.class);
given(nativeSession.getUserPrincipal()).willReturn(null);
StandardWebSocketSession session = new StandardWebSocketSession(this.headers, this.attributes, null, null);
session.initializeNativeSession(nativeSession);
reset(nativeSession);
assertThat(session.getPrincipal()).isNull();
verifyNoMoreInteractions(nativeSession);
}
@Test
@SuppressWarnings("resource")
public void getAcceptedProtocol() {
String protocol = "foo";
Session nativeSession = Mockito.mock(Session.class);
given(nativeSession.getNegotiatedSubprotocol()).willReturn(protocol);
StandardWebSocketSession session = new StandardWebSocketSession(this.headers, this.attributes, null, null);
session.initializeNativeSession(nativeSession);
reset(nativeSession);
assertThat(session.getAcceptedProtocol()).isEqualTo(protocol);
verifyNoMoreInteractions(nativeSession);
}
}
| 31.490196 | 115 | 0.782067 |
9082ed1f219280901ffc629a024b88041a68e8f4 | 1,785 | package net.sunxu.mybatis.automapper.processor.environment;
import com.google.common.base.Strings;
import org.apache.ibatis.type.JdbcType;
import javax.validation.constraints.NotNull;
import static net.sunxu.mybatis.automapper.processor.util.HelpUtils.convertToLowerCaseSplitByUnderLine;
import static net.sunxu.mybatis.automapper.processor.util.HelpUtils.convertToUpperCaseSplitByUnderLine;
public abstract class Configuration {
public enum NamingRule {
DEFAULT,
LOWER_CASE,
LOWER_CASE_SPLIT_BY_UNDER_LINE,
UPPER_CASE,
UPPER_CASE_SPLIT_BY_UNDER_LINE;
}
public String getMybatisConfigurationPath() {
return null;
}
public String getMybatisDefaultDatabaseId() {
return null;
}
public @NotNull NamingRule getDefaultSchemaNamingRule() {
return NamingRule.DEFAULT;
}
public @NotNull NamingRule getDefaultColumnNamingRule() {
return NamingRule.DEFAULT;
}
public String getDefaultAnnoymousMapper() {
return null;
}
public String getNameByNamingRule(String name, NamingRule rule) {
name = Strings.nullToEmpty(name);
if (rule != null) {
switch (rule) {
case LOWER_CASE:
return name.toLowerCase();
case LOWER_CASE_SPLIT_BY_UNDER_LINE:
return convertToLowerCaseSplitByUnderLine(name);
case UPPER_CASE:
return name.toUpperCase();
case UPPER_CASE_SPLIT_BY_UNDER_LINE:
return convertToUpperCaseSplitByUnderLine(name);
}
}
return name;
}
public @NotNull JdbcType getJdbcTypeByJavaType(String javaType) {
return JdbcType.UNDEFINED;
}
}
| 28.790323 | 103 | 0.664426 |
cfbba27d2bb16ee88c82d2b7706973f34630752d | 332 | package com.gzc.appendix_b.double_checked_locking;
public class Main {
public static void main(String[] args) {
// 线程A
new Thread(() -> System.out.println(MySystem.getInstance().getDate())).start();
// 线程B
new Thread(() -> System.out.println(MySystem.getInstance().getDate())).start();
}
}
| 27.666667 | 87 | 0.626506 |
d7d261b6b467483dfc5f334519f3d855f4717b19 | 900 | package com.mauersu.util.common;
import com.mauersu.config.RedisConfig;
import com.mauersu.exception.RedisInitException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Created by zhigang.huang on 2017/9/27.
*/
public class ResourceUtil {
public static Properties loadProperties(String resource) {
Properties properties = new Properties();
InputStream is = null;
try {
is = openInputStream(resource);
properties.load(is);
} catch (IOException var3) {
throw new RedisInitException("couldn't load properties file '" + resource + "' ", var3);
} finally {
IOUtil.closeQuietly(is);
}
return properties;
}
public static InputStream openInputStream(String resource) {
return ResourceUtil.class.getResourceAsStream(resource);
}
}
| 27.272727 | 100 | 0.664444 |
530a5fc8cf4259d4e6b1bd1cdf85674e694e581e | 116 | package com.xeno.goo.interactions;
public interface IBlobInteraction
{
boolean resolve(BlobContext context);
}
| 16.571429 | 41 | 0.793103 |
7f1db70aa54885dc5f349f31ac8b84888055b060 | 1,299 | package com.cesarschool.ManagerProject.model;
import java.sql.Date;
import java.time.MonthDay;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Calendario {
@Id
@GeneratedValue
private long id;
@Column(nullable = false)
private String descricao;
@ElementCollection
private List<Date> feriadosFixos = new ArrayList<Date>();
@ElementCollection
private List<MonthDay> feriadosCiclicos = new ArrayList<MonthDay>();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public List<Date> getFeriadosFixos() {
return feriadosFixos;
}
public void setFeriadosFixos(List<Date> feriadosFixos) {
this.feriadosFixos = feriadosFixos;
}
public List<MonthDay> getFeriadosCiclicos() {
return feriadosCiclicos;
}
public void setFeriadosCiclicos(List<MonthDay> feriadosCiclicos) {
this.feriadosCiclicos = feriadosCiclicos;
}
}
| 20.296875 | 69 | 0.767513 |
36d9f56e9eea36ac6c1d89c5f68d3ab3c5a93195 | 2,365 | package com.justwayward.book.bean;
import java.util.List;
/**
* Created by gaoyuan on 2017/11/23.
*/
public class CategoryBean {
/**
* id : 1
* category : 分类1
* pid : 0
* list_order : 0
* sub_category : [{"id":2,"category":"测试分类","pid":1,"list_order":0,"novel_num":0}]
*/
private int id;
private String category;
private int pid;
private int list_order;
private List<SubCategoryBean> sub_category;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public int getList_order() {
return list_order;
}
public void setList_order(int list_order) {
this.list_order = list_order;
}
public List<SubCategoryBean> getSub_category() {
return sub_category;
}
public void setSub_category(List<SubCategoryBean> sub_category) {
this.sub_category = sub_category;
}
public static class SubCategoryBean {
/**
* id : 2
* category : 测试分类
* pid : 1
* list_order : 0
* novel_num : 0
*/
private int id;
private String category;
private int pid;
private int list_order;
private int novel_num;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public int getList_order() {
return list_order;
}
public void setList_order(int list_order) {
this.list_order = list_order;
}
public int getNovel_num() {
return novel_num;
}
public void setNovel_num(int novel_num) {
this.novel_num = novel_num;
}
}
}
| 19.545455 | 87 | 0.534461 |
a38ec1006ae93edc01bb01c5fe090cde3191fea3 | 400 | public class MaximumSubarray {
public int largestSum(int[] array) {
int prevSum = array[0];
int res = array[0];
for (int i = 1; i < array.length; i++) {
if (prevSum > 0) {
prevSum += array[i];
} else {
prevSum = array[i];
}
res = Math.max(prevSum, res);
}
return res;
}
}
| 25 | 48 | 0.4275 |
dbd43c4231d1bc52918eeb52bb172511c696efdf | 1,310 | /**
* Copyright 2020 yametech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yametech.yangjian.agent.plugin.redisson.bean;
import java.util.List;
public class RedisKeyBean {
private List<String> keys;
private long eventTime;
private long useTime;
public RedisKeyBean(List<String> keys, long eventTime, long useTime) {
this.keys = keys;
this.eventTime = eventTime;
this.useTime = useTime;
}
public List<String> getKeys() {
return keys;
}
public void setKeys(List<String> keys) {
this.keys = keys;
}
public long getEventTime() {
return eventTime;
}
public void setEventTime(long eventTime) {
this.eventTime = eventTime;
}
public long getUseTime() {
return useTime;
}
public void setUseTime(long useTime) {
this.useTime = useTime;
}
}
| 22.982456 | 75 | 0.722137 |
1a1e150c7cbcf9f8d00694663e2a3edca0672543 | 1,706 | package com.google.android.gms.common.internal;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.internal.safeparcel.SafeParcelReader;
public final class zan implements Creator<ResolveAccountResponse> {
public final /* synthetic */ Object[] newArray(int i) {
return new ResolveAccountResponse[i];
}
public final /* synthetic */ Object createFromParcel(Parcel parcel) {
int b = SafeParcelReader.m21925b(parcel);
IBinder iBinder = null;
ConnectionResult connectionResult = null;
int i = 0;
boolean z = false;
boolean z2 = false;
while (parcel.dataPosition() < b) {
int a = SafeParcelReader.m21920a(parcel);
int a2 = SafeParcelReader.m21919a(a);
if (a2 == 1) {
i = SafeParcelReader.m21949w(parcel, a);
} else if (a2 == 2) {
iBinder = SafeParcelReader.m21948v(parcel, a);
} else if (a2 == 3) {
connectionResult = (ConnectionResult) SafeParcelReader.m21921a(parcel, a, ConnectionResult.CREATOR);
} else if (a2 == 4) {
z = SafeParcelReader.m21945s(parcel, a);
} else if (a2 != 5) {
SafeParcelReader.m21918C(parcel, a);
} else {
z2 = SafeParcelReader.m21945s(parcel, a);
}
}
SafeParcelReader.m21944r(parcel, b);
ResolveAccountResponse resolveAccountResponse = new ResolveAccountResponse(i, iBinder, connectionResult, z, z2);
return resolveAccountResponse;
}
}
| 39.674419 | 120 | 0.62075 |
a4400067601e8b00cf011384c7b9039bf53b47ea | 2,160 | package com.sap.cloud.lm.sl.mta.handlers.v3;
import java.util.Arrays;
import org.junit.runners.Parameterized.Parameters;
import com.sap.cloud.lm.sl.common.util.Tester.Expectation;
public class DescriptorMergerTest extends com.sap.cloud.lm.sl.mta.handlers.v2.DescriptorMergerTest {
@Parameters
public static Iterable<Object[]> getParameters() {
return Arrays.asList(new Object[][] {
// @formatter:off
// (0) Valid deployment and extension descriptor:
{
"/mta/sample/v3/mtad-01.yaml", new String[] { "/mta/sample/v3/config-01.mtaext", },
new Expectation(Expectation.Type.JSON, "/mta/sample/v3/merged-04.yaml.json"),
},
// (1) Valid deployment and extension descriptors (multiple):
{
"/mta/sample/v3/mtad-01.yaml", new String[] { "/mta/sample/v3/config-01.mtaext", "/mta/sample/v3/config-05.mtaext", },
new Expectation(Expectation.Type.JSON, "/mta/sample/v3/merged-05.yaml.json"),
},
// (2) Merge hook parameters from deployment and extension descriptor
{
"/mta/sample/v3/mtad-06.yaml", new String[] { "/mta/sample/v3/config-08.mtaext", },
new Expectation(Expectation.Type.JSON, "/mta/sample/v3/merged-06.yaml.json"),
},
// (3) Merge hook required dependencies from deployment and extension descriptor
{
"/mta/sample/v3/mtad-06.yaml", new String[] { "/mta/sample/v3/config-09.mtaext", },
new Expectation(Expectation.Type.JSON, "/mta/sample/v3/merged-07.yaml.json"),
},
// @formatter:on
});
}
public DescriptorMergerTest(String deploymentDescriptorLocation, String[] extensionDescriptorLocations, Expectation expectation) {
super(deploymentDescriptorLocation, extensionDescriptorLocations, expectation);
}
@Override
protected DescriptorMerger createDescriptorMerger() {
return new DescriptorMerger();
}
@Override
protected DescriptorParser getDescriptorParser() {
return new DescriptorParser();
}
}
| 40 | 134 | 0.633796 |
43dd3b2572558336a6feede4800a7930252cb276 | 1,982 | package com.lk.syxl.customview.mvp.impl;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.lk.syxl.customview.model.Phone;
import com.lk.syxl.customview.mvp.NumberBelongView;
import com.lk.syxl.customview.utils.HttpUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Created by likun on 2017/10/11.
*/
public class NumberBelongPresenter extends BasePresenter {
String api = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
NumberBelongView belongView;
Phone mPhone;
public NumberBelongPresenter(NumberBelongView belongView){
this.belongView = belongView;
}
public Phone getPhoneInfo(){
return mPhone;
}
public void searchPhoneInfo(String phone){
if (phone.length() != 11){
belongView.showToast("手机号码格式不对");
return;
}
belongView.showLoading();
check(phone);
}
private void check(String phone) {
Map<String ,String> praram = new HashMap<>();
praram.put("tel",phone);
HttpUtils utils = new HttpUtils(new HttpUtils.HttpResponse() {
@Override
public void onSuccess(Object obj) {
String json = obj.toString();
int indexOf = json.indexOf("{");
json = json.substring(indexOf);
mPhone = parseModelFromFastjson(json);
belongView.closeLoading();
belongView.updateView();
}
@Override
public void onError(String error) {
belongView.showToast(error);
belongView.closeLoading();
}
});
utils.sendGetRequest(api,praram);
}
private Phone parseModelFromGson(String json){
Gson gson = new Gson();
return gson.fromJson(json, Phone.class);
}
private Phone parseModelFromFastjson(String json){
return JSONObject.parseObject(json,Phone.class);
}
}
| 27.150685 | 72 | 0.616044 |
5810fde201e23046bce9c26129c3a41c2ac4d0da | 5,493 | package neu.train.project.system.controller;
import neu.train.common.constant.UserConstants;
import neu.train.common.utils.SecurityUtils;
import neu.train.common.utils.StringUtils;
//import neu.train.common.utils.poi.ExcelUtil;
//import neu.train.framework.aspectj.lang.annotation.Log;
//import neu.train.framework.aspectj.lang.enums.BusinessType;
import neu.train.framework.security.service.TokenService;
import neu.train.framework.web.controller.BaseController;
import neu.train.framework.web.domain.AjaxResult;
import neu.train.framework.web.page.TableDataInfo;
import neu.train.project.system.domain.SysUser;
import neu.train.project.system.service.ISysRoleService;
import neu.train.project.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* User 信息
*
* @author
*/
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
@Autowired
private ISysUserService userService;
@Autowired
private ISysRoleService roleService;
// @Autowired
// private ISysPostService postService;
@Autowired
private TokenService tokenService;
/**
* 获取User 列表
*/
@PreAuthorize("@ss.hasPermi('system:user:list')")
@GetMapping("/list")
public TableDataInfo list(SysUser user)
{
startPage();
List<SysUser> list = userService.selectUserList(user);
return getDataTable(list);
}
/**
* 根据User ID获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:user:query')")
@GetMapping(value = { "/", "/{userId}" })
public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
{
AjaxResult ajax = AjaxResult.success();
ajax.put("roles", roleService.selectRoleAll());
// ajax.put("posts", postService.selectPostAll());
if (StringUtils.isNotNull(userId))
{
ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
// ajax.put("postIds", postService.selectPostListByUserId(userId));
ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
}
return ajax;
}
/**
* Add User
*/
@PreAuthorize("@ss.hasPermi('system:user:add')")
// @Log(title = "User 管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysUser user)
{
if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
{
return AjaxResult.error("Add User '" + user.getUserName() + "'Fail,登录Account Already存在");
}
else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
{
return AjaxResult.error("Add User '" + user.getUserName() + "'Fail,Tele-NumberAlready存在");
}
else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
{
return AjaxResult.error("Add User '" + user.getUserName() + "'Fail,邮箱Account Already存在");
}
user.setCreateBy(SecurityUtils.getUsername());
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
return toAjax(userService.insertUser(user));
}
/**
* Modify User
*/
@PreAuthorize("@ss.hasPermi('system:user:edit')")
// @Log(title = "User 管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysUser user)
{
userService.checkUserAllowed(user);
if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
{
return AjaxResult.error(" Modify User '" + user.getUserName() + "'Fail,Tele-NumberAlready存在");
}
else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
{
return AjaxResult.error(" Modify User '" + user.getUserName() + "'Fail,邮箱Account Already存在");
}
user.setUpdateBy(SecurityUtils.getUsername());
return toAjax(userService.updateUser(user));
}
/**
* Delete User
*/
@PreAuthorize("@ss.hasPermi('system:user:remove')")
// @Log(title = "User 管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{userIds}")
public AjaxResult remove(@PathVariable Long[] userIds)
{
return toAjax(userService.deleteUserByIds(userIds));
}
/**
* Reset 密码
*/
@PreAuthorize("@ss.hasPermi('system:user:edit')")
// @Log(title = "User 管理", businessType = BusinessType.UPDATE)
@PutMapping("/resetPwd")
public AjaxResult resetPwd(@RequestBody SysUser user)
{
userService.checkUserAllowed(user);
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
user.setUpdateBy(SecurityUtils.getUsername());
return toAjax(userService.resetPwd(user));
}
/**
* Status Modify
*/
@PreAuthorize("@ss.hasPermi('system:user:edit')")
// @Log(title = "User 管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody SysUser user)
{
userService.checkUserAllowed(user);
user.setUpdateBy(SecurityUtils.getUsername());
return toAjax(userService.updateUserStatus(user));
}
} | 34.765823 | 107 | 0.675769 |
8f9627b0266bf3707a3bb6e83c7adbe4916fcdca | 1,095 | package edu.rutgers.MOST.presentation;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRootPane;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;
//based on code from http://www.java2s.com/Code/Java/Swing-JFC/CreateaProgressBar.htm
public class ProgressBar extends JFrame {
//public JButton cancelButton = new JButton(" Cancel ");
public JProgressBar progress = new JProgressBar(0, 100);
public ProgressBar() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
progress.setValue(0);
progress.setStringPainted(true);
pane.add(progress);
/*
JPanel pane2 = new JPanel();
pane2.add(cancelButton);
pane.add(pane2);
*/
setContentPane(pane);
setUndecorated(true);
//pane.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.GRAY));
pane.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 2, false));
}
} | 29.594595 | 103 | 0.770776 |
ddb88d28c2321bbc153a54899579cb3741823657 | 162 | package sample;
public class MockConnection implements AutoCloseable {
public void close() {
System.out.println("MockConnection is closed.");
}
} | 23.142857 | 56 | 0.703704 |
adbd8958131380abcff8de71df21e334e969a7b1 | 636 | /**
* @Author : Anand Kumar Keshavan
*/
public class Main {
public static void main(String[] args) {
Cart cart = new Cart();
cart.Add( new Item("Veggies", "Onions", 2, 100.00))
.Add( new Item("Dairy Prod", "Milk", 4, 60.00))
.Add( new Item("Snacks", "Biscuits", 2, 20.00))
.Add( new Item("Snacks", "Chips", 3, 40.00))
.Add( new Item("Veggies", "Tomatoes", 1, 60.00))
.Add( new Item("Snacks", "Chocolate", 1, 50.00));
System.out.println(cart.toString());
CategorizedView view= CategorizedView.create(cart);
System.out.println(view.toString());
}
}
| 28.909091 | 58 | 0.566038 |
7c936627f333c16aea7f1535f16de4bd0ca779d0 | 205 | package com.atsebak.embeddedlinuxjvm.utils;
public class Notifications {
/**
* ID for notifications
*/
public static final String GROUPDISPLAY_ID = "EmbeddedLinux JVM Notifications";
}
| 20.5 | 83 | 0.717073 |
559bacb1edb3d423c47e9fb9e0a8b770716c65e6 | 5,132 | /*
* Copyright 2014 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.profiler.context;
import com.navercorp.pinpoint.bootstrap.context.Trace;
import com.navercorp.pinpoint.bootstrap.context.TraceId;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.profiler.context.id.AsyncIdGenerator;
import com.navercorp.pinpoint.profiler.context.id.DefaultTraceId;
import com.navercorp.pinpoint.profiler.context.recorder.DefaultRecorderFactory;
import com.navercorp.pinpoint.profiler.context.recorder.RecorderFactory;
import com.navercorp.pinpoint.profiler.context.storage.SpanStorage;
import com.navercorp.pinpoint.profiler.metadata.SqlMetaDataService;
import com.navercorp.pinpoint.profiler.metadata.StringMetaDataService;
import com.navercorp.pinpoint.profiler.sender.EnhancedDataSender;
import com.navercorp.pinpoint.profiler.sender.LoggingDataSender;
import com.navercorp.pinpoint.rpc.FutureListener;
import com.navercorp.pinpoint.rpc.ResponseMessage;
import com.navercorp.pinpoint.rpc.client.PinpointClientReconnectEventListener;
import org.apache.thrift.TBase;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.mockito.Mockito.mock;
/**
* @author emeroad
*/
public class TraceTest {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Test
public void trace() {
TraceId traceId = new DefaultTraceId("agent", 0, 1);
CallStackFactory callStackFactory = new CallStackFactoryV1(64);
SpanFactory spanFactory = new DefaultSpanFactory("appName", "agentId", 0, ServiceType.STAND_ALONE);
StringMetaDataService stringMetaDataService = mock(StringMetaDataService.class);
SqlMetaDataService sqlMetaDataService = mock(SqlMetaDataService.class);
RecorderFactory recorderFactory = new DefaultRecorderFactory(stringMetaDataService, sqlMetaDataService);
AsyncIdGenerator asyncIdGenerator = mock(AsyncIdGenerator.class);
SpanStorage storage = new SpanStorage(LoggingDataSender.DEFAULT_LOGGING_DATA_SENDER);
Trace trace = new DefaultTrace(callStackFactory, storage, traceId, 0L, asyncIdGenerator, true,
spanFactory, recorderFactory);
trace.traceBlockBegin();
// get data form db
getDataFromDB(trace);
// response to client
trace.traceBlockEnd();
}
@Test
public void popEventTest() {
TraceId traceId = new DefaultTraceId("agent", 0, 1);
CallStackFactory callStackFactory = new CallStackFactoryV1(64);
SpanFactory spanFactory = new DefaultSpanFactory("appName", "agentId", 0, ServiceType.STAND_ALONE);
StringMetaDataService stringMetaDataService = mock(StringMetaDataService.class);
SqlMetaDataService sqlMetaDataService = mock(SqlMetaDataService.class);
RecorderFactory recorderFactory = new DefaultRecorderFactory(stringMetaDataService, sqlMetaDataService);
AsyncIdGenerator asyncIdGenerator = mock(AsyncIdGenerator.class);
TestDataSender dataSender = new TestDataSender();
SpanStorage storage = new SpanStorage(LoggingDataSender.DEFAULT_LOGGING_DATA_SENDER);
Trace trace = new DefaultTrace(callStackFactory, storage, traceId, 0L, asyncIdGenerator, true, spanFactory, recorderFactory);
trace.close();
logger.debug(String.valueOf(dataSender.event));
}
public class TestDataSender implements EnhancedDataSender {
public boolean event;
@Override
public boolean send(TBase<?, ?> data) {
event = true;
return false;
}
@Override
public void stop() {
}
@Override
public boolean request(TBase<?, ?> data) {
return send(data);
}
@Override
public boolean request(TBase<?, ?> data, int retry) {
return send(data);
}
@Override
public boolean request(TBase<?, ?> data, FutureListener<ResponseMessage> listener) {
return send(data);
}
@Override
public boolean addReconnectEventListener(PinpointClientReconnectEventListener eventListener) {
return false;
}
@Override
public boolean removeReconnectEventListener(PinpointClientReconnectEventListener eventListener) {
return false;
}
}
private void getDataFromDB(Trace trace) {
trace.traceBlockBegin();
// db server request
// get a db response
trace.traceBlockEnd();
}
}
| 34.911565 | 133 | 0.720382 |
30d479088c870cbfcdbd4c32a5ae32a893e835b4 | 911 | package Core;
/*Rap Battle Online: Class ProfileImage*/
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
import com.loopj.android.http.BinaryHttpResponseHandler;
import WebApi.WebApiClient;
public class ProfileImage {
public static void getImageData(String avatarPath, final ImageView avatar){
try {
WebApiClient.get(WebApiClient.BASE_ADDRESS + avatarPath, null, new BinaryHttpResponseHandler(new String[] { "image/png", "image/jpeg" }) {
@Override
public void onSuccess(byte[] responseData) {
Bitmap image = BitmapFactory.decodeByteArray(responseData, 0, responseData.length);
avatar.setImageBitmap(image);
}
});
}
catch(Throwable e){
Log.wtf("Image", e);
}
}
}
| 31.413793 | 150 | 0.645445 |
a1e7aa5e47c54ca3346010a7a84e11970ffb94d1 | 670 | package expression.logical;
import expression.Expression;
/** class to represent logical expression Equal
* @author Hélène Collavizza
* @date June 2008
*/
public class EqualExpression extends Comparator{
public EqualExpression(Expression a1, Expression a2) {
super(a1,a2);
}
public String toString() {
return "( " + arg1.toString() + "==" + arg2.toString() + " )";
}
public boolean equals(Expression exp){
return (exp instanceof EqualExpression) &&
arg1.equals(((EqualExpression)exp).arg1) && arg2.equals(((EqualExpression)exp).arg2);
}
public String abstractSyntax(){
return "IDSExprEquality";
}
}
| 21.612903 | 90 | 0.665672 |
6dfc05597872a922af6911f33d508cdbb05e65ab | 1,805 | /*
* Copyright 2010-2019 James Pether Sörling
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $Id$
* $HeadURL$
*/
package com.hack23.cia.service.data.api;
import com.hack23.cia.model.internal.application.system.impl.ApplicationConfiguration;
import com.hack23.cia.model.internal.application.system.impl.ConfigurationGroup;
/**
* The Interface ApplicationConfigurationService.
*/
@FunctionalInterface
public interface ApplicationConfigurationService {
/**
* Check value or load default.
*
* @param configTitle
* the config title
* @param configDescription
* the config description
* @param configurationGroup
* the configuration group
* @param component
* the component
* @param componentTitle
* the component title
* @param componentDescription
* the component description
* @param propertyId
* the property id
* @param propertyValue
* the property value
* @return the application configuration
*/
ApplicationConfiguration checkValueOrLoadDefault(String configTitle, String configDescription,
ConfigurationGroup configurationGroup, String component, String componentTitle, String componentDescription,
String propertyId, String propertyValue);
}
| 32.232143 | 111 | 0.725762 |
7d51e9fdfa51f97bc0c3694636e64da4ac6c07f6 | 927 | package ru.job4j.array;
/**
* Contains.
* @author MShonorov (shonorov@gmail.com)
* @version $Id$
* @since 0.1
*/
public class ArrayCharLike {
/**
* Find if one string contains another.
* @param origin origin string.
* @param sub string to find.
* @return true if contains.
*/
public boolean contains(String origin, String sub) {
boolean result = false;
char[] data = origin.toCharArray();
char[] value = sub.toCharArray();
for (int i = 0; i <= data.length - value.length; i++) {
for (int j = 0; j < value.length; j++) {
if (data[i + j] != value[j]) {
break;
}
if (data[i + j] == value[value.length - 1]) {
result = true;
}
}
if (result) {
break;
}
}
return result;
}
}
| 26.485714 | 63 | 0.463862 |
63a74ce3e284c940a43009cb82c8dea247c2cafe | 2,103 | package com.bloxbean.cardano.client.coinselection;
import com.bloxbean.cardano.client.backend.exception.ApiException;
import com.bloxbean.cardano.client.backend.model.Amount;
import com.bloxbean.cardano.client.backend.model.Utxo;
import com.bloxbean.cardano.client.config.Configuration;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* Implement this interface to provide custom UtxoSelection Strategy
*/
public interface UtxoSelectionStrategy {
default List<Utxo> selectUtxos(String address, String unit, BigInteger amount, Set<Utxo> utxosToExclude) throws ApiException {
return this.selectUtxos(address, unit, amount, null, utxosToExclude);
}
default List<Utxo> selectUtxos(String address, String unit, BigInteger amount, String datumHash, Set<Utxo> utxosToExclude) throws ApiException{
Set<Utxo> selected = select(address, new Amount(unit, amount), datumHash, utxosToExclude);
return selected != null ? new ArrayList<>(selected) : Collections.emptyList();
}
default Set<Utxo> select(String address, Amount outputAmount, String datumHash, Set<Utxo> utxosToExclude){
return select(address, outputAmount, datumHash, utxosToExclude, Configuration.INSTANCE.getCoinSelectionLimit());
}
default Set<Utxo> select(String address, Amount outputAmount, String datumHash, Set<Utxo> utxosToExclude, int maxUtxoSelectionLimit){
return select(address, Collections.singletonList(outputAmount), datumHash, utxosToExclude, maxUtxoSelectionLimit);
}
default Set<Utxo> select(String address, List<Amount> outputAmounts, String datumHash, Set<Utxo> utxosToExclude){
return this.select(address, outputAmounts, datumHash, utxosToExclude, Configuration.INSTANCE.getCoinSelectionLimit());
}
Set<Utxo> select(String address, List<Amount> outputAmounts, String datumHash, Set<Utxo> utxosToExclude, int maxUtxoSelectionLimit);
UtxoSelectionStrategy fallback();
void setIgnoreUtxosWithDatumHash(boolean ignoreUtxosWithDatumHash);
}
| 51.292683 | 147 | 0.779363 |
67d7f9c9b25de4e041719339d12c19663069514b | 2,850 | package com.purbon.kafka.topology.model;
import com.purbon.kafka.topology.model.users.Connector;
import com.purbon.kafka.topology.model.users.Consumer;
import com.purbon.kafka.topology.model.users.KStream;
import com.purbon.kafka.topology.model.users.Producer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Project {
private String name;
private List<String> zookeepers;
private List<Consumer> consumers;
private List<Producer> producers;
private List<KStream> streams;
private List<Connector> connectors;
private Map<String, List<String>> rbacRawRoles;
private List<Topic> topics;
private Topology topology;
public Project() {
this("default");
}
public Project(String name) {
this.name = name;
this.topics = new ArrayList<>();
this.consumers = new ArrayList<>();
this.producers = new ArrayList<>();
this.streams = new ArrayList<>();
this.consumers = new ArrayList<>();
this.zookeepers = new ArrayList<>();
this.connectors = new ArrayList<>();
this.rbacRawRoles = new HashMap<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getZookeepers() {
return zookeepers;
}
public void setZookeepers(List<String> zookeepers) {
this.zookeepers = zookeepers;
}
public List<Consumer> getConsumers() {
return consumers;
}
public void setConsumers(List<Consumer> consumers) {
this.consumers = consumers;
}
public List<Producer> getProducers() {
return producers;
}
public void setProducers(List<Producer> producers) {
this.producers = producers;
}
public List<KStream> getStreams() {
return streams;
}
public void setStreams(List<KStream> streams) {
this.streams = streams;
}
public List<Connector> getConnectors() {
return connectors;
}
public void setConnectors(List<Connector> connectors) {
this.connectors = connectors;
}
public List<Topic> getTopics() {
return topics;
}
public void addTopic(Topic topic) {
topic.setProject(this);
this.topics.add(topic);
}
public void setTopics(List<Topic> topics) {
this.topics = topics;
}
public String buildTopicPrefix() {
return buildTopicPrefix(topology);
}
public String buildTopicPrefix(Topology topology) {
StringBuilder sb = new StringBuilder();
sb.append(topology.buildNamePrefix())
.append(".")
.append(name);
return sb.toString();
}
public void setTopology(Topology topology) {
this.topology = topology;
}
public void setRbacRawRoles(Map<String, List<String>> rbacRawRoles) {
this.rbacRawRoles = rbacRawRoles;
}
public Map<String, List<String>> getRbacRawRoles() {
return rbacRawRoles;
}
}
| 22.265625 | 71 | 0.691228 |
3fa3dc59c4cd2cd090d7cebfbf3024876b86a1f8 | 228 | package net.woggioni.worth.utils;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
@EqualsAndHashCode
@RequiredArgsConstructor
public class Tuple2<T, U> {
public final T _1;
public final U _2;
}
| 19 | 38 | 0.785088 |
12211062e73300de56cd44426e1abc16251f9561 | 1,789 | package com.demo.mediacodec;
import com.demo.mediacodec.decoder.AudioDecodeThread;
import com.demo.mediacodec.decoder.VideoDecodeThread;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
// https://github.com/taehwandev/MediaCodecExample/tree/master/src/net/thdev/mediacodecexample/decoder
// https://github.com/vecio/MediaCodecDemo
// https://github.com/starlightslo/Android-Music-MediaCodec-Example/blob/master/src/com/tonyhuang/example/Decoder.java
public class DecodeActivity extends Activity implements SurfaceHolder.Callback {
private static final String SAMPLE = Environment.getExternalStorageDirectory() + "/video.mp4";
private VideoDecodeThread mVideo = null;
private AudioDecodeThread mAudio = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SurfaceView sv = new SurfaceView(this);
sv.getHolder().addCallback(this);
setContentView(sv);
}
protected void onDestroy() {
super.onDestroy();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (mVideo == null) {
mVideo = new VideoDecodeThread(holder.getSurface(), SAMPLE);
mVideo.start();
}
if (mAudio == null) {
mAudio = new AudioDecodeThread(SAMPLE);
mAudio.start();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mVideo != null) {
mVideo.close();
mVideo = null;
}
if (mAudio != null) {
mAudio.close();
mAudio = null;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} | 26.308824 | 118 | 0.74455 |
aaca2b7433f279e5627fae002fffa856d0aad90b | 1,414 |
package com.lmax.disruptor.support;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.SequenceBarrier;
public final class TestWaiter implements Callable<List<StubEvent>>
{
private final long toWaitForSequence;
private final long initialSequence;
private final CyclicBarrier cyclicBarrier;
private final SequenceBarrier sequenceBarrier;
private final RingBuffer<StubEvent> ringBuffer;
public TestWaiter(
final CyclicBarrier cyclicBarrier,
final SequenceBarrier sequenceBarrier,
final RingBuffer<StubEvent> ringBuffer,
final long initialSequence,
final long toWaitForSequence)
{
this.cyclicBarrier = cyclicBarrier;
this.initialSequence = initialSequence;
this.ringBuffer = ringBuffer;
this.toWaitForSequence = toWaitForSequence;
this.sequenceBarrier = sequenceBarrier;
}
@Override
public List<StubEvent> call() throws Exception
{
cyclicBarrier.await();
sequenceBarrier.waitFor(toWaitForSequence);
final List<StubEvent> messages = new ArrayList<>();
for (long l = initialSequence; l <= toWaitForSequence; l++)
{
messages.add(ringBuffer.get(l));
}
return messages;
}
} | 29.458333 | 67 | 0.706506 |
68e178c9ac7dc81730ff7089d8d4a6120122040c | 6,302 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.airlift.stats;
import com.facebook.airlift.log.Logger;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import io.airlift.units.Duration;
import org.HdrHistogram.Histogram;
import org.HdrHistogram.HistogramIterationValue;
import org.weakref.jmx.Managed;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.concurrent.GuardedBy;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
public class PauseMeter
{
private static final Logger LOG = Logger.get(PauseMeter.class);
private final long sleepNanos;
@GuardedBy("histogram")
private final Histogram histogram = new Histogram(3);
@GuardedBy("histogram")
private long totalPauseNanos;
private final Supplier<Histogram> snapshot = Suppliers.memoizeWithExpiration(this::makeSnapshot, 1, TimeUnit.SECONDS);
private final Thread thread;
// public to make it less likely for the VM to optimize it out
public volatile Object allocatedObject;
public PauseMeter()
{
this(new Duration(10, TimeUnit.MILLISECONDS));
}
public PauseMeter(Duration sleepTime)
{
this.sleepNanos = sleepTime.roundTo(TimeUnit.NANOSECONDS);
thread = new Thread(this::run, "VM Pause Meter");
thread.setDaemon(true);
}
@PostConstruct
public void start()
{
thread.start();
}
@PreDestroy
public void stop()
{
thread.interrupt();
}
private Histogram makeSnapshot()
{
synchronized (histogram) {
return histogram.copy();
}
}
private void run()
{
long shortestObservableInterval = Long.MAX_VALUE;
while (!Thread.currentThread().isInterrupted()) {
try {
long before = System.nanoTime();
TimeUnit.NANOSECONDS.sleep(sleepNanos);
// attempt to allocate an object to capture any effects due to allocation stalls
allocatedObject = new Long[] {before};
long after = System.nanoTime();
long delta = after - before;
shortestObservableInterval = Math.min(shortestObservableInterval, delta);
long pauseNanos = delta - shortestObservableInterval;
synchronized (histogram) {
histogram.recordValue(pauseNanos);
totalPauseNanos += pauseNanos;
}
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
catch (Throwable e) {
LOG.warn(e, "Unexpected error");
}
}
}
@Managed(description = "< 10ms")
public long getLessThan10msPauses()
{
return snapshot.get().getCountBetweenValues(0, TimeUnit.MILLISECONDS.toNanos(10));
}
@Managed(description = "10ms to 50ms")
public long get10msTo50msPauses()
{
return snapshot.get().getCountBetweenValues(TimeUnit.MILLISECONDS.toNanos(10), TimeUnit.MILLISECONDS.toNanos(50));
}
@Managed(description = "50ms to 500ms")
public long get50msTo500msPauses()
{
return snapshot.get().getCountBetweenValues(TimeUnit.MILLISECONDS.toNanos(50), TimeUnit.MILLISECONDS.toNanos(500));
}
@Managed(description = "500ms to 1s")
public long get500msTo1sPauses()
{
return snapshot.get().getCountBetweenValues(TimeUnit.MILLISECONDS.toNanos(500), TimeUnit.SECONDS.toNanos(1));
}
@Managed(description = "1s to 10s")
public long get1sTo10sPauses()
{
return snapshot.get().getCountBetweenValues(TimeUnit.SECONDS.toNanos(1), TimeUnit.SECONDS.toNanos(10));
}
@Managed(description = "10s to 1m")
public long get10sTo1mPauses()
{
return snapshot.get().getCountBetweenValues(TimeUnit.SECONDS.toNanos(10), TimeUnit.MINUTES.toNanos(1));
}
@Managed(description = "> 1m")
public long getGreaterThan1mPauses()
{
return snapshot.get().getCountBetweenValues(TimeUnit.MINUTES.toNanos(1), Long.MAX_VALUE);
}
@Managed(description = "Per-bucket counts")
public Map<Double, Long> getCounts()
{
Map<Double, Long> result = new TreeMap<>();
for (HistogramIterationValue entry : snapshot.get().logarithmicBucketValues(TimeUnit.MILLISECONDS.toNanos(1), 2)) {
double median = (entry.getValueIteratedTo() + entry.getValueIteratedFrom()) / 2.0;
result.put(round(median / (double) TimeUnit.MILLISECONDS.toNanos(1), 2), entry.getCountAddedInThisIterationStep());
}
return result;
}
@Managed(description = "Per-bucket total pause time in s")
public Map<Double, Double> getSums()
{
long previous = 0;
Map<Double, Double> result = new TreeMap<>();
for (HistogramIterationValue entry : snapshot.get().logarithmicBucketValues(TimeUnit.MILLISECONDS.toNanos(1), 2)) {
double median = (entry.getValueIteratedTo() + entry.getValueIteratedFrom()) / 2.0;
long current = entry.getTotalValueToThisValue();
result.put(round(median / TimeUnit.MILLISECONDS.toNanos(1), 2), round((current - previous) * 1.0 / TimeUnit.SECONDS.toNanos(1), 2));
previous = current;
}
return result;
}
@Managed
public double getTotalPauseSeconds()
{
synchronized (histogram) {
return totalPauseNanos * 1.0 / TimeUnit.SECONDS.toNanos(1);
}
}
private static double round(double value, int digits)
{
double scale = Math.pow(10, digits);
return Math.round(value * scale) / scale;
}
}
| 31.828283 | 144 | 0.654237 |
6c9e5ca526900e3f69d6f83f7141e377487ddd6f | 1,859 | /*
* The MIT License
*
* Copyright 2016 kbouzidi.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.reit.utils;
/**
* <h3 id="target"><a name="user-content-target" href="#target" class="headeranchor-link" aria-hidden="true"><span
* class="headeranchor"></span></a>Todo state {@link Enum}</h3>
*/
public enum EStates {
TODO("TODO"),
ONGOING("ONGOING"),
DONE("DONE"),
DELETED("DELETED");
private String value;
EStates(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
public static EStates fromString(String text) {
if (text != null) {
for (EStates state : EStates.values()) {
if (text.equalsIgnoreCase(state.getValue())) {
return state;
}
}
}
return null;
}
} | 32.614035 | 114 | 0.688542 |
9e9c8512f7956bcdcd696c38b899a69d34881f40 | 2,781 | package eu.fbk.das.rs.challenges;
import static eu.fbk.das.utils.Utils.equal;
import static eu.fbk.das.utils.Utils.f;
import static eu.fbk.das.utils.Utils.pf;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.joda.time.DateTime;
import eu.fbk.das.rs.challenges.calculator.ChallengesConfig;
import eu.fbk.das.rs.challenges.generation.RecommendationSystem;
import it.smartcommunitylab.model.PlayerStateDTO;
import it.smartcommunitylab.model.ext.PlayerLevel;
import it.smartcommunitylab.model.ext.PointConcept;
public class ChallengeUtil {
protected RecommendationSystem rs;
protected String prefix;
protected int playerLimit = 50;
protected int minLvl = -1;
protected String[] counters;
public ChallengeUtil() {
this(new RecommendationSystem());
}
public ChallengeUtil(RecommendationSystem rs) {
this.rs = rs;
}
public void prepare(int challengeWeek) {
counters = ChallengesConfig.getPerfomanceCounters();
prefix = f(ChallengesConfig.getChallengeNamePrefix(), challengeWeek);
}
protected List<String> getPlayers() {
Set<String> players = rs.facade.getGamePlayers(rs.gameId);
List<String> playersToConsider = new ArrayList<>(playerLimit);
for (String pId: players) {
PlayerStateDTO p = rs.facade.getPlayerState(rs.gameId, pId);
int lvl = getLevel(p);
if (minLvl < 0 || lvl >= minLvl) {
playersToConsider.add(pId);
if (playerLimit != 0 && playersToConsider.size() >= playerLimit)
break;
}
}
return playersToConsider;
}
public static int getLevel(PlayerStateDTO state) {
// check the level of the player
List<PlayerLevel> lvls = state.getLevels();
for (PlayerLevel lvl: lvls) {
if (!equal(lvl.getPointConcept(), "green leaves"))
continue;
return lvl.getLevelIndex();
/*
String s = slug(lvl.getLevelValue());
for (int i = 0; i < cfg.levelNames.length; i++)
if (equal(s, slug(cfg.levelNames[i])))
return i;
pf("Could not decode value %s of PlayerStateDTO level %s \n", lvl.getLevelValue(), lvl);
return -1;
*/
}
pf("Could not find level based on green leaves! %s - Assuming level 0 \n", lvls);
return 0;
}
public static double getPeriodScore(PointConcept pc, String w, DateTime dt) {
try {
return pc.getPeriodScore(w, dt.getMillis());
} catch (Exception e) { // if ask for a date previous of period startDate return 0
return 0;
}
}
}
| 27.264706 | 100 | 0.619202 |
6ac2b0a5429f3667606a786961a3ded2e2d60c7a | 625 | package com.karta05csr.bandung.home.viewmodel.controller;
import com.karta05csr.bandung.databinding.HomeActivityBinding;
import com.karta05csr.bandung.home.viewmodel.HomeVM;
import id.gits.mvvmcore.controller.GitsController;
/**
* Created by irfan on 17/06/16.
*/
public class HomeController extends GitsController<HomeVM, HomeActivityBinding> {
@Override
public HomeVM createViewModel(HomeActivityBinding binding) {
return new HomeVM(mActivity, this, binding);
}
@Override
public void bindViewModel(HomeActivityBinding binding, HomeVM viewModel) {
binding.setVm(viewModel);
}
}
| 28.409091 | 81 | 0.7632 |
2a9f5ff6587b7be2696521faa1284466cbdc45a7 | 4,113 | package com.basaki.example.config;
import com.basaki.example.handler.BookHandler;
import com.basaki.example.handler.MovieHandler;
import com.basaki.example.util.UuidBeanFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import java.util.UUID;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.dozer.loader.api.BeanMappingBuilder;
import org.dozer.loader.api.TypeMappingOptions;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ServletHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;
/**
* Created by indra.basak on 3/8/17.
*/
@Configuration
public class SpringConfiguration {
@Bean
public static Mapper getMapper() {
BeanMappingBuilder builder = new BeanMappingBuilder() {
protected void configure() {
mapping(UUID.class, UUID.class, TypeMappingOptions.oneWay(),
TypeMappingOptions.beanFactory(
UuidBeanFactory.class.getName()));
}
};
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.addMapping(builder);
return mapper;
}
@Primary
@Bean
public ObjectMapper createCustomObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.registerModule(new JodaModule());
return mapper;
}
//@Bean
public ServletRegistrationBean registerBookServlet(BookHandler handler) {
HttpHandler httpHandler = WebHttpHandlerBuilder
.webHandler(toHttpHandler(handler.getRoutes()))
.build();
ServletHttpHandlerAdapter servlet =
new ServletHttpHandlerAdapter(httpHandler);
ServletRegistrationBean registrationBean =
new ServletRegistrationBean<>(servlet, "/booxs");
registrationBean.setName("booxs");
registrationBean.setLoadOnStartup(1);
registrationBean.setAsyncSupported(true);
return registrationBean;
}
@Bean
public ServletRegistrationBean registerMoviewServlet(MovieHandler handler) {
HttpHandler httpHandler = WebHttpHandlerBuilder
.webHandler(toHttpHandler(handler.getRoutes()))
.build();
ServletHttpHandlerAdapter servlet =
new ServletHttpHandlerAdapter(httpHandler);
ServletRegistrationBean registrationBean =
new ServletRegistrationBean<>(servlet, "/");
registrationBean.setName("movies");
registrationBean.setLoadOnStartup(1);
registrationBean.setAsyncSupported(true);
return registrationBean;
}
private RouterFunction<ServerResponse> routingFunctionOld() {
HandlerFunction<ServerResponse> ping =
request -> ServerResponse.ok().body(fromObject("pong"));
return route(GET("/ping"), ping).filter((request, next) -> {
System.out.println(
"Before handler invocation: " + request.path());
return next.handle(request);
});
}
}
| 37.733945 | 93 | 0.719426 |
bbea9f318ac3a9bd13085e08fc85bf7f79afdd71 | 11,769 | package org.monarchinitiative.sgenes.gtf.io.impl;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.monarchinitiative.sgenes.gtf.model.Biotype;
import org.monarchinitiative.sgenes.gtf.model.RefseqGene;
import org.monarchinitiative.sgenes.gtf.model.RefseqSource;
import org.monarchinitiative.sgenes.gtf.model.RefseqTranscript;
import org.monarchinitiative.sgenes.model.*;
import org.monarchinitiative.svart.CoordinateSystem;
import org.monarchinitiative.svart.Coordinates;
import org.monarchinitiative.svart.GenomicRegion;
import org.monarchinitiative.svart.Strand;
import org.monarchinitiative.svart.assembly.GenomicAssemblies;
import org.monarchinitiative.svart.assembly.GenomicAssembly;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class RefseqParserTest {
private static final Path IMPL_DIR = Path.of("src/test/resources/org/monarchinitiative/sgenes/gtf/io/impl");
@Nested
public class SmallGtfFileTest {
private final GenomicAssembly GRCH38 = GenomicAssemblies.GRCh38p13();
/**
* A GTF file with definitions of SURF2 and FBN1 genes from RefSeq.
* The file was prepared by running:
* <pre>
* zcat GCF_000001405.39_GRCh38.p13_genomic.gtf.gz | grep "^#" > GCF_000001405.39_GRCh38.p13_genomic.surf2_fbn1.gtf
* zcat GCF_000001405.39_GRCh38.p13_genomic.gtf.gz | grep "SURF2" >> GCF_000001405.39_GRCh38.p13_genomic.surf2_fbn1.gtf
* zcat GCF_000001405.39_GRCh38.p13_genomic.gtf.gz | grep "FBN1" >> GCF_000001405.39_GRCh38.p13_genomic.surf2_fbn1.gtf
* gzip GCF_000001405.39_GRCh38.p13_genomic.surf2_fbn1.gtf
* </pre>
* Then, we removed <em>FBN-DT</em> and the <em>SURF2_1</em>.
*/
private final Path GTF_PATH = IMPL_DIR.resolve("GCF_000001405.39_GRCh38.p13_genomic.surf2_fbn1.gtf.gz");
@Test
public void iterate() {
RefseqParser parser = new RefseqParser(GTF_PATH, GRCH38);
List<RefseqGene> genes = new ArrayList<>();
for (RefseqGene gene : parser) {
genes.add(gene);
}
assertThat(genes, hasSize(2));
}
@Test
public void stream() {
RefseqParser parser = new RefseqParser(GTF_PATH, GRCH38);
List<RefseqGene> genes = parser.stream().sequential()
.collect(Collectors.toUnmodifiableList());
assertThat(genes, hasSize(2));
// ----------------------------------------- SURF2 ---------------------------------------------------------
RefseqGene surf2 = genes.get(0);
// Location stuff
assertThat(surf2.contigName(), equalTo("9"));
assertThat(surf2.strand(), equalTo(Strand.POSITIVE));
assertThat(surf2.coordinateSystem(), equalTo(CoordinateSystem.oneBased()));
assertThat(surf2.start(), equalTo(133_356_550));
assertThat(surf2.end(), equalTo(133_361_158));
// ID stuff
assertThat(surf2.accession(), equalTo("NCBIGene:6835"));
assertThat(surf2.symbol(), equalTo("SURF2"));
assertThat(surf2.id().hgncId().isPresent(), equalTo(true));
assertThat(surf2.id().hgncId().get(), equalTo("HGNC:11475"));
assertThat(surf2.id().ncbiGeneId().isPresent(), equalTo(true));
assertThat(surf2.id().ncbiGeneId().get(), equalTo("NCBIGene:6835"));
// Metadata
assertThat(surf2.biotype(), equalTo(Biotype.protein_coding));
// Transcripts
assertThat(surf2.transcriptCount(), equalTo(2));
Iterator<? extends RefseqTranscript> surf2Iterator = surf2.transcripts();
RefseqTranscript surf2Tx = surf2Iterator.next();
assertThat(surf2Tx.evidence().isPresent(), equalTo(true));
assertThat(surf2Tx.evidence().get(), equalTo(TranscriptEvidence.KNOWN));
assertThat(surf2Tx.featureSource().isPresent(), equalTo(true));
assertThat(surf2Tx.featureSource().get(), equalTo(FeatureSource.REFSEQ));
// ----------------------------------------- FBN1 ----------------------------------------------------------
RefseqGene fbn1 = genes.get(1);
// Location stuff
assertThat(fbn1.contigName(), equalTo("15"));
assertThat(fbn1.strand(), equalTo(Strand.NEGATIVE));
assertThat(fbn1.coordinateSystem(), equalTo(CoordinateSystem.oneBased()));
assertThat(fbn1.start(), equalTo(53_345_481));
assertThat(fbn1.end(), equalTo(53_582_877));
// ID stuff
assertThat(fbn1.accession(), equalTo("NCBIGene:2200"));
assertThat(fbn1.symbol(), equalTo("FBN1"));
assertThat(fbn1.id().hgncId().isPresent(), equalTo(true));
assertThat(fbn1.id().hgncId().get(), equalTo("HGNC:3603"));
assertThat(fbn1.id().ncbiGeneId().isPresent(), equalTo(true));
assertThat(fbn1.id().ncbiGeneId().get(), equalTo("NCBIGene:2200"));
// Metadata
assertThat(fbn1.biotype(), equalTo(Biotype.protein_coding));
// Transcripts
assertThat(fbn1.transcriptCount(), equalTo(1));
Iterator<? extends RefseqTranscript> fbn1Iterator = fbn1.transcripts();
RefseqTranscript fbn1Tx = fbn1Iterator.next();
assertThat(fbn1Tx.evidence().isPresent(), equalTo(true));
assertThat(fbn1Tx.evidence().get(), equalTo(TranscriptEvidence.KNOWN));
assertThat(fbn1Tx.featureSource().isPresent(), equalTo(true));
assertThat(fbn1Tx.featureSource().get(), equalTo(FeatureSource.REFSEQ));
Map<String, Coordinates> cdsCoordinates = fbn1.codingTranscripts()
.collect(Collectors.toMap(Identified::accession, Coding::cdsCoordinates));
assertThat(cdsCoordinates, hasEntry("NM_000138.5", Coordinates.of(CoordinateSystem.oneBased(), 53_346_421, 53_580_200)));
}
}
/**
* Older (hg19) RefSeq releases do not include `transcript` rows. We should infer the transcript data from other rows.
*/
@Nested
public class MissingTranscriptRecordsTest {
private final GenomicAssembly GRCH37 = GenomicAssemblies.GRCh37p13();
/**
* A GTF file with definitions of SURF2 and FBN1 genes from RefSeq.
* The file was prepared by running:
* <pre>
* zcat GCF_000001405.39_GRCh38.p13_genomic.gtf.gz | grep "^#" > GCF_000001405.39_GRCh38.p13_genomic.surf2_fbn1.gtf
* zcat GCF_000001405.39_GRCh38.p13_genomic.gtf.gz | grep "SURF2" >> GCF_000001405.39_GRCh38.p13_genomic.surf2_fbn1.gtf
* zcat GCF_000001405.39_GRCh38.p13_genomic.gtf.gz | grep "FBN1" >> GCF_000001405.39_GRCh38.p13_genomic.surf2_fbn1.gtf
* gzip GCF_000001405.39_GRCh38.p13_genomic.surf2_fbn1.gtf
* </pre>
* Then, we removed <em>FBN-DT</em> and the <em>SURF2_1</em>.
*/
private final Path GTF_PATH = IMPL_DIR.resolve("GCF_000001405.25_GRCh37.p13_genomic.surf2.gtf.gz");
@Test
public void iterate() {
RefseqParser parser = new RefseqParser(GTF_PATH, GRCH37);
List<RefseqGene> genes = new ArrayList<>();
for (RefseqGene gene : parser) {
genes.add(gene);
}
assertThat(genes, hasSize(1));
RefseqGene surf2 = genes.get(0);
// Location stuff
assertThat(surf2.contigName(), equalTo("9"));
assertThat(surf2.strand(), equalTo(Strand.POSITIVE));
assertThat(surf2.coordinateSystem(), equalTo(CoordinateSystem.oneBased()));
assertThat(surf2.start(), equalTo(136_223_426));
assertThat(surf2.end(), equalTo(136_228_034));
// ID stuff
assertThat(surf2.accession(), equalTo("NCBIGene:6835"));
assertThat(surf2.symbol(), equalTo("SURF2"));
assertThat(surf2.id().hgncId().isPresent(), equalTo(true));
assertThat(surf2.id().hgncId().get(), equalTo("HGNC:11475"));
assertThat(surf2.id().ncbiGeneId().isPresent(), equalTo(true));
assertThat(surf2.id().ncbiGeneId().get(), equalTo("NCBIGene:6835"));
// Metadata
assertThat(surf2.biotype(), equalTo(Biotype.protein_coding));
assertThat(surf2.featureSource().isPresent(), equalTo(true));
assertThat(surf2.featureSource().get(), equalTo(FeatureSource.REFSEQ));
// Transcripts
assertThat(surf2.transcriptCount(), equalTo(2));
List<? extends RefseqTranscript> txs = surf2.transcriptStream()
.sorted(Comparator.comparing(Identified::accession))
.collect(Collectors.toList());
// - NM_001278928.2
RefseqTranscript first = txs.get(0);
assertThat(first.accession(), equalTo("NM_001278928.2"));
assertThat(first.symbol(), equalTo("surfeit 2, transcript variant 2"));
assertThat(first.id().ccdsId().isPresent(), equalTo(false));
assertThat(first.location(), equalTo(GenomicRegion.of(GRCH37.contigByName("9"), Strand.POSITIVE, CoordinateSystem.zeroBased(), 136_223_425, 136_228_034)));
assertThat(first.exons().size(), equalTo(6));
assertThat(first.evidence().isPresent(), equalTo(true));
assertThat(first.evidence().get(), equalTo(TranscriptEvidence.KNOWN));
assertThat(first.featureSource().isPresent(), equalTo(true));
assertThat(first.featureSource().get(), equalTo(FeatureSource.REFSEQ));
assertThat(first.biotype(), equalTo(Biotype.protein_coding));
assertThat(first.source(), equalTo(RefseqSource.BestRefSeq));
assertThat(first, instanceOf(CodingTranscript.class));
CodingTranscript firstCoding = (CodingTranscript) first;
assertThat(firstCoding.startCodon().startWithCoordinateSystem(CoordinateSystem.zeroBased()), equalTo(136_223_468));
assertThat(firstCoding.stopCodon().endWithCoordinateSystem(CoordinateSystem.zeroBased()), equalTo(136_228_015));
// - NM_017503.5
RefseqTranscript second = txs.get(1);
assertThat(second.accession(), equalTo("NM_017503.5"));
assertThat(second.symbol(), equalTo("surfeit 2, transcript variant 1"));
assertThat(second.id().ccdsId().isPresent(), equalTo(false));
assertThat(second.location(), equalTo(GenomicRegion.of(GRCH37.contigByName("9"), Strand.POSITIVE, CoordinateSystem.zeroBased(), 136_223_425, 136_228_034)));
assertThat(second.exons().size(), equalTo(6));
assertThat(second.evidence().isPresent(), equalTo(true));
assertThat(second.evidence().get(), equalTo(TranscriptEvidence.KNOWN));
assertThat(second.featureSource().isPresent(), equalTo(true));
assertThat(second.featureSource().get(), equalTo(FeatureSource.REFSEQ));
assertThat(second.biotype(), equalTo(Biotype.protein_coding));
assertThat(second.source(), equalTo(RefseqSource.BestRefSeq));
assertThat(second, instanceOf(CodingTranscript.class));
CodingTranscript secondCoding = (CodingTranscript) second;
assertThat(secondCoding.startCodon().startWithCoordinateSystem(CoordinateSystem.zeroBased()), equalTo(136_223_468));
assertThat(secondCoding.stopCodon().endWithCoordinateSystem(CoordinateSystem.zeroBased()), equalTo(136_228_015));
}
}
} | 50.728448 | 168 | 0.638372 |
e67b195444c3aa03d99c58b800a6f1492990f250 | 974 | package main.java;
import main.java.rsa.Rsa;
import java.math.BigInteger;
public class SpeedTest {
private static int numOfMeasurements = 5;
private static int testIncreaseSpeed = 3;
public static void main(String[] args) {
System.out.println("I am speed!");
long time;
Rsa rsa = new Rsa();
BigInteger N ;
BigInteger Next = BigInteger.valueOf(2);
StringBuilder row;
while (true) {
row = new StringBuilder();
Next = Next.multiply(BigInteger.valueOf(testIncreaseSpeed));
Next = Next.nextProbablePrime();
N = Next.multiply(Next.nextProbablePrime());
for (int i = 0; i < numOfMeasurements; i++) {
time = rsa.calcPQ(N);
row.append("\t");
row.append(time);
}
System.out.print(row);
System.out.print("\t\t");
System.out.println(N);
}
}
}
| 27.055556 | 72 | 0.545175 |
f3d4738d1196a6e28c63fcc675f42b89d9dfaf14 | 340 | package com.google.gwt.chrome.cookie;
/**
* Callback function called when cookie has been changed.
* @author Paweł Psztyć
*
*/
public interface ChromeCookieChangeCallback {
/**
* Cookie has been changed some way.
* See {@link ChromeCookie} for more informations.
* @param event
*/
void onChange( ChromeCookieChange event );
}
| 22.666667 | 57 | 0.720588 |
a9ce8c7675d301141e647dce81b6f86961dd37b4 | 68,785 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hive
operator|.
name|service
operator|.
name|rpc
operator|.
name|thrift
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|scheme
operator|.
name|IScheme
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|scheme
operator|.
name|SchemeFactory
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|scheme
operator|.
name|StandardScheme
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|scheme
operator|.
name|TupleScheme
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TTupleProtocol
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocolException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|EncodingUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|async
operator|.
name|AsyncMethodCallback
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|server
operator|.
name|AbstractNonblockingServer
operator|.
name|*
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashMap
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|EnumMap
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Set
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashSet
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|EnumSet
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Collections
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|BitSet
import|;
end_import
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|ByteBuffer
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Arrays
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|annotation
operator|.
name|Generated
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_class
annotation|@
name|SuppressWarnings
argument_list|(
block|{
literal|"cast"
block|,
literal|"rawtypes"
block|,
literal|"serial"
block|,
literal|"unchecked"
block|}
argument_list|)
annotation|@
name|Generated
argument_list|(
name|value
operator|=
literal|"Autogenerated by Thrift Compiler (0.9.3)"
argument_list|)
annotation|@
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|common
operator|.
name|classification
operator|.
name|InterfaceAudience
operator|.
name|Public
annotation|@
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|common
operator|.
name|classification
operator|.
name|InterfaceStability
operator|.
name|Stable
specifier|public
class|class
name|TStatus
implements|implements
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TBase
argument_list|<
name|TStatus
argument_list|,
name|TStatus
operator|.
name|_Fields
argument_list|>
implements|,
name|java
operator|.
name|io
operator|.
name|Serializable
implements|,
name|Cloneable
implements|,
name|Comparable
argument_list|<
name|TStatus
argument_list|>
block|{
specifier|private
specifier|static
specifier|final
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TStruct
name|STRUCT_DESC
init|=
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TStruct
argument_list|(
literal|"TStatus"
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TField
name|STATUS_CODE_FIELD_DESC
init|=
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TField
argument_list|(
literal|"statusCode"
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|I32
argument_list|,
operator|(
name|short
operator|)
literal|1
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TField
name|INFO_MESSAGES_FIELD_DESC
init|=
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TField
argument_list|(
literal|"infoMessages"
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|LIST
argument_list|,
operator|(
name|short
operator|)
literal|2
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TField
name|SQL_STATE_FIELD_DESC
init|=
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TField
argument_list|(
literal|"sqlState"
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|STRING
argument_list|,
operator|(
name|short
operator|)
literal|3
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TField
name|ERROR_CODE_FIELD_DESC
init|=
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TField
argument_list|(
literal|"errorCode"
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|I32
argument_list|,
operator|(
name|short
operator|)
literal|4
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TField
name|ERROR_MESSAGE_FIELD_DESC
init|=
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TField
argument_list|(
literal|"errorMessage"
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|STRING
argument_list|,
operator|(
name|short
operator|)
literal|5
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Map
argument_list|<
name|Class
argument_list|<
name|?
extends|extends
name|IScheme
argument_list|>
argument_list|,
name|SchemeFactory
argument_list|>
name|schemes
init|=
operator|new
name|HashMap
argument_list|<
name|Class
argument_list|<
name|?
extends|extends
name|IScheme
argument_list|>
argument_list|,
name|SchemeFactory
argument_list|>
argument_list|()
decl_stmt|;
static|static
block|{
name|schemes
operator|.
name|put
argument_list|(
name|StandardScheme
operator|.
name|class
argument_list|,
operator|new
name|TStatusStandardSchemeFactory
argument_list|()
argument_list|)
expr_stmt|;
name|schemes
operator|.
name|put
argument_list|(
name|TupleScheme
operator|.
name|class
argument_list|,
operator|new
name|TStatusTupleSchemeFactory
argument_list|()
argument_list|)
expr_stmt|;
block|}
specifier|private
name|TStatusCode
name|statusCode
decl_stmt|;
comment|// required
specifier|private
name|List
argument_list|<
name|String
argument_list|>
name|infoMessages
decl_stmt|;
comment|// optional
specifier|private
name|String
name|sqlState
decl_stmt|;
comment|// optional
specifier|private
name|int
name|errorCode
decl_stmt|;
comment|// optional
specifier|private
name|String
name|errorMessage
decl_stmt|;
comment|// optional
comment|/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
specifier|public
enum|enum
name|_Fields
implements|implements
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TFieldIdEnum
block|{
comment|/** * * @see TStatusCode */
name|STATUS_CODE
argument_list|(
operator|(
name|short
operator|)
literal|1
argument_list|,
literal|"statusCode"
argument_list|)
block|,
name|INFO_MESSAGES
argument_list|(
operator|(
name|short
operator|)
literal|2
argument_list|,
literal|"infoMessages"
argument_list|)
block|,
name|SQL_STATE
argument_list|(
operator|(
name|short
operator|)
literal|3
argument_list|,
literal|"sqlState"
argument_list|)
block|,
name|ERROR_CODE
argument_list|(
operator|(
name|short
operator|)
literal|4
argument_list|,
literal|"errorCode"
argument_list|)
block|,
name|ERROR_MESSAGE
argument_list|(
operator|(
name|short
operator|)
literal|5
argument_list|,
literal|"errorMessage"
argument_list|)
block|;
specifier|private
specifier|static
specifier|final
name|Map
argument_list|<
name|String
argument_list|,
name|_Fields
argument_list|>
name|byName
init|=
operator|new
name|HashMap
argument_list|<
name|String
argument_list|,
name|_Fields
argument_list|>
argument_list|()
decl_stmt|;
static|static
block|{
for|for
control|(
name|_Fields
name|field
range|:
name|EnumSet
operator|.
name|allOf
argument_list|(
name|_Fields
operator|.
name|class
argument_list|)
control|)
block|{
name|byName
operator|.
name|put
argument_list|(
name|field
operator|.
name|getFieldName
argument_list|()
argument_list|,
name|field
argument_list|)
expr_stmt|;
block|}
block|}
comment|/** * Find the _Fields constant that matches fieldId, or null if its not found. */
specifier|public
specifier|static
name|_Fields
name|findByThriftId
parameter_list|(
name|int
name|fieldId
parameter_list|)
block|{
switch|switch
condition|(
name|fieldId
condition|)
block|{
case|case
literal|1
case|:
comment|// STATUS_CODE
return|return
name|STATUS_CODE
return|;
case|case
literal|2
case|:
comment|// INFO_MESSAGES
return|return
name|INFO_MESSAGES
return|;
case|case
literal|3
case|:
comment|// SQL_STATE
return|return
name|SQL_STATE
return|;
case|case
literal|4
case|:
comment|// ERROR_CODE
return|return
name|ERROR_CODE
return|;
case|case
literal|5
case|:
comment|// ERROR_MESSAGE
return|return
name|ERROR_MESSAGE
return|;
default|default:
return|return
literal|null
return|;
block|}
block|}
comment|/** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */
specifier|public
specifier|static
name|_Fields
name|findByThriftIdOrThrow
parameter_list|(
name|int
name|fieldId
parameter_list|)
block|{
name|_Fields
name|fields
init|=
name|findByThriftId
argument_list|(
name|fieldId
argument_list|)
decl_stmt|;
if|if
condition|(
name|fields
operator|==
literal|null
condition|)
throw|throw
operator|new
name|IllegalArgumentException
argument_list|(
literal|"Field "
operator|+
name|fieldId
operator|+
literal|" doesn't exist!"
argument_list|)
throw|;
return|return
name|fields
return|;
block|}
comment|/** * Find the _Fields constant that matches name, or null if its not found. */
specifier|public
specifier|static
name|_Fields
name|findByName
parameter_list|(
name|String
name|name
parameter_list|)
block|{
return|return
name|byName
operator|.
name|get
argument_list|(
name|name
argument_list|)
return|;
block|}
specifier|private
specifier|final
name|short
name|_thriftId
decl_stmt|;
specifier|private
specifier|final
name|String
name|_fieldName
decl_stmt|;
name|_Fields
parameter_list|(
name|short
name|thriftId
parameter_list|,
name|String
name|fieldName
parameter_list|)
block|{
name|_thriftId
operator|=
name|thriftId
expr_stmt|;
name|_fieldName
operator|=
name|fieldName
expr_stmt|;
block|}
specifier|public
name|short
name|getThriftFieldId
parameter_list|()
block|{
return|return
name|_thriftId
return|;
block|}
specifier|public
name|String
name|getFieldName
parameter_list|()
block|{
return|return
name|_fieldName
return|;
block|}
block|}
comment|// isset id assignments
specifier|private
specifier|static
specifier|final
name|int
name|__ERRORCODE_ISSET_ID
init|=
literal|0
decl_stmt|;
specifier|private
name|byte
name|__isset_bitfield
init|=
literal|0
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|_Fields
name|optionals
index|[]
init|=
block|{
name|_Fields
operator|.
name|INFO_MESSAGES
block|,
name|_Fields
operator|.
name|SQL_STATE
block|,
name|_Fields
operator|.
name|ERROR_CODE
block|,
name|_Fields
operator|.
name|ERROR_MESSAGE
block|}
decl_stmt|;
specifier|public
specifier|static
specifier|final
name|Map
argument_list|<
name|_Fields
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldMetaData
argument_list|>
name|metaDataMap
decl_stmt|;
static|static
block|{
name|Map
argument_list|<
name|_Fields
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldMetaData
argument_list|>
name|tmpMap
init|=
operator|new
name|EnumMap
argument_list|<
name|_Fields
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldMetaData
argument_list|>
argument_list|(
name|_Fields
operator|.
name|class
argument_list|)
decl_stmt|;
name|tmpMap
operator|.
name|put
argument_list|(
name|_Fields
operator|.
name|STATUS_CODE
argument_list|,
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldMetaData
argument_list|(
literal|"statusCode"
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TFieldRequirementType
operator|.
name|REQUIRED
argument_list|,
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|EnumMetaData
argument_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|ENUM
argument_list|,
name|TStatusCode
operator|.
name|class
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
name|tmpMap
operator|.
name|put
argument_list|(
name|_Fields
operator|.
name|INFO_MESSAGES
argument_list|,
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldMetaData
argument_list|(
literal|"infoMessages"
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TFieldRequirementType
operator|.
name|OPTIONAL
argument_list|,
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|ListMetaData
argument_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|LIST
argument_list|,
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldValueMetaData
argument_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|STRING
argument_list|)
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
name|tmpMap
operator|.
name|put
argument_list|(
name|_Fields
operator|.
name|SQL_STATE
argument_list|,
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldMetaData
argument_list|(
literal|"sqlState"
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TFieldRequirementType
operator|.
name|OPTIONAL
argument_list|,
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldValueMetaData
argument_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|STRING
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
name|tmpMap
operator|.
name|put
argument_list|(
name|_Fields
operator|.
name|ERROR_CODE
argument_list|,
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldMetaData
argument_list|(
literal|"errorCode"
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TFieldRequirementType
operator|.
name|OPTIONAL
argument_list|,
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldValueMetaData
argument_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|I32
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
name|tmpMap
operator|.
name|put
argument_list|(
name|_Fields
operator|.
name|ERROR_MESSAGE
argument_list|,
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldMetaData
argument_list|(
literal|"errorMessage"
argument_list|,
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TFieldRequirementType
operator|.
name|OPTIONAL
argument_list|,
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldValueMetaData
argument_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|STRING
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
name|metaDataMap
operator|=
name|Collections
operator|.
name|unmodifiableMap
argument_list|(
name|tmpMap
argument_list|)
expr_stmt|;
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|meta_data
operator|.
name|FieldMetaData
operator|.
name|addStructMetaDataMap
argument_list|(
name|TStatus
operator|.
name|class
argument_list|,
name|metaDataMap
argument_list|)
expr_stmt|;
block|}
specifier|public
name|TStatus
parameter_list|()
block|{ }
specifier|public
name|TStatus
parameter_list|(
name|TStatusCode
name|statusCode
parameter_list|)
block|{
name|this
argument_list|()
expr_stmt|;
name|this
operator|.
name|statusCode
operator|=
name|statusCode
expr_stmt|;
block|}
comment|/** * Performs a deep copy on<i>other</i>. */
specifier|public
name|TStatus
parameter_list|(
name|TStatus
name|other
parameter_list|)
block|{
name|__isset_bitfield
operator|=
name|other
operator|.
name|__isset_bitfield
expr_stmt|;
if|if
condition|(
name|other
operator|.
name|isSetStatusCode
argument_list|()
condition|)
block|{
name|this
operator|.
name|statusCode
operator|=
name|other
operator|.
name|statusCode
expr_stmt|;
block|}
if|if
condition|(
name|other
operator|.
name|isSetInfoMessages
argument_list|()
condition|)
block|{
name|List
argument_list|<
name|String
argument_list|>
name|__this__infoMessages
init|=
operator|new
name|ArrayList
argument_list|<
name|String
argument_list|>
argument_list|(
name|other
operator|.
name|infoMessages
argument_list|)
decl_stmt|;
name|this
operator|.
name|infoMessages
operator|=
name|__this__infoMessages
expr_stmt|;
block|}
if|if
condition|(
name|other
operator|.
name|isSetSqlState
argument_list|()
condition|)
block|{
name|this
operator|.
name|sqlState
operator|=
name|other
operator|.
name|sqlState
expr_stmt|;
block|}
name|this
operator|.
name|errorCode
operator|=
name|other
operator|.
name|errorCode
expr_stmt|;
if|if
condition|(
name|other
operator|.
name|isSetErrorMessage
argument_list|()
condition|)
block|{
name|this
operator|.
name|errorMessage
operator|=
name|other
operator|.
name|errorMessage
expr_stmt|;
block|}
block|}
specifier|public
name|TStatus
name|deepCopy
parameter_list|()
block|{
return|return
operator|new
name|TStatus
argument_list|(
name|this
argument_list|)
return|;
block|}
annotation|@
name|Override
specifier|public
name|void
name|clear
parameter_list|()
block|{
name|this
operator|.
name|statusCode
operator|=
literal|null
expr_stmt|;
name|this
operator|.
name|infoMessages
operator|=
literal|null
expr_stmt|;
name|this
operator|.
name|sqlState
operator|=
literal|null
expr_stmt|;
name|setErrorCodeIsSet
argument_list|(
literal|false
argument_list|)
expr_stmt|;
name|this
operator|.
name|errorCode
operator|=
literal|0
expr_stmt|;
name|this
operator|.
name|errorMessage
operator|=
literal|null
expr_stmt|;
block|}
comment|/** * * @see TStatusCode */
specifier|public
name|TStatusCode
name|getStatusCode
parameter_list|()
block|{
return|return
name|this
operator|.
name|statusCode
return|;
block|}
comment|/** * * @see TStatusCode */
specifier|public
name|void
name|setStatusCode
parameter_list|(
name|TStatusCode
name|statusCode
parameter_list|)
block|{
name|this
operator|.
name|statusCode
operator|=
name|statusCode
expr_stmt|;
block|}
specifier|public
name|void
name|unsetStatusCode
parameter_list|()
block|{
name|this
operator|.
name|statusCode
operator|=
literal|null
expr_stmt|;
block|}
comment|/** Returns true if field statusCode is set (has been assigned a value) and false otherwise */
specifier|public
name|boolean
name|isSetStatusCode
parameter_list|()
block|{
return|return
name|this
operator|.
name|statusCode
operator|!=
literal|null
return|;
block|}
specifier|public
name|void
name|setStatusCodeIsSet
parameter_list|(
name|boolean
name|value
parameter_list|)
block|{
if|if
condition|(
operator|!
name|value
condition|)
block|{
name|this
operator|.
name|statusCode
operator|=
literal|null
expr_stmt|;
block|}
block|}
specifier|public
name|int
name|getInfoMessagesSize
parameter_list|()
block|{
return|return
operator|(
name|this
operator|.
name|infoMessages
operator|==
literal|null
operator|)
condition|?
literal|0
else|:
name|this
operator|.
name|infoMessages
operator|.
name|size
argument_list|()
return|;
block|}
specifier|public
name|java
operator|.
name|util
operator|.
name|Iterator
argument_list|<
name|String
argument_list|>
name|getInfoMessagesIterator
parameter_list|()
block|{
return|return
operator|(
name|this
operator|.
name|infoMessages
operator|==
literal|null
operator|)
condition|?
literal|null
else|:
name|this
operator|.
name|infoMessages
operator|.
name|iterator
argument_list|()
return|;
block|}
specifier|public
name|void
name|addToInfoMessages
parameter_list|(
name|String
name|elem
parameter_list|)
block|{
if|if
condition|(
name|this
operator|.
name|infoMessages
operator|==
literal|null
condition|)
block|{
name|this
operator|.
name|infoMessages
operator|=
operator|new
name|ArrayList
argument_list|<
name|String
argument_list|>
argument_list|()
expr_stmt|;
block|}
name|this
operator|.
name|infoMessages
operator|.
name|add
argument_list|(
name|elem
argument_list|)
expr_stmt|;
block|}
specifier|public
name|List
argument_list|<
name|String
argument_list|>
name|getInfoMessages
parameter_list|()
block|{
return|return
name|this
operator|.
name|infoMessages
return|;
block|}
specifier|public
name|void
name|setInfoMessages
parameter_list|(
name|List
argument_list|<
name|String
argument_list|>
name|infoMessages
parameter_list|)
block|{
name|this
operator|.
name|infoMessages
operator|=
name|infoMessages
expr_stmt|;
block|}
specifier|public
name|void
name|unsetInfoMessages
parameter_list|()
block|{
name|this
operator|.
name|infoMessages
operator|=
literal|null
expr_stmt|;
block|}
comment|/** Returns true if field infoMessages is set (has been assigned a value) and false otherwise */
specifier|public
name|boolean
name|isSetInfoMessages
parameter_list|()
block|{
return|return
name|this
operator|.
name|infoMessages
operator|!=
literal|null
return|;
block|}
specifier|public
name|void
name|setInfoMessagesIsSet
parameter_list|(
name|boolean
name|value
parameter_list|)
block|{
if|if
condition|(
operator|!
name|value
condition|)
block|{
name|this
operator|.
name|infoMessages
operator|=
literal|null
expr_stmt|;
block|}
block|}
specifier|public
name|String
name|getSqlState
parameter_list|()
block|{
return|return
name|this
operator|.
name|sqlState
return|;
block|}
specifier|public
name|void
name|setSqlState
parameter_list|(
name|String
name|sqlState
parameter_list|)
block|{
name|this
operator|.
name|sqlState
operator|=
name|sqlState
expr_stmt|;
block|}
specifier|public
name|void
name|unsetSqlState
parameter_list|()
block|{
name|this
operator|.
name|sqlState
operator|=
literal|null
expr_stmt|;
block|}
comment|/** Returns true if field sqlState is set (has been assigned a value) and false otherwise */
specifier|public
name|boolean
name|isSetSqlState
parameter_list|()
block|{
return|return
name|this
operator|.
name|sqlState
operator|!=
literal|null
return|;
block|}
specifier|public
name|void
name|setSqlStateIsSet
parameter_list|(
name|boolean
name|value
parameter_list|)
block|{
if|if
condition|(
operator|!
name|value
condition|)
block|{
name|this
operator|.
name|sqlState
operator|=
literal|null
expr_stmt|;
block|}
block|}
specifier|public
name|int
name|getErrorCode
parameter_list|()
block|{
return|return
name|this
operator|.
name|errorCode
return|;
block|}
specifier|public
name|void
name|setErrorCode
parameter_list|(
name|int
name|errorCode
parameter_list|)
block|{
name|this
operator|.
name|errorCode
operator|=
name|errorCode
expr_stmt|;
name|setErrorCodeIsSet
argument_list|(
literal|true
argument_list|)
expr_stmt|;
block|}
specifier|public
name|void
name|unsetErrorCode
parameter_list|()
block|{
name|__isset_bitfield
operator|=
name|EncodingUtils
operator|.
name|clearBit
argument_list|(
name|__isset_bitfield
argument_list|,
name|__ERRORCODE_ISSET_ID
argument_list|)
expr_stmt|;
block|}
comment|/** Returns true if field errorCode is set (has been assigned a value) and false otherwise */
specifier|public
name|boolean
name|isSetErrorCode
parameter_list|()
block|{
return|return
name|EncodingUtils
operator|.
name|testBit
argument_list|(
name|__isset_bitfield
argument_list|,
name|__ERRORCODE_ISSET_ID
argument_list|)
return|;
block|}
specifier|public
name|void
name|setErrorCodeIsSet
parameter_list|(
name|boolean
name|value
parameter_list|)
block|{
name|__isset_bitfield
operator|=
name|EncodingUtils
operator|.
name|setBit
argument_list|(
name|__isset_bitfield
argument_list|,
name|__ERRORCODE_ISSET_ID
argument_list|,
name|value
argument_list|)
expr_stmt|;
block|}
specifier|public
name|String
name|getErrorMessage
parameter_list|()
block|{
return|return
name|this
operator|.
name|errorMessage
return|;
block|}
specifier|public
name|void
name|setErrorMessage
parameter_list|(
name|String
name|errorMessage
parameter_list|)
block|{
name|this
operator|.
name|errorMessage
operator|=
name|errorMessage
expr_stmt|;
block|}
specifier|public
name|void
name|unsetErrorMessage
parameter_list|()
block|{
name|this
operator|.
name|errorMessage
operator|=
literal|null
expr_stmt|;
block|}
comment|/** Returns true if field errorMessage is set (has been assigned a value) and false otherwise */
specifier|public
name|boolean
name|isSetErrorMessage
parameter_list|()
block|{
return|return
name|this
operator|.
name|errorMessage
operator|!=
literal|null
return|;
block|}
specifier|public
name|void
name|setErrorMessageIsSet
parameter_list|(
name|boolean
name|value
parameter_list|)
block|{
if|if
condition|(
operator|!
name|value
condition|)
block|{
name|this
operator|.
name|errorMessage
operator|=
literal|null
expr_stmt|;
block|}
block|}
specifier|public
name|void
name|setFieldValue
parameter_list|(
name|_Fields
name|field
parameter_list|,
name|Object
name|value
parameter_list|)
block|{
switch|switch
condition|(
name|field
condition|)
block|{
case|case
name|STATUS_CODE
case|:
if|if
condition|(
name|value
operator|==
literal|null
condition|)
block|{
name|unsetStatusCode
argument_list|()
expr_stmt|;
block|}
else|else
block|{
name|setStatusCode
argument_list|(
operator|(
name|TStatusCode
operator|)
name|value
argument_list|)
expr_stmt|;
block|}
break|break;
case|case
name|INFO_MESSAGES
case|:
if|if
condition|(
name|value
operator|==
literal|null
condition|)
block|{
name|unsetInfoMessages
argument_list|()
expr_stmt|;
block|}
else|else
block|{
name|setInfoMessages
argument_list|(
operator|(
name|List
argument_list|<
name|String
argument_list|>
operator|)
name|value
argument_list|)
expr_stmt|;
block|}
break|break;
case|case
name|SQL_STATE
case|:
if|if
condition|(
name|value
operator|==
literal|null
condition|)
block|{
name|unsetSqlState
argument_list|()
expr_stmt|;
block|}
else|else
block|{
name|setSqlState
argument_list|(
operator|(
name|String
operator|)
name|value
argument_list|)
expr_stmt|;
block|}
break|break;
case|case
name|ERROR_CODE
case|:
if|if
condition|(
name|value
operator|==
literal|null
condition|)
block|{
name|unsetErrorCode
argument_list|()
expr_stmt|;
block|}
else|else
block|{
name|setErrorCode
argument_list|(
operator|(
name|Integer
operator|)
name|value
argument_list|)
expr_stmt|;
block|}
break|break;
case|case
name|ERROR_MESSAGE
case|:
if|if
condition|(
name|value
operator|==
literal|null
condition|)
block|{
name|unsetErrorMessage
argument_list|()
expr_stmt|;
block|}
else|else
block|{
name|setErrorMessage
argument_list|(
operator|(
name|String
operator|)
name|value
argument_list|)
expr_stmt|;
block|}
break|break;
block|}
block|}
specifier|public
name|Object
name|getFieldValue
parameter_list|(
name|_Fields
name|field
parameter_list|)
block|{
switch|switch
condition|(
name|field
condition|)
block|{
case|case
name|STATUS_CODE
case|:
return|return
name|getStatusCode
argument_list|()
return|;
case|case
name|INFO_MESSAGES
case|:
return|return
name|getInfoMessages
argument_list|()
return|;
case|case
name|SQL_STATE
case|:
return|return
name|getSqlState
argument_list|()
return|;
case|case
name|ERROR_CODE
case|:
return|return
name|getErrorCode
argument_list|()
return|;
case|case
name|ERROR_MESSAGE
case|:
return|return
name|getErrorMessage
argument_list|()
return|;
block|}
throw|throw
operator|new
name|IllegalStateException
argument_list|()
throw|;
block|}
comment|/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
specifier|public
name|boolean
name|isSet
parameter_list|(
name|_Fields
name|field
parameter_list|)
block|{
if|if
condition|(
name|field
operator|==
literal|null
condition|)
block|{
throw|throw
operator|new
name|IllegalArgumentException
argument_list|()
throw|;
block|}
switch|switch
condition|(
name|field
condition|)
block|{
case|case
name|STATUS_CODE
case|:
return|return
name|isSetStatusCode
argument_list|()
return|;
case|case
name|INFO_MESSAGES
case|:
return|return
name|isSetInfoMessages
argument_list|()
return|;
case|case
name|SQL_STATE
case|:
return|return
name|isSetSqlState
argument_list|()
return|;
case|case
name|ERROR_CODE
case|:
return|return
name|isSetErrorCode
argument_list|()
return|;
case|case
name|ERROR_MESSAGE
case|:
return|return
name|isSetErrorMessage
argument_list|()
return|;
block|}
throw|throw
operator|new
name|IllegalStateException
argument_list|()
throw|;
block|}
annotation|@
name|Override
specifier|public
name|boolean
name|equals
parameter_list|(
name|Object
name|that
parameter_list|)
block|{
if|if
condition|(
name|that
operator|==
literal|null
condition|)
return|return
literal|false
return|;
if|if
condition|(
name|that
operator|instanceof
name|TStatus
condition|)
return|return
name|this
operator|.
name|equals
argument_list|(
operator|(
name|TStatus
operator|)
name|that
argument_list|)
return|;
return|return
literal|false
return|;
block|}
specifier|public
name|boolean
name|equals
parameter_list|(
name|TStatus
name|that
parameter_list|)
block|{
if|if
condition|(
name|that
operator|==
literal|null
condition|)
return|return
literal|false
return|;
name|boolean
name|this_present_statusCode
init|=
literal|true
operator|&&
name|this
operator|.
name|isSetStatusCode
argument_list|()
decl_stmt|;
name|boolean
name|that_present_statusCode
init|=
literal|true
operator|&&
name|that
operator|.
name|isSetStatusCode
argument_list|()
decl_stmt|;
if|if
condition|(
name|this_present_statusCode
operator|||
name|that_present_statusCode
condition|)
block|{
if|if
condition|(
operator|!
operator|(
name|this_present_statusCode
operator|&&
name|that_present_statusCode
operator|)
condition|)
return|return
literal|false
return|;
if|if
condition|(
operator|!
name|this
operator|.
name|statusCode
operator|.
name|equals
argument_list|(
name|that
operator|.
name|statusCode
argument_list|)
condition|)
return|return
literal|false
return|;
block|}
name|boolean
name|this_present_infoMessages
init|=
literal|true
operator|&&
name|this
operator|.
name|isSetInfoMessages
argument_list|()
decl_stmt|;
name|boolean
name|that_present_infoMessages
init|=
literal|true
operator|&&
name|that
operator|.
name|isSetInfoMessages
argument_list|()
decl_stmt|;
if|if
condition|(
name|this_present_infoMessages
operator|||
name|that_present_infoMessages
condition|)
block|{
if|if
condition|(
operator|!
operator|(
name|this_present_infoMessages
operator|&&
name|that_present_infoMessages
operator|)
condition|)
return|return
literal|false
return|;
if|if
condition|(
operator|!
name|this
operator|.
name|infoMessages
operator|.
name|equals
argument_list|(
name|that
operator|.
name|infoMessages
argument_list|)
condition|)
return|return
literal|false
return|;
block|}
name|boolean
name|this_present_sqlState
init|=
literal|true
operator|&&
name|this
operator|.
name|isSetSqlState
argument_list|()
decl_stmt|;
name|boolean
name|that_present_sqlState
init|=
literal|true
operator|&&
name|that
operator|.
name|isSetSqlState
argument_list|()
decl_stmt|;
if|if
condition|(
name|this_present_sqlState
operator|||
name|that_present_sqlState
condition|)
block|{
if|if
condition|(
operator|!
operator|(
name|this_present_sqlState
operator|&&
name|that_present_sqlState
operator|)
condition|)
return|return
literal|false
return|;
if|if
condition|(
operator|!
name|this
operator|.
name|sqlState
operator|.
name|equals
argument_list|(
name|that
operator|.
name|sqlState
argument_list|)
condition|)
return|return
literal|false
return|;
block|}
name|boolean
name|this_present_errorCode
init|=
literal|true
operator|&&
name|this
operator|.
name|isSetErrorCode
argument_list|()
decl_stmt|;
name|boolean
name|that_present_errorCode
init|=
literal|true
operator|&&
name|that
operator|.
name|isSetErrorCode
argument_list|()
decl_stmt|;
if|if
condition|(
name|this_present_errorCode
operator|||
name|that_present_errorCode
condition|)
block|{
if|if
condition|(
operator|!
operator|(
name|this_present_errorCode
operator|&&
name|that_present_errorCode
operator|)
condition|)
return|return
literal|false
return|;
if|if
condition|(
name|this
operator|.
name|errorCode
operator|!=
name|that
operator|.
name|errorCode
condition|)
return|return
literal|false
return|;
block|}
name|boolean
name|this_present_errorMessage
init|=
literal|true
operator|&&
name|this
operator|.
name|isSetErrorMessage
argument_list|()
decl_stmt|;
name|boolean
name|that_present_errorMessage
init|=
literal|true
operator|&&
name|that
operator|.
name|isSetErrorMessage
argument_list|()
decl_stmt|;
if|if
condition|(
name|this_present_errorMessage
operator|||
name|that_present_errorMessage
condition|)
block|{
if|if
condition|(
operator|!
operator|(
name|this_present_errorMessage
operator|&&
name|that_present_errorMessage
operator|)
condition|)
return|return
literal|false
return|;
if|if
condition|(
operator|!
name|this
operator|.
name|errorMessage
operator|.
name|equals
argument_list|(
name|that
operator|.
name|errorMessage
argument_list|)
condition|)
return|return
literal|false
return|;
block|}
return|return
literal|true
return|;
block|}
annotation|@
name|Override
specifier|public
name|int
name|hashCode
parameter_list|()
block|{
name|List
argument_list|<
name|Object
argument_list|>
name|list
init|=
operator|new
name|ArrayList
argument_list|<
name|Object
argument_list|>
argument_list|()
decl_stmt|;
name|boolean
name|present_statusCode
init|=
literal|true
operator|&&
operator|(
name|isSetStatusCode
argument_list|()
operator|)
decl_stmt|;
name|list
operator|.
name|add
argument_list|(
name|present_statusCode
argument_list|)
expr_stmt|;
if|if
condition|(
name|present_statusCode
condition|)
name|list
operator|.
name|add
argument_list|(
name|statusCode
operator|.
name|getValue
argument_list|()
argument_list|)
expr_stmt|;
name|boolean
name|present_infoMessages
init|=
literal|true
operator|&&
operator|(
name|isSetInfoMessages
argument_list|()
operator|)
decl_stmt|;
name|list
operator|.
name|add
argument_list|(
name|present_infoMessages
argument_list|)
expr_stmt|;
if|if
condition|(
name|present_infoMessages
condition|)
name|list
operator|.
name|add
argument_list|(
name|infoMessages
argument_list|)
expr_stmt|;
name|boolean
name|present_sqlState
init|=
literal|true
operator|&&
operator|(
name|isSetSqlState
argument_list|()
operator|)
decl_stmt|;
name|list
operator|.
name|add
argument_list|(
name|present_sqlState
argument_list|)
expr_stmt|;
if|if
condition|(
name|present_sqlState
condition|)
name|list
operator|.
name|add
argument_list|(
name|sqlState
argument_list|)
expr_stmt|;
name|boolean
name|present_errorCode
init|=
literal|true
operator|&&
operator|(
name|isSetErrorCode
argument_list|()
operator|)
decl_stmt|;
name|list
operator|.
name|add
argument_list|(
name|present_errorCode
argument_list|)
expr_stmt|;
if|if
condition|(
name|present_errorCode
condition|)
name|list
operator|.
name|add
argument_list|(
name|errorCode
argument_list|)
expr_stmt|;
name|boolean
name|present_errorMessage
init|=
literal|true
operator|&&
operator|(
name|isSetErrorMessage
argument_list|()
operator|)
decl_stmt|;
name|list
operator|.
name|add
argument_list|(
name|present_errorMessage
argument_list|)
expr_stmt|;
if|if
condition|(
name|present_errorMessage
condition|)
name|list
operator|.
name|add
argument_list|(
name|errorMessage
argument_list|)
expr_stmt|;
return|return
name|list
operator|.
name|hashCode
argument_list|()
return|;
block|}
annotation|@
name|Override
specifier|public
name|int
name|compareTo
parameter_list|(
name|TStatus
name|other
parameter_list|)
block|{
if|if
condition|(
operator|!
name|getClass
argument_list|()
operator|.
name|equals
argument_list|(
name|other
operator|.
name|getClass
argument_list|()
argument_list|)
condition|)
block|{
return|return
name|getClass
argument_list|()
operator|.
name|getName
argument_list|()
operator|.
name|compareTo
argument_list|(
name|other
operator|.
name|getClass
argument_list|()
operator|.
name|getName
argument_list|()
argument_list|)
return|;
block|}
name|int
name|lastComparison
init|=
literal|0
decl_stmt|;
name|lastComparison
operator|=
name|Boolean
operator|.
name|valueOf
argument_list|(
name|isSetStatusCode
argument_list|()
argument_list|)
operator|.
name|compareTo
argument_list|(
name|other
operator|.
name|isSetStatusCode
argument_list|()
argument_list|)
expr_stmt|;
if|if
condition|(
name|lastComparison
operator|!=
literal|0
condition|)
block|{
return|return
name|lastComparison
return|;
block|}
if|if
condition|(
name|isSetStatusCode
argument_list|()
condition|)
block|{
name|lastComparison
operator|=
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TBaseHelper
operator|.
name|compareTo
argument_list|(
name|this
operator|.
name|statusCode
argument_list|,
name|other
operator|.
name|statusCode
argument_list|)
expr_stmt|;
if|if
condition|(
name|lastComparison
operator|!=
literal|0
condition|)
block|{
return|return
name|lastComparison
return|;
block|}
block|}
name|lastComparison
operator|=
name|Boolean
operator|.
name|valueOf
argument_list|(
name|isSetInfoMessages
argument_list|()
argument_list|)
operator|.
name|compareTo
argument_list|(
name|other
operator|.
name|isSetInfoMessages
argument_list|()
argument_list|)
expr_stmt|;
if|if
condition|(
name|lastComparison
operator|!=
literal|0
condition|)
block|{
return|return
name|lastComparison
return|;
block|}
if|if
condition|(
name|isSetInfoMessages
argument_list|()
condition|)
block|{
name|lastComparison
operator|=
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TBaseHelper
operator|.
name|compareTo
argument_list|(
name|this
operator|.
name|infoMessages
argument_list|,
name|other
operator|.
name|infoMessages
argument_list|)
expr_stmt|;
if|if
condition|(
name|lastComparison
operator|!=
literal|0
condition|)
block|{
return|return
name|lastComparison
return|;
block|}
block|}
name|lastComparison
operator|=
name|Boolean
operator|.
name|valueOf
argument_list|(
name|isSetSqlState
argument_list|()
argument_list|)
operator|.
name|compareTo
argument_list|(
name|other
operator|.
name|isSetSqlState
argument_list|()
argument_list|)
expr_stmt|;
if|if
condition|(
name|lastComparison
operator|!=
literal|0
condition|)
block|{
return|return
name|lastComparison
return|;
block|}
if|if
condition|(
name|isSetSqlState
argument_list|()
condition|)
block|{
name|lastComparison
operator|=
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TBaseHelper
operator|.
name|compareTo
argument_list|(
name|this
operator|.
name|sqlState
argument_list|,
name|other
operator|.
name|sqlState
argument_list|)
expr_stmt|;
if|if
condition|(
name|lastComparison
operator|!=
literal|0
condition|)
block|{
return|return
name|lastComparison
return|;
block|}
block|}
name|lastComparison
operator|=
name|Boolean
operator|.
name|valueOf
argument_list|(
name|isSetErrorCode
argument_list|()
argument_list|)
operator|.
name|compareTo
argument_list|(
name|other
operator|.
name|isSetErrorCode
argument_list|()
argument_list|)
expr_stmt|;
if|if
condition|(
name|lastComparison
operator|!=
literal|0
condition|)
block|{
return|return
name|lastComparison
return|;
block|}
if|if
condition|(
name|isSetErrorCode
argument_list|()
condition|)
block|{
name|lastComparison
operator|=
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TBaseHelper
operator|.
name|compareTo
argument_list|(
name|this
operator|.
name|errorCode
argument_list|,
name|other
operator|.
name|errorCode
argument_list|)
expr_stmt|;
if|if
condition|(
name|lastComparison
operator|!=
literal|0
condition|)
block|{
return|return
name|lastComparison
return|;
block|}
block|}
name|lastComparison
operator|=
name|Boolean
operator|.
name|valueOf
argument_list|(
name|isSetErrorMessage
argument_list|()
argument_list|)
operator|.
name|compareTo
argument_list|(
name|other
operator|.
name|isSetErrorMessage
argument_list|()
argument_list|)
expr_stmt|;
if|if
condition|(
name|lastComparison
operator|!=
literal|0
condition|)
block|{
return|return
name|lastComparison
return|;
block|}
if|if
condition|(
name|isSetErrorMessage
argument_list|()
condition|)
block|{
name|lastComparison
operator|=
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TBaseHelper
operator|.
name|compareTo
argument_list|(
name|this
operator|.
name|errorMessage
argument_list|,
name|other
operator|.
name|errorMessage
argument_list|)
expr_stmt|;
if|if
condition|(
name|lastComparison
operator|!=
literal|0
condition|)
block|{
return|return
name|lastComparison
return|;
block|}
block|}
return|return
literal|0
return|;
block|}
specifier|public
name|_Fields
name|fieldForId
parameter_list|(
name|int
name|fieldId
parameter_list|)
block|{
return|return
name|_Fields
operator|.
name|findByThriftId
argument_list|(
name|fieldId
argument_list|)
return|;
block|}
specifier|public
name|void
name|read
parameter_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocol
name|iprot
parameter_list|)
throws|throws
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TException
block|{
name|schemes
operator|.
name|get
argument_list|(
name|iprot
operator|.
name|getScheme
argument_list|()
argument_list|)
operator|.
name|getScheme
argument_list|()
operator|.
name|read
argument_list|(
name|iprot
argument_list|,
name|this
argument_list|)
expr_stmt|;
block|}
specifier|public
name|void
name|write
parameter_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocol
name|oprot
parameter_list|)
throws|throws
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TException
block|{
name|schemes
operator|.
name|get
argument_list|(
name|oprot
operator|.
name|getScheme
argument_list|()
argument_list|)
operator|.
name|getScheme
argument_list|()
operator|.
name|write
argument_list|(
name|oprot
argument_list|,
name|this
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
specifier|public
name|String
name|toString
parameter_list|()
block|{
name|StringBuilder
name|sb
init|=
operator|new
name|StringBuilder
argument_list|(
literal|"TStatus("
argument_list|)
decl_stmt|;
name|boolean
name|first
init|=
literal|true
decl_stmt|;
name|sb
operator|.
name|append
argument_list|(
literal|"statusCode:"
argument_list|)
expr_stmt|;
if|if
condition|(
name|this
operator|.
name|statusCode
operator|==
literal|null
condition|)
block|{
name|sb
operator|.
name|append
argument_list|(
literal|"null"
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|sb
operator|.
name|append
argument_list|(
name|this
operator|.
name|statusCode
argument_list|)
expr_stmt|;
block|}
name|first
operator|=
literal|false
expr_stmt|;
if|if
condition|(
name|isSetInfoMessages
argument_list|()
condition|)
block|{
if|if
condition|(
operator|!
name|first
condition|)
name|sb
operator|.
name|append
argument_list|(
literal|", "
argument_list|)
expr_stmt|;
name|sb
operator|.
name|append
argument_list|(
literal|"infoMessages:"
argument_list|)
expr_stmt|;
if|if
condition|(
name|this
operator|.
name|infoMessages
operator|==
literal|null
condition|)
block|{
name|sb
operator|.
name|append
argument_list|(
literal|"null"
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|sb
operator|.
name|append
argument_list|(
name|this
operator|.
name|infoMessages
argument_list|)
expr_stmt|;
block|}
name|first
operator|=
literal|false
expr_stmt|;
block|}
if|if
condition|(
name|isSetSqlState
argument_list|()
condition|)
block|{
if|if
condition|(
operator|!
name|first
condition|)
name|sb
operator|.
name|append
argument_list|(
literal|", "
argument_list|)
expr_stmt|;
name|sb
operator|.
name|append
argument_list|(
literal|"sqlState:"
argument_list|)
expr_stmt|;
if|if
condition|(
name|this
operator|.
name|sqlState
operator|==
literal|null
condition|)
block|{
name|sb
operator|.
name|append
argument_list|(
literal|"null"
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|sb
operator|.
name|append
argument_list|(
name|this
operator|.
name|sqlState
argument_list|)
expr_stmt|;
block|}
name|first
operator|=
literal|false
expr_stmt|;
block|}
if|if
condition|(
name|isSetErrorCode
argument_list|()
condition|)
block|{
if|if
condition|(
operator|!
name|first
condition|)
name|sb
operator|.
name|append
argument_list|(
literal|", "
argument_list|)
expr_stmt|;
name|sb
operator|.
name|append
argument_list|(
literal|"errorCode:"
argument_list|)
expr_stmt|;
name|sb
operator|.
name|append
argument_list|(
name|this
operator|.
name|errorCode
argument_list|)
expr_stmt|;
name|first
operator|=
literal|false
expr_stmt|;
block|}
if|if
condition|(
name|isSetErrorMessage
argument_list|()
condition|)
block|{
if|if
condition|(
operator|!
name|first
condition|)
name|sb
operator|.
name|append
argument_list|(
literal|", "
argument_list|)
expr_stmt|;
name|sb
operator|.
name|append
argument_list|(
literal|"errorMessage:"
argument_list|)
expr_stmt|;
if|if
condition|(
name|this
operator|.
name|errorMessage
operator|==
literal|null
condition|)
block|{
name|sb
operator|.
name|append
argument_list|(
literal|"null"
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|sb
operator|.
name|append
argument_list|(
name|this
operator|.
name|errorMessage
argument_list|)
expr_stmt|;
block|}
name|first
operator|=
literal|false
expr_stmt|;
block|}
name|sb
operator|.
name|append
argument_list|(
literal|")"
argument_list|)
expr_stmt|;
return|return
name|sb
operator|.
name|toString
argument_list|()
return|;
block|}
specifier|public
name|void
name|validate
parameter_list|()
throws|throws
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TException
block|{
comment|// check for required fields
if|if
condition|(
operator|!
name|isSetStatusCode
argument_list|()
condition|)
block|{
throw|throw
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocolException
argument_list|(
literal|"Required field 'statusCode' is unset! Struct:"
operator|+
name|toString
argument_list|()
argument_list|)
throw|;
block|}
comment|// check for sub-struct validity
block|}
specifier|private
name|void
name|writeObject
parameter_list|(
name|java
operator|.
name|io
operator|.
name|ObjectOutputStream
name|out
parameter_list|)
throws|throws
name|java
operator|.
name|io
operator|.
name|IOException
block|{
try|try
block|{
name|write
argument_list|(
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TCompactProtocol
argument_list|(
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|transport
operator|.
name|TIOStreamTransport
argument_list|(
name|out
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TException
name|te
parameter_list|)
block|{
throw|throw
operator|new
name|java
operator|.
name|io
operator|.
name|IOException
argument_list|(
name|te
argument_list|)
throw|;
block|}
block|}
specifier|private
name|void
name|readObject
parameter_list|(
name|java
operator|.
name|io
operator|.
name|ObjectInputStream
name|in
parameter_list|)
throws|throws
name|java
operator|.
name|io
operator|.
name|IOException
throws|,
name|ClassNotFoundException
block|{
try|try
block|{
comment|// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
name|__isset_bitfield
operator|=
literal|0
expr_stmt|;
name|read
argument_list|(
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TCompactProtocol
argument_list|(
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|transport
operator|.
name|TIOStreamTransport
argument_list|(
name|in
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TException
name|te
parameter_list|)
block|{
throw|throw
operator|new
name|java
operator|.
name|io
operator|.
name|IOException
argument_list|(
name|te
argument_list|)
throw|;
block|}
block|}
specifier|private
specifier|static
class|class
name|TStatusStandardSchemeFactory
implements|implements
name|SchemeFactory
block|{
specifier|public
name|TStatusStandardScheme
name|getScheme
parameter_list|()
block|{
return|return
operator|new
name|TStatusStandardScheme
argument_list|()
return|;
block|}
block|}
specifier|private
specifier|static
class|class
name|TStatusStandardScheme
extends|extends
name|StandardScheme
argument_list|<
name|TStatus
argument_list|>
block|{
specifier|public
name|void
name|read
parameter_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocol
name|iprot
parameter_list|,
name|TStatus
name|struct
parameter_list|)
throws|throws
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TException
block|{
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TField
name|schemeField
decl_stmt|;
name|iprot
operator|.
name|readStructBegin
argument_list|()
expr_stmt|;
while|while
condition|(
literal|true
condition|)
block|{
name|schemeField
operator|=
name|iprot
operator|.
name|readFieldBegin
argument_list|()
expr_stmt|;
if|if
condition|(
name|schemeField
operator|.
name|type
operator|==
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|STOP
condition|)
block|{
break|break;
block|}
switch|switch
condition|(
name|schemeField
operator|.
name|id
condition|)
block|{
case|case
literal|1
case|:
comment|// STATUS_CODE
if|if
condition|(
name|schemeField
operator|.
name|type
operator|==
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|I32
condition|)
block|{
name|struct
operator|.
name|statusCode
operator|=
name|org
operator|.
name|apache
operator|.
name|hive
operator|.
name|service
operator|.
name|rpc
operator|.
name|thrift
operator|.
name|TStatusCode
operator|.
name|findByValue
argument_list|(
name|iprot
operator|.
name|readI32
argument_list|()
argument_list|)
expr_stmt|;
name|struct
operator|.
name|setStatusCodeIsSet
argument_list|(
literal|true
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocolUtil
operator|.
name|skip
argument_list|(
name|iprot
argument_list|,
name|schemeField
operator|.
name|type
argument_list|)
expr_stmt|;
block|}
break|break;
case|case
literal|2
case|:
comment|// INFO_MESSAGES
if|if
condition|(
name|schemeField
operator|.
name|type
operator|==
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|LIST
condition|)
block|{
block|{
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TList
name|_list134
init|=
name|iprot
operator|.
name|readListBegin
argument_list|()
decl_stmt|;
name|struct
operator|.
name|infoMessages
operator|=
operator|new
name|ArrayList
argument_list|<
name|String
argument_list|>
argument_list|(
name|_list134
operator|.
name|size
argument_list|)
expr_stmt|;
name|String
name|_elem135
decl_stmt|;
for|for
control|(
name|int
name|_i136
init|=
literal|0
init|;
name|_i136
operator|<
name|_list134
operator|.
name|size
condition|;
operator|++
name|_i136
control|)
block|{
name|_elem135
operator|=
name|iprot
operator|.
name|readString
argument_list|()
expr_stmt|;
name|struct
operator|.
name|infoMessages
operator|.
name|add
argument_list|(
name|_elem135
argument_list|)
expr_stmt|;
block|}
name|iprot
operator|.
name|readListEnd
argument_list|()
expr_stmt|;
block|}
name|struct
operator|.
name|setInfoMessagesIsSet
argument_list|(
literal|true
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocolUtil
operator|.
name|skip
argument_list|(
name|iprot
argument_list|,
name|schemeField
operator|.
name|type
argument_list|)
expr_stmt|;
block|}
break|break;
case|case
literal|3
case|:
comment|// SQL_STATE
if|if
condition|(
name|schemeField
operator|.
name|type
operator|==
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|STRING
condition|)
block|{
name|struct
operator|.
name|sqlState
operator|=
name|iprot
operator|.
name|readString
argument_list|()
expr_stmt|;
name|struct
operator|.
name|setSqlStateIsSet
argument_list|(
literal|true
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocolUtil
operator|.
name|skip
argument_list|(
name|iprot
argument_list|,
name|schemeField
operator|.
name|type
argument_list|)
expr_stmt|;
block|}
break|break;
case|case
literal|4
case|:
comment|// ERROR_CODE
if|if
condition|(
name|schemeField
operator|.
name|type
operator|==
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|I32
condition|)
block|{
name|struct
operator|.
name|errorCode
operator|=
name|iprot
operator|.
name|readI32
argument_list|()
expr_stmt|;
name|struct
operator|.
name|setErrorCodeIsSet
argument_list|(
literal|true
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocolUtil
operator|.
name|skip
argument_list|(
name|iprot
argument_list|,
name|schemeField
operator|.
name|type
argument_list|)
expr_stmt|;
block|}
break|break;
case|case
literal|5
case|:
comment|// ERROR_MESSAGE
if|if
condition|(
name|schemeField
operator|.
name|type
operator|==
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|STRING
condition|)
block|{
name|struct
operator|.
name|errorMessage
operator|=
name|iprot
operator|.
name|readString
argument_list|()
expr_stmt|;
name|struct
operator|.
name|setErrorMessageIsSet
argument_list|(
literal|true
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocolUtil
operator|.
name|skip
argument_list|(
name|iprot
argument_list|,
name|schemeField
operator|.
name|type
argument_list|)
expr_stmt|;
block|}
break|break;
default|default:
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocolUtil
operator|.
name|skip
argument_list|(
name|iprot
argument_list|,
name|schemeField
operator|.
name|type
argument_list|)
expr_stmt|;
block|}
name|iprot
operator|.
name|readFieldEnd
argument_list|()
expr_stmt|;
block|}
name|iprot
operator|.
name|readStructEnd
argument_list|()
expr_stmt|;
name|struct
operator|.
name|validate
argument_list|()
expr_stmt|;
block|}
specifier|public
name|void
name|write
parameter_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocol
name|oprot
parameter_list|,
name|TStatus
name|struct
parameter_list|)
throws|throws
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TException
block|{
name|struct
operator|.
name|validate
argument_list|()
expr_stmt|;
name|oprot
operator|.
name|writeStructBegin
argument_list|(
name|STRUCT_DESC
argument_list|)
expr_stmt|;
if|if
condition|(
name|struct
operator|.
name|statusCode
operator|!=
literal|null
condition|)
block|{
name|oprot
operator|.
name|writeFieldBegin
argument_list|(
name|STATUS_CODE_FIELD_DESC
argument_list|)
expr_stmt|;
name|oprot
operator|.
name|writeI32
argument_list|(
name|struct
operator|.
name|statusCode
operator|.
name|getValue
argument_list|()
argument_list|)
expr_stmt|;
name|oprot
operator|.
name|writeFieldEnd
argument_list|()
expr_stmt|;
block|}
if|if
condition|(
name|struct
operator|.
name|infoMessages
operator|!=
literal|null
condition|)
block|{
if|if
condition|(
name|struct
operator|.
name|isSetInfoMessages
argument_list|()
condition|)
block|{
name|oprot
operator|.
name|writeFieldBegin
argument_list|(
name|INFO_MESSAGES_FIELD_DESC
argument_list|)
expr_stmt|;
block|{
name|oprot
operator|.
name|writeListBegin
argument_list|(
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TList
argument_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|STRING
argument_list|,
name|struct
operator|.
name|infoMessages
operator|.
name|size
argument_list|()
argument_list|)
argument_list|)
expr_stmt|;
for|for
control|(
name|String
name|_iter137
range|:
name|struct
operator|.
name|infoMessages
control|)
block|{
name|oprot
operator|.
name|writeString
argument_list|(
name|_iter137
argument_list|)
expr_stmt|;
block|}
name|oprot
operator|.
name|writeListEnd
argument_list|()
expr_stmt|;
block|}
name|oprot
operator|.
name|writeFieldEnd
argument_list|()
expr_stmt|;
block|}
block|}
if|if
condition|(
name|struct
operator|.
name|sqlState
operator|!=
literal|null
condition|)
block|{
if|if
condition|(
name|struct
operator|.
name|isSetSqlState
argument_list|()
condition|)
block|{
name|oprot
operator|.
name|writeFieldBegin
argument_list|(
name|SQL_STATE_FIELD_DESC
argument_list|)
expr_stmt|;
name|oprot
operator|.
name|writeString
argument_list|(
name|struct
operator|.
name|sqlState
argument_list|)
expr_stmt|;
name|oprot
operator|.
name|writeFieldEnd
argument_list|()
expr_stmt|;
block|}
block|}
if|if
condition|(
name|struct
operator|.
name|isSetErrorCode
argument_list|()
condition|)
block|{
name|oprot
operator|.
name|writeFieldBegin
argument_list|(
name|ERROR_CODE_FIELD_DESC
argument_list|)
expr_stmt|;
name|oprot
operator|.
name|writeI32
argument_list|(
name|struct
operator|.
name|errorCode
argument_list|)
expr_stmt|;
name|oprot
operator|.
name|writeFieldEnd
argument_list|()
expr_stmt|;
block|}
if|if
condition|(
name|struct
operator|.
name|errorMessage
operator|!=
literal|null
condition|)
block|{
if|if
condition|(
name|struct
operator|.
name|isSetErrorMessage
argument_list|()
condition|)
block|{
name|oprot
operator|.
name|writeFieldBegin
argument_list|(
name|ERROR_MESSAGE_FIELD_DESC
argument_list|)
expr_stmt|;
name|oprot
operator|.
name|writeString
argument_list|(
name|struct
operator|.
name|errorMessage
argument_list|)
expr_stmt|;
name|oprot
operator|.
name|writeFieldEnd
argument_list|()
expr_stmt|;
block|}
block|}
name|oprot
operator|.
name|writeFieldStop
argument_list|()
expr_stmt|;
name|oprot
operator|.
name|writeStructEnd
argument_list|()
expr_stmt|;
block|}
block|}
specifier|private
specifier|static
class|class
name|TStatusTupleSchemeFactory
implements|implements
name|SchemeFactory
block|{
specifier|public
name|TStatusTupleScheme
name|getScheme
parameter_list|()
block|{
return|return
operator|new
name|TStatusTupleScheme
argument_list|()
return|;
block|}
block|}
specifier|private
specifier|static
class|class
name|TStatusTupleScheme
extends|extends
name|TupleScheme
argument_list|<
name|TStatus
argument_list|>
block|{
annotation|@
name|Override
specifier|public
name|void
name|write
parameter_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocol
name|prot
parameter_list|,
name|TStatus
name|struct
parameter_list|)
throws|throws
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TException
block|{
name|TTupleProtocol
name|oprot
init|=
operator|(
name|TTupleProtocol
operator|)
name|prot
decl_stmt|;
name|oprot
operator|.
name|writeI32
argument_list|(
name|struct
operator|.
name|statusCode
operator|.
name|getValue
argument_list|()
argument_list|)
expr_stmt|;
name|BitSet
name|optionals
init|=
operator|new
name|BitSet
argument_list|()
decl_stmt|;
if|if
condition|(
name|struct
operator|.
name|isSetInfoMessages
argument_list|()
condition|)
block|{
name|optionals
operator|.
name|set
argument_list|(
literal|0
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|struct
operator|.
name|isSetSqlState
argument_list|()
condition|)
block|{
name|optionals
operator|.
name|set
argument_list|(
literal|1
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|struct
operator|.
name|isSetErrorCode
argument_list|()
condition|)
block|{
name|optionals
operator|.
name|set
argument_list|(
literal|2
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|struct
operator|.
name|isSetErrorMessage
argument_list|()
condition|)
block|{
name|optionals
operator|.
name|set
argument_list|(
literal|3
argument_list|)
expr_stmt|;
block|}
name|oprot
operator|.
name|writeBitSet
argument_list|(
name|optionals
argument_list|,
literal|4
argument_list|)
expr_stmt|;
if|if
condition|(
name|struct
operator|.
name|isSetInfoMessages
argument_list|()
condition|)
block|{
block|{
name|oprot
operator|.
name|writeI32
argument_list|(
name|struct
operator|.
name|infoMessages
operator|.
name|size
argument_list|()
argument_list|)
expr_stmt|;
for|for
control|(
name|String
name|_iter138
range|:
name|struct
operator|.
name|infoMessages
control|)
block|{
name|oprot
operator|.
name|writeString
argument_list|(
name|_iter138
argument_list|)
expr_stmt|;
block|}
block|}
block|}
if|if
condition|(
name|struct
operator|.
name|isSetSqlState
argument_list|()
condition|)
block|{
name|oprot
operator|.
name|writeString
argument_list|(
name|struct
operator|.
name|sqlState
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|struct
operator|.
name|isSetErrorCode
argument_list|()
condition|)
block|{
name|oprot
operator|.
name|writeI32
argument_list|(
name|struct
operator|.
name|errorCode
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|struct
operator|.
name|isSetErrorMessage
argument_list|()
condition|)
block|{
name|oprot
operator|.
name|writeString
argument_list|(
name|struct
operator|.
name|errorMessage
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Override
specifier|public
name|void
name|read
parameter_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TProtocol
name|prot
parameter_list|,
name|TStatus
name|struct
parameter_list|)
throws|throws
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|TException
block|{
name|TTupleProtocol
name|iprot
init|=
operator|(
name|TTupleProtocol
operator|)
name|prot
decl_stmt|;
name|struct
operator|.
name|statusCode
operator|=
name|org
operator|.
name|apache
operator|.
name|hive
operator|.
name|service
operator|.
name|rpc
operator|.
name|thrift
operator|.
name|TStatusCode
operator|.
name|findByValue
argument_list|(
name|iprot
operator|.
name|readI32
argument_list|()
argument_list|)
expr_stmt|;
name|struct
operator|.
name|setStatusCodeIsSet
argument_list|(
literal|true
argument_list|)
expr_stmt|;
name|BitSet
name|incoming
init|=
name|iprot
operator|.
name|readBitSet
argument_list|(
literal|4
argument_list|)
decl_stmt|;
if|if
condition|(
name|incoming
operator|.
name|get
argument_list|(
literal|0
argument_list|)
condition|)
block|{
block|{
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TList
name|_list139
init|=
operator|new
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TList
argument_list|(
name|org
operator|.
name|apache
operator|.
name|thrift
operator|.
name|protocol
operator|.
name|TType
operator|.
name|STRING
argument_list|,
name|iprot
operator|.
name|readI32
argument_list|()
argument_list|)
decl_stmt|;
name|struct
operator|.
name|infoMessages
operator|=
operator|new
name|ArrayList
argument_list|<
name|String
argument_list|>
argument_list|(
name|_list139
operator|.
name|size
argument_list|)
expr_stmt|;
name|String
name|_elem140
decl_stmt|;
for|for
control|(
name|int
name|_i141
init|=
literal|0
init|;
name|_i141
operator|<
name|_list139
operator|.
name|size
condition|;
operator|++
name|_i141
control|)
block|{
name|_elem140
operator|=
name|iprot
operator|.
name|readString
argument_list|()
expr_stmt|;
name|struct
operator|.
name|infoMessages
operator|.
name|add
argument_list|(
name|_elem140
argument_list|)
expr_stmt|;
block|}
block|}
name|struct
operator|.
name|setInfoMessagesIsSet
argument_list|(
literal|true
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|incoming
operator|.
name|get
argument_list|(
literal|1
argument_list|)
condition|)
block|{
name|struct
operator|.
name|sqlState
operator|=
name|iprot
operator|.
name|readString
argument_list|()
expr_stmt|;
name|struct
operator|.
name|setSqlStateIsSet
argument_list|(
literal|true
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|incoming
operator|.
name|get
argument_list|(
literal|2
argument_list|)
condition|)
block|{
name|struct
operator|.
name|errorCode
operator|=
name|iprot
operator|.
name|readI32
argument_list|()
expr_stmt|;
name|struct
operator|.
name|setErrorCodeIsSet
argument_list|(
literal|true
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|incoming
operator|.
name|get
argument_list|(
literal|3
argument_list|)
condition|)
block|{
name|struct
operator|.
name|errorMessage
operator|=
name|iprot
operator|.
name|readString
argument_list|()
expr_stmt|;
name|struct
operator|.
name|setErrorMessageIsSet
argument_list|(
literal|true
argument_list|)
expr_stmt|;
block|}
block|}
block|}
block|}
end_class
end_unit
| 13.064577 | 145 | 0.796467 |
47a77ad5af1e4872832272584c9e6cc62c217ae9 | 3,415 | /*
* Copyright (c) 2015-2020, Virgil Security, Inc.
*
* Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* (3) Neither the name of virgil nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.virgilsecurity.demo.purekit.server.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.virgilsecurity.demo.purekit.server.model.http.ResetData;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ResetControllerTest extends RestDocTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
void reset() throws Exception {
ResetData body = this.restTemplate.postForObject("/reset", null, ResetData.class);
assertNotNull(body);
assertEquals(1, body.getPatients().size());
assertEquals(1, body.getPhysicians().size());
assertEquals(1, body.getLaboratories().size());
assertEquals(2, body.getLabTests().size());
assertEquals(2, body.getPrescriptions().size());
this.mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.POST, "/reset"))
.andDo(document("reset", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())));
}
}
| 46.148649 | 99 | 0.787994 |
0ce8a97be1fb49b12556a7bc0ba185d51e83d6ed | 2,550 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.cxf.spring;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBusFactory;
import org.springframework.beans.factory.SmartFactoryBean;
/**
* This factoryBean which can help user to choice CXF components that he wants bus to load
* without needing to import bunch of CXF packages in OSGi bundle, as the SpringBusFactory
* will try to load the bus extensions with the CXF bundle classloader.
* You can set the CXF extensions files with ; as the separator to create a bus.
*
* NOTE: when you set the includeDefaultBus value to be false, you should aware that the CXF bus
* will automatically load all the extension in CXF 2.4.x by default.
* You can still specify the spring extension file in the cfgFiles list and it will override
* the extensions which is load by CXF bus.
*/
public class SpringBusFactoryBean implements SmartFactoryBean<Bus> {
private String[] cfgFiles;
private boolean includeDefaultBus;
private SpringBusFactory bf;
public Bus getObject() throws Exception {
bf = new SpringBusFactory();
if (cfgFiles != null) {
return bf.createBus(cfgFiles, includeDefaultBus);
} else {
return bf.createBus();
}
}
public Class<?> getObjectType() {
return Bus.class;
}
public void setCfgFiles(String cfgFiles) {
this.cfgFiles = cfgFiles.split(";");
}
public void setIncludeDefaultBus(boolean includeDefaultBus) {
this.includeDefaultBus = includeDefaultBus;
}
public boolean isSingleton() {
return true;
}
public boolean isEagerInit() {
return true;
}
public boolean isPrototype() {
return false;
}
}
| 34.931507 | 96 | 0.712941 |
a8761d5cfa20f1fcb0005dc158a720046e98c39b | 257 | package sizebay.catalog.client.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ImportationRules {
String rules;
}
| 15.117647 | 37 | 0.824903 |
a969b3441418926601e94d4e9b28b22ea6df369b | 1,893 | package old.divideconquer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.Parameterized.Parameter;
import java.util.Arrays;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
/**
* Created by xd031 on 2017/8/2.
*/
@RunWith(Parameterized.class)
public class BinarySearchTest {
public static final int[][][] objects = {
{new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, new int[]{5}, new int[]{4}},
{new int[]{2, 3, 4, 5, 6, 7, 8}, new int[]{5}, new int[]{3}},
{new int[]{1}, new int[]{1}, new int[]{0}},
{new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, new int[]{10}, new int[]{-1}},
{new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, new int[]{-2}, new int[]{-1}},
};
@Parameter(0)
public int[] sortArr;
@Parameter(1)
public int[] target;
@Parameter(2)
public int[] result;
private BinarySearch demo;
@Parameters(name = "{index}:binarySearchWithDivideConquer({0},{1})=={2}")
public static Iterable<Object[]> test() {
return Arrays.asList(objects);
}
@Before
public void setUp() {
demo = new BinarySearch();
}
@Test
public void binarySearchWithDivideConquer() throws Exception {
assertThat(demo.binarySearchWithDivideConquer(sortArr, target[0], 0, sortArr.length - 1), is(result[0]));
}
@Test
public void binarySearch() throws Exception {
assertThat(demo.binarySearch(sortArr, target[0], 0, sortArr.length - 1), is(result[0]));
}
/**
* For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
* the contiguous subarray [4,-1,2,1] has the largest sum = 6.
*
* @throws Exception
*/
@Test
public void maxSubArray() throws Exception {
int[] input = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4};
assertThat(demo.maxSubArray(input), is(6));
}
}
| 27.434783 | 109 | 0.633386 |
7a924de42242d6437dff563607c942c8af1c79cb | 344 | package br.com.criaproposta.demo.servicosterceiro.criacartao.associacarteira;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface AssociaCarteiraRepository extends JpaRepository<AssociaCarteira, Long> {
boolean existsByCarteira(Carteira carteira);
}
| 28.666667 | 89 | 0.857558 |
348c9cbc02096dcd26d426f9851423ae271e454f | 9,838 | package com.intact.rx.core.rxrepo.writer;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import com.intact.rx.api.RxConfig;
import com.intact.rx.api.RxContext;
import com.intact.rx.api.RxObserver;
import com.intact.rx.api.Subscription;
import com.intact.rx.api.cache.CacheHandle;
import com.intact.rx.api.cache.RxCache;
import com.intact.rx.api.cache.RxCacheAccess;
import com.intact.rx.api.command.*;
import com.intact.rx.api.rxrepo.RxRepositoryWriter;
import com.intact.rx.api.subject.RxSubjectCombi;
import com.intact.rx.core.rxcache.Streamer;
import com.intact.rx.core.rxcache.StreamerBuilder;
import com.intact.rx.core.rxcache.controller.ActsControllerConfig;
import com.intact.rx.core.rxcache.controller.ActsControllerPolicy;
import com.intact.rx.core.rxcircuit.breaker.CircuitBreakerPolicy;
import com.intact.rx.core.rxcircuit.breaker.CircuitId;
import com.intact.rx.core.rxcircuit.rate.RateLimiterId;
import com.intact.rx.core.rxcircuit.rate.RateLimiterPolicy;
import com.intact.rx.core.rxrepo.RepositoryRequestStatus;
public class RepositoryStreamWriter<K, V> implements RxRepositoryWriter<K, V>, RxObserver<Map<K, V>> {
private final CacheHandle cacheHandle;
private final RxContext rxContext;
private final RxConfig rxConfig;
private final Strategy2<Boolean, K, V> pusher;
// Local state
private final AtomicReference<Streamer> lastStreamer;
private final RxSubjectCombi<Map<K, V>> subject;
public RepositoryStreamWriter(CacheHandle cacheHandle, RxContext rxContext, RxConfig rxConfig, Strategy2<Boolean, K, V> pusher) {
this.cacheHandle = cacheHandle;
this.rxConfig = rxConfig;
this.pusher = pusher;
this.rxContext = rxContext;
this.lastStreamer = new AtomicReference<>(null);
this.subject = new RxSubjectCombi<>();
}
@Override
public RxCache<K, V> cache() {
return RxCacheAccess.cache(cacheHandle, rxConfig.actPolicy.getCachePolicy());
}
@Override
public boolean put(K key, V value, long msecs) {
return computeAndGetPrivate(key, () -> value, msecs).isPresent();
}
@Override
public boolean putAndRemoveLocal(K key, V value, long msecs) {
return putPusherAndGetPrivate(
key,
() -> {
if (pusher.perform(key, value)) {
cache().take(key);
}
return Collections.emptyMap();
},
msecs).isPresent();
}
@Override
public Optional<V> putAndGet(K key, V value, long msecs) {
return computeAndGetPrivate(key, () -> value, msecs);
}
@Override
public Optional<V> preComputeAndPut(K key, V value, final Strategy3<V, K, V, Optional<V>> preComputer, long msecs) {
Strategy0<V> computer = () -> {
Optional<V> cachedValue = cache().read(key);
return preComputer.perform(key, value, cachedValue);
};
return computeAndGetPrivate(key, computer, msecs);
}
@Override
public Optional<V> putAndPostCompute(K key, V value, final Strategy4<V, Boolean, K, V, Optional<V>> postComputer, long msecs) {
Strategy0<Map<K, V>> cacher = () -> {
Boolean isAccepted = pusher.perform(key, value);
Optional<V> cachedValue = cache().read(key);
V postComputedValue = postComputer.perform(isAccepted, key, value, cachedValue);
return Map.of(key, postComputedValue);
};
return putPusherAndGetPrivate(key, cacher, msecs);
}
@Override
public boolean compute(K key, Strategy0<V> computer, long msecs) {
return computeAndGetPrivate(key, computer, msecs).isPresent();
}
@Override
public boolean putIfAbsent(K key, V value, long msecs) {
Optional<V> previous = cache().read(key);
boolean absent = !previous.isPresent();
return absent && computeAndGetPrivate(key, () -> value, msecs).isPresent();
}
@Override
public boolean putIfPresent(K key, V value, long msecs) {
Optional<V> previous = cache().read(key);
boolean present = previous.isPresent();
return present && computeAndGetPrivate(key, () -> value, msecs).isPresent();
}
@Override
public boolean putIfNotEqual(K key, V value, long msecs) {
Optional<V> previous = cache().read(key);
boolean notEqual = !previous.isPresent() || !Objects.equals(previous.get(), value);
return notEqual && computeAndGetPrivate(key, () -> value, msecs).isPresent();
}
@Override
public boolean putIf(Strategy2<Boolean, K, V> criterion, K key, V value, long msecs) {
return criterion.perform(key, value) && computeAndGetPrivate(key, () -> value, msecs).isPresent();
}
@Override
public RepositoryRequestStatus lastRequestStatus() {
Streamer streamer = lastStreamer.get();
return streamer != null
? RepositoryRequestStatus.create(streamer.getStatus())
: RepositoryRequestStatus.no();
}
// -----------------------------------------------------------
// Callback functions
// -----------------------------------------------------------
@Override
public RxRepositoryWriter<K, V> connect(RxObserver<Map<K, V>> observer) {
subject.connect(observer);
return this;
}
@Override
public RxRepositoryWriter<K, V> disconnect(RxObserver<Map<K, V>> observer) {
subject.disconnect(observer);
return this;
}
@Override
public RxRepositoryWriter<K, V> disconnectAll() {
subject.disconnectAll();
return this;
}
@Override
public RxRepositoryWriter<K, V> onCompleteDo(VoidStrategy0 completedFunction) {
subject.onCompleteDo(completedFunction);
return this;
}
@Override
public RxRepositoryWriter<K, V> onErrorDo(VoidStrategy1<Throwable> errorFunction) {
subject.onErrorDo(errorFunction);
return this;
}
@Override
public RxRepositoryWriter<K, V> onNextDo(VoidStrategy1<Map<K, V>> nextFunction) {
subject.onNextDo(nextFunction);
return this;
}
@Override
public RxRepositoryWriter<K, V> onSubscribeDo(VoidStrategy1<Subscription> subscribeFunction) {
subject.onSubscribeDo(subscribeFunction);
return this;
}
// -----------------------------------------------------------
// RxObserver<Map<K, V>>
// -----------------------------------------------------------
@Override
public void onComplete() {
subject.onComplete();
}
@Override
public void onError(Throwable throwable) {
subject.onError(throwable);
}
@Override
public void onNext(Map<K, V> value) {
subject.onNext(value);
}
@Override
public void onSubscribe(Subscription subscription) {
subject.onSubscribe(subscription);
}
// -----------------------------------------------------------
// private implementation
// -----------------------------------------------------------
private Optional<V> computeAndGetPrivate(K key, Strategy0<V> computer, long msecs) {
if (key == null || computer == null) {
return Optional.empty();
}
Streamer streamer =
createStreamBuilder()
.sequential()
.set(cacheHandle, key, computer, pusher)
.done();
lastStreamer.set(streamer);
boolean success = streamer.subscribe()
.waitFor(msecs)
.isSuccess();
return success ?
streamer.computeIfAbsent(cacheHandle, key, 1)
: Optional.empty();
}
private Optional<V> putPusherAndGetPrivate(K key, Strategy0<Map<K, V>> pusher, long msecs) {
if (key == null || pusher == null) {
return Optional.empty();
}
Streamer streamer =
createStreamBuilder()
.sequential()
.get(cacheHandle, pusher)
.done();
lastStreamer.set(streamer);
boolean success = streamer.subscribe()
.waitFor(msecs)
.isSuccess();
return success ?
streamer.computeIfAbsent(cacheHandle, key, 1)
: Optional.empty();
}
private StreamerBuilder createStreamBuilder() {
return Streamer
.forCache(cacheHandle.getMasterCacheId())
.withExecuteAround(rxContext)
.withThreadPoolConfig(rxConfig.rxThreadPoolConfig)
.withControllerConfig(
ActsControllerConfig.builder()
.withActsControllerPolicy(ActsControllerPolicy.from(rxConfig.actsControllerConfig.getActsControllerPolicy(), CircuitBreakerPolicy.unlimited, RateLimiterPolicy.unlimited))
.withCircuitBreakerId(CircuitId.none())
.withRateLimiterId(RateLimiterId.none())
.build())
.withActPolicy(rxConfig.actPolicy)
.withCommandConfig(rxConfig.commandConfig)
.withFaultPolicy(rxConfig.faultPolicy)
.withDomainCacheId(rxConfig.domainCacheId)
.build()
.onSubscribeDo(this::onSubscribe)
.onNextDo(this::onNext, CacheHandle.<V>findCachedType(cacheHandle).orElseThrow(() -> new IllegalStateException("CacheHandle without class information")))
.onErrorDo(this::onError)
.onCompleteDo(this::onComplete);
}
}
| 34.640845 | 202 | 0.604289 |
2ab4a58679678282d177448ed5b7655e5798aa04 | 182 | package powercrystals.minefactoryreloaded.api;
import net.minecraft.entity.player.EntityPlayer;
public interface ILiquidDrinkHandler
{
public void onDrink(EntityPlayer player);
}
| 20.222222 | 48 | 0.840659 |
3db3934add0dcd2e97aa2479f1093773f1425ccd | 837 | package com.checkshow.entity;
import com.checkshow.entity.constant.GenreEnum;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
/**
* Genre Entity
* id : PK
* comment : 설명
* detailComment : 자세한 설명
*/
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Genre {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Short id;
@Column(nullable = false)
private String code;
@Column(nullable = false)
private String detailCode;
@Builder
public Genre(Short id, String code, String detailCode) {
this.id = id;
this.code = code;
this.detailCode = detailCode;
}
public GenreEnum toEnum() {
return GenreEnum.findById(this.id);
}
}
| 19.022727 | 60 | 0.684588 |
fd0a79fe4c9e78a3db6da0ace601e5a35bac2037 | 733 | // a good explanation: https://leetcode.com/problems/range-addition/discuss/84225/Detailed-explanation-if-you-don't-understand-especially-%22put-negative-inc-at-endIndex+1%22
class Solution {
// improve from naive O(kn) to O(k+n)
public int[] getModifiedArray(int length, int[][] updates) {
int[] res = new int[length];
for(int[] update : updates) {
int value = update[2];
int start = update[0];
int end = update[1];
res[start] += value;
if(end < length - 1) res[end + 1] -= value;
}
int sum = 0;
for(int i = 0; i < length; i++) {
sum += res[i];
res[i] = sum;
}
return res;
}
}
| 30.541667 | 174 | 0.526603 |
565cd158ed7ab4e88c3e65adb232d2e67fa810d3 | 2,500 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package talitakumi.servicios;
import com.kcreativa.printer.DirectPrintToPrinter;
import java.io.IOException;
import java.util.Date;
import javax.persistence.EntityManager;
import org.apache.log4j.Logger;
import talitakumi.engine.framework.DataParameter;
import talitakumi.framework.Sesion;
import talitakumi.model.core.Usuarios;
import talitakumi.services.AbstractService;
/**
*
* @author rupertus
*/
public class ImprimirTicketDeControl implements AbstractService {
private Logger logger;
private Long numtick;
public void setEntityManager(EntityManager em) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void setLogger(Logger logger) {
this.logger = logger;
}
@Override
public void setParameters(Object o) {
DataParameter dp = (DataParameter) o;
numtick = (Long) dp.get("numtick");
}
@Override
public Object invoke() {
boolean b = false;
try {
b = imprimirTicket();
b = true;
} catch (IOException ex) {
logger.error(ex);
}
return(b);
}
@Override
public Object getResultado() {
throw new UnsupportedOperationException("Not supported yet.");
}
public boolean imprimirTicket() throws IOException {
boolean result;
result = true;
Usuarios u = (Usuarios) Sesion.getVariableEntorno("usuario");
DirectPrintToPrinter dp = new DirectPrintToPrinter("lpt1:");
dp.openDevice();
dp.writeln(" ");
dp.writeln(" ");
dp.writeln(" ");
dp.write((char)14);
dp.writeln("TICKET DE CONTROL");
dp.write((char)14);
dp.write((char)15);
dp.writeln("Gaston Moratorio RUT 214438560011");
dp.write((char)18);
dp.writeln(" ");
dp.writeln("Funcionario : " + u.getUsuario());
dp.writeln(" ");
dp.writeln("F/H " + new Date());
dp.writeln(" ");
dp.writeln("TICKETS " + numtick);
dp.writeln(" ");
dp.writeln("--------------------------------");
dp.writeln(" ");
dp.writeln(" ");
dp.writeln(" ");
dp.writeln(" ");
dp.writeln(" ");
dp.writeln(" ");
dp.write((char)27);
dp.write((char)105);
dp.closeDevice();
return(result);
}
}
| 23.148148 | 70 | 0.5816 |
b554222cab84539d39aa1b2b12b23878f632710b | 6,321 | package com.park.bean;
import java.io.*;
import java.util.*;
//user_feedback
@SuppressWarnings({"serial"})
public class User_feedback implements Cloneable , Serializable{
//public static String[] carrays ={"id","ui_id","content","ctime","utime","note","type","pi_id","area_code","pi_name","pda_id"};
public long id;//bigint(20) 主键ID
public long ui_id;//bigint(20) 用户主键ID
public String content="";//varchar(255) 反馈信息
public Date ctime=new Date();//datetime 创建时间
public Date utime=new Date();//datetime 更新时间
public String note="";//varchar(100) 备注
public int type;//int(11) 反馈来源(0:app用户反馈1:PDA管理人反馈2:道闸管理人反馈)
public long pi_id;//bigint(20) 停车场主键ID
public String area_code="";//varchar(30) 地址区域编码
public String pi_name="";//varchar(100) 停车场名称
public long pda_id;//bigint(20) PDA设备表的主键ID
public long getId(){
return id;
}
public void setId(long value){
this.id= value;
}
public long getUi_id(){
return ui_id;
}
public void setUi_id(long value){
this.ui_id= value;
}
public String getContent(){
return content;
}
public void setContent(String value){
if(value == null){
value = "";
}
this.content= value;
}
public Date getCtime(){
return ctime;
}
public void setCtime(Date value){
if(value == null){
value = new Date();
}
this.ctime= value;
}
public Date getUtime(){
return utime;
}
public void setUtime(Date value){
if(value == null){
value = new Date();
}
this.utime= value;
}
public String getNote(){
return note;
}
public void setNote(String value){
if(value == null){
value = "";
}
this.note= value;
}
public int getType(){
return type;
}
public void setType(int value){
this.type= value;
}
public long getPi_id(){
return pi_id;
}
public void setPi_id(long value){
this.pi_id= value;
}
public String getArea_code(){
return area_code;
}
public void setArea_code(String value){
if(value == null){
value = "";
}
this.area_code= value;
}
public String getPi_name(){
return pi_name;
}
public void setPi_name(String value){
if(value == null){
value = "";
}
this.pi_name= value;
}
public long getPda_id(){
return pda_id;
}
public void setPda_id(long value){
this.pda_id= value;
}
public static User_feedback newUser_feedback(long id, long ui_id, String content, Date ctime, Date utime, String note, int type, long pi_id, String area_code, String pi_name, long pda_id) {
User_feedback ret = new User_feedback();
ret.setId(id);
ret.setUi_id(ui_id);
ret.setContent(content);
ret.setCtime(ctime);
ret.setUtime(utime);
ret.setNote(note);
ret.setType(type);
ret.setPi_id(pi_id);
ret.setArea_code(area_code);
ret.setPi_name(pi_name);
ret.setPda_id(pda_id);
return ret;
}
public void assignment(User_feedback user_feedback) {
long id = user_feedback.getId();
long ui_id = user_feedback.getUi_id();
String content = user_feedback.getContent();
Date ctime = user_feedback.getCtime();
Date utime = user_feedback.getUtime();
String note = user_feedback.getNote();
int type = user_feedback.getType();
long pi_id = user_feedback.getPi_id();
String area_code = user_feedback.getArea_code();
String pi_name = user_feedback.getPi_name();
long pda_id = user_feedback.getPda_id();
this.setId(id);
this.setUi_id(ui_id);
this.setContent(content);
this.setCtime(ctime);
this.setUtime(utime);
this.setNote(note);
this.setType(type);
this.setPi_id(pi_id);
this.setArea_code(area_code);
this.setPi_name(pi_name);
this.setPda_id(pda_id);
}
@SuppressWarnings("unused")
public static void getUser_feedback(User_feedback user_feedback ){
long id = user_feedback.getId();
long ui_id = user_feedback.getUi_id();
String content = user_feedback.getContent();
Date ctime = user_feedback.getCtime();
Date utime = user_feedback.getUtime();
String note = user_feedback.getNote();
int type = user_feedback.getType();
long pi_id = user_feedback.getPi_id();
String area_code = user_feedback.getArea_code();
String pi_name = user_feedback.getPi_name();
long pda_id = user_feedback.getPda_id();
}
public Map<String,Object> toMap(){
return toEnMap(this);
}
public static Map<String,Object> toEnMap(User_feedback user_feedback){
long id = user_feedback.getId();
long ui_id = user_feedback.getUi_id();
String content = user_feedback.getContent();
Date ctime = user_feedback.getCtime();
Date utime = user_feedback.getUtime();
String note = user_feedback.getNote();
int type = user_feedback.getType();
long pi_id = user_feedback.getPi_id();
String area_code = user_feedback.getArea_code();
String pi_name = user_feedback.getPi_name();
long pda_id = user_feedback.getPda_id();
Map<String,Object> _ret = new HashMap<String,Object>();
_ret.put("id",id);
_ret.put("ui_id",ui_id);
_ret.put("content",content);
_ret.put("ctime",ctime);
_ret.put("utime",utime);
_ret.put("note",note);
_ret.put("com/park/type",type);
_ret.put("pi_id",pi_id);
_ret.put("area_code",area_code);
_ret.put("pi_name",pi_name);
_ret.put("pda_id",pda_id);
return _ret;
}
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
public User_feedback clone2(){
try{
return (User_feedback) this.clone();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| 26.670886 | 193 | 0.591995 |
722c19e47ecfc057fd36988999aa716e0738f299 | 1,440 | package documents;
/**
* This class describes audio and video materials of library system.
*
* @author Anastasia Minakova
* @see Document
*/
public class AudioVideoMaterial extends Document {
/**
* Initialize new audio/video.
*
* @param Title Title.
* @param Authors Authors.
* @param IsAllowedForStudents Student allowance.
* @param NumberOfCopies Count of copies.
* @param IsReference Reference status.
* @param Price Price.
* @param KeyWords Search keywords.
*/
public AudioVideoMaterial(String Title, String Authors, boolean IsAllowedForStudents, int NumberOfCopies, boolean IsReference, double Price, String KeyWords) {
super(Title, Authors, IsAllowedForStudents, NumberOfCopies, IsReference, Price, KeyWords);
setType("av");
}
/**
* Get this audio/video in string notation.
*
* @return String with audio/video description.
*/
public String toString() {
return ("Id: " + this.getID() + "\n" +
"Title: " + this.getTitle() + "\n" +
"Authors: " + this.getAuthors() + "\n" +
"Allowed for students: " + this.isAllowedForStudents() + "\n" +
"Number of copies: " + this.getNumberOfCopies() + "\n" +
"This is reference book: " + this.isReference() + "\n" +
"Price: " + this.getPrice() + "\n" +
"KeyWords: " + this.getKeyWords() + "\n");
}
@Override
public String getType() {
return "av";
}
}
| 30.638298 | 160 | 0.631944 |
a8c2bad4318a6a2e5efb21ed43d498fc2d2a30cf | 2,719 | /*******************************************************************************
* Copyright 2018 T Mobile, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package com.tmobile.cloud.awsrules.s3;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.tmobile.cloud.constants.PacmanRuleConstants;
import com.tmobile.pacman.commons.PacmanSdkConstants;
import com.tmobile.pacman.commons.rule.RuleResult;
/**
* Purpose: This test checks for s3 bucket containing web-site configuration.
*
* Author: pavankumarchaitanya
*
* Reviewers: Kamal, Kanchana
*
* Modified Date: April 11th, 2019
*
*/
public class S3HostsWebsiteRuleTest {
@Test
public void testExecute() {
Map<String, String> ruleParam = new HashMap<>();
Map<String, String> resourceAttributes = new HashMap<>();
S3HostsWebsiteRule s3HostsWebsiteRule = new S3HostsWebsiteRule();
resourceAttributes.put(PacmanSdkConstants.RESOURCE_ID, "test-resource-id");
resourceAttributes.put(PacmanRuleConstants.WEB_SITE_CONFIGURATION, "true");
ruleParam.put("executionId", "test");
ruleParam.put(PacmanSdkConstants.RULE_ID, "rule-id");
RuleResult ruleResult = s3HostsWebsiteRule.execute(ruleParam, resourceAttributes);
assertTrue(ruleResult.getStatus().equals(PacmanSdkConstants.STATUS_FAILURE));
}
@Test
public void testExecuteNoWebsiteConfiguration() {
Map<String, String> ruleParam = new HashMap<>();
Map<String, String> resourceAttributes = new HashMap<>();
S3HostsWebsiteRule s3HostsWebsiteRule = new S3HostsWebsiteRule();
resourceAttributes.put(PacmanSdkConstants.RESOURCE_ID, "test-resource-id");
resourceAttributes.put(PacmanRuleConstants.WEB_SITE_CONFIGURATION, "false");
ruleParam.put("executionId", "test");
ruleParam.put(PacmanSdkConstants.RULE_ID, "rule-id");
RuleResult ruleResult = s3HostsWebsiteRule.execute(ruleParam, resourceAttributes);
assertTrue(ruleResult.getStatus().equals(PacmanSdkConstants.STATUS_SUCCESS));
}
} | 39.405797 | 85 | 0.706142 |
2285252fdfc5ad5492f5e9980f36cdee851dd495 | 2,597 | package com.devonfw.tools.ide.logging;
/**
* Simple wrapper to print out to console and logger.
*/
public class Output {
private static final String BANNER = "***********************************************************";
private static final Output INSTANCE = new Output();
/**
* Print {@link #info(String) info} surrounded with a banner.
*
* @param message the message text/template.
* @param args the optional arguments to fill into the message.
*/
public void banner(String message, Object... args) {
info(BANNER);
info(message, args);
info(BANNER);
}
/**
* Print the message to console and log.
*
* @param message the message text/template.
* @param args the optional arguments to fill into the message.
*/
public void info(String message, Object... args) {
info(String.format(message, args));
}
/**
* Print the message to console and log.
*
* @param message the plain message.
*/
public void info(String message) {
System.out.println(message);
Log.info(message);
}
/**
* Log debug message.
*
* @param message the plain message.
*/
public void debug(String message) {
Log.debug(message);
}
/**
* Print the message as warning to console and log.
*
* @param message the message text/template.
* @param args the optional arguments to fill into the message.
*/
public void warn(String message, Object... args) {
warn(String.format(message, args));
}
/**
* Print the message as warning to console and log.
*
* @param message the plain message.
*/
public void warn(String message) {
System.out.println("WARNING: " + message);
Log.warn(message);
}
/**
* Print the error to console and log.
*
* @param e the {@link Exception}.
*/
public void err(Exception e) {
err(e.toString(), e);
}
/**
* Print the message as error to console and log.
*
* @param message the message text/template.
* @param args the optional arguments to fill into the message.
*/
public void err(String message, Object... args) {
err(String.format(message, args), (Exception) null);
}
/**
* Print the message as error to console and log.
*
* @param message the plain message.
* @param e the {@link Exception} or {@code null} for none.
*/
public void err(String message, Exception e) {
System.out.println("ERROR: " + message);
Log.err(message, e);
}
/**
* @return get the instance of {@link Output}.
*/
public static Output get() {
return INSTANCE;
}
}
| 21.46281 | 101 | 0.61494 |
7962bfdce9ec189e6ac36ef4bbef231409f61e93 | 11,339 | package ch.ethz.infk.pps.zeph.benchmark.macro.e2e.config;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
public class E2EConfig {
private BenchmarkType benchmarkType;
private String experimentId;
private Boolean e2eProducer;
private Boolean e2eController;
private Long timestampSync;
private Integer testTimeSec;
private String outputFile;
private Boolean deleteTopics;
private Integer producerPartition;
private Integer producerPartitionCount;
private Integer producerPartitionSize;
private List<Long> universeIds;
private Integer universeSize;
private Double expoDelayMean;
private String kafkaBootstrapServers;
private String dataFolder;
private Long windowSizeMillis;
private String application;
// fields only required for zeph
private Integer universeMinSize;
private Double alpha;
private Double delta;
private Integer controllerPartitionCount;
private Integer controllerPartition;
private Integer controllerPartitionSize;
private Integer universesInController;
private Integer producersInController; // per universe
private Duration consumerPollTimeout;
public boolean isLeader() {
return e2eProducer && producerPartition == 0l;
}
public Integer getTotalNumberOfProducers() {
return producerPartitionSize * getNumUniverses();
}
public Integer getTotalNumberOfControllers() {
if (benchmarkType != BenchmarkType.zeph) {
return null;
}
Double total = (controllerPartitionSize * getNumUniverses() / (double) universesInController
/ (double) producersInController);
return total.intValue();
}
public Boolean isE2eProducer() {
return e2eProducer;
}
public String getApplication() {
return application;
}
public Boolean isE2eController() {
return e2eController;
}
public void setTimestampSync(Long timestampSync) {
this.timestampSync = timestampSync;
}
public Long getTimestampSync() {
return timestampSync;
}
public String getExperimentId() {
return experimentId;
}
public Integer getTestTimeSec() {
return testTimeSec;
}
public String getOutputFile() {
return outputFile;
}
public Boolean isDeleteTopics() {
return deleteTopics;
}
public Integer getNumUniverses() {
return universeIds.size();
}
public BenchmarkType getBenchmarkType() {
return benchmarkType;
}
public Integer getProducerPartition() {
return producerPartition;
}
public Integer getProducerPartitionCount() {
return producerPartitionCount;
}
public Integer getProducerPartitionSize() {
return producerPartitionSize;
}
public List<Long> getUniverseIds() {
return universeIds;
}
public Integer getUniverseSize() {
return universeSize;
}
public Double getExpoDelayMean() {
return expoDelayMean;
}
public String getKafkaBootstrapServers() {
return kafkaBootstrapServers;
}
public String getDataFolder() {
return dataFolder;
}
public Long getWindowSizeMillis() {
return windowSizeMillis;
}
public Integer getUniverseMinSize() {
return universeMinSize;
}
public Double getAlpha() {
return alpha;
}
public Double getDelta() {
return delta;
}
public Integer getControllerPartitionCount() {
return controllerPartitionCount;
}
public Integer getControllerPartition() {
return controllerPartition;
}
public Integer getControllerPartitionSize() {
return controllerPartitionSize;
}
public Integer getUniversesInController() {
return universesInController;
}
public Integer getProducersInController() {
return producersInController;
}
public Duration getConsumerPollTimeout() {
return consumerPollTimeout;
}
@Override
public String toString() {
return "E2EConfig [benchmarkType=" + benchmarkType + ", experimentId=" + experimentId + ", e2eProducer="
+ e2eProducer + ", e2eController=" + e2eController + ", timestampSync=" + timestampSync
+ ", testTimeSec=" + testTimeSec + ", outputFile=" + outputFile + ", deleteTopics=" + deleteTopics
+ ", producerPartition=" + producerPartition + ", producerPartitionCount=" + producerPartitionCount
+ ", producerPartitionSize=" + producerPartitionSize + ", universeIds=" + universeIds
+ ", universeSize=" + universeSize + ", expoDelayMean=" + expoDelayMean + ", kafkaBootstrapServers="
+ kafkaBootstrapServers + ", dataFolder=" + dataFolder + ", windowSizeMillis=" + windowSizeMillis
+ ", application=" + application + ", universeMinSize=" + universeMinSize + ", alpha=" + alpha
+ ", delta=" + delta + ", controllerPartitionCount=" + controllerPartitionCount
+ ", controllerPartition=" + controllerPartition + ", controllerPartitionSize="
+ controllerPartitionSize + ", universesInController=" + universesInController
+ ", producersInController=" + producersInController + ", consumerPollTimeout=" + consumerPollTimeout
+ "]";
}
public static enum BenchmarkType {
zeph, plaintext
}
public static class E2EConfigBuilder {
private E2EConfig config;
public E2EConfigBuilder(BenchmarkType benchmarkType) {
config = new E2EConfig();
config.benchmarkType = benchmarkType;
}
public E2EConfigBuilder withExperimentId(String experimentId) {
config.experimentId = experimentId;
return this;
}
public E2EConfigBuilder withE2EProducer(boolean e2eProducer) {
config.e2eProducer = e2eProducer;
return this;
}
public E2EConfigBuilder withE2EController(boolean e2eController) {
config.e2eController = e2eController;
return this;
}
public E2EConfigBuilder withTimestampSync(long timestampSync) {
config.timestampSync = timestampSync;
return this;
}
public E2EConfigBuilder withTestTimeSec(int testTimeSec) {
config.testTimeSec = testTimeSec;
return this;
}
public E2EConfigBuilder withApplication(String application) {
config.application = application;
return this;
}
public E2EConfigBuilder withOutputFile(String outputFile) {
config.outputFile = outputFile;
return this;
}
public E2EConfigBuilder withDeleteTopics(boolean deleteTopics) {
config.deleteTopics = deleteTopics;
return this;
}
public E2EConfigBuilder withProducerPartition(int producerPartition) {
config.producerPartition = producerPartition;
return this;
}
public E2EConfigBuilder withProducerPartitionCount(int producerPartitionCount) {
config.producerPartitionCount = producerPartitionCount;
return this;
}
public E2EConfigBuilder withProducerPartitionSize(int producerPartitionSize) {
config.producerPartitionSize = producerPartitionSize;
return this;
}
public E2EConfigBuilder withUniverseIds(List<Long> universeIds) {
config.universeIds = universeIds;
return this;
}
public E2EConfigBuilder withUniverseSize(int universeSize) {
config.universeSize = universeSize;
return this;
}
public E2EConfigBuilder withExpoDelayMean(double expoDelayMean) {
config.expoDelayMean = expoDelayMean;
return this;
}
public E2EConfigBuilder withWindowSizeMillis(long windowSizeMillis) {
config.windowSizeMillis = windowSizeMillis;
return this;
}
public E2EConfigBuilder withKafkaBootstrapServers(String kafkaBootstrapServers) {
config.kafkaBootstrapServers = kafkaBootstrapServers;
return this;
}
public E2EConfigBuilder withDataFolder(String dataFolder) {
config.dataFolder = dataFolder;
return this;
}
// zeph specific
public E2EConfigBuilder withControllerPartition(int controllerPartition) {
config.controllerPartition = controllerPartition;
return this;
}
public E2EConfigBuilder withControllerPartitionCount(int controllerPartitionCount) {
config.controllerPartitionCount = controllerPartitionCount;
return this;
}
public E2EConfigBuilder withControllerPartitionSize(int controllerPartitionSize) {
config.controllerPartitionSize = controllerPartitionSize;
return this;
}
public E2EConfigBuilder withUniversesInController(int universesInController) {
config.universesInController = universesInController;
return this;
}
public E2EConfigBuilder withProducersInController(int producersInController) {
config.producersInController = producersInController;
return this;
}
public E2EConfigBuilder withUniverseMinSize(int universeMinSize) {
config.universeMinSize = universeMinSize;
return this;
}
public E2EConfigBuilder withAlpha(double alpha) {
config.alpha = alpha;
return this;
}
public E2EConfigBuilder withDelta(double delta) {
config.delta = delta;
return this;
}
public E2EConfigBuilder withConsumerPollTimeout(Duration consumerPollTimeout) {
config.consumerPollTimeout = consumerPollTimeout;
return this;
}
private void verifyBase() {
Objects.requireNonNull(config.e2eProducer);
Objects.requireNonNull(config.e2eController);
Objects.requireNonNull(config.experimentId);
Objects.requireNonNull(config.testTimeSec);
Objects.requireNonNull(config.deleteTopics);
Objects.requireNonNull(config.outputFile);
Objects.requireNonNull(config.producerPartition);
Objects.requireNonNull(config.producerPartitionCount);
Objects.requireNonNull(config.producerPartitionSize);
Objects.requireNonNull(config.universeIds);
Objects.requireNonNull(config.universeSize);
Objects.requireNonNull(config.expoDelayMean);
Objects.requireNonNull(config.windowSizeMillis);
Objects.requireNonNull(config.kafkaBootstrapServers);
Objects.requireNonNull(config.dataFolder);
requireTrue(!config.universeIds.isEmpty(), "universe ids cannot be empty");
requireTrue(config.producerPartition >= 0 && config.producerPartition < config.producerPartitionCount,
"producer partition must be within [0, producerPartitionCount)");
requireTrue(config.producerPartitionSize * config.producerPartitionCount == config.universeSize,
"producer partition size and count must match universe size");
}
private void verifyZeph() {
Objects.requireNonNull(config.controllerPartition);
Objects.requireNonNull(config.controllerPartitionCount);
Objects.requireNonNull(config.controllerPartitionSize);
Objects.requireNonNull(config.universeMinSize);
Objects.requireNonNull(config.alpha);
Objects.requireNonNull(config.delta);
Objects.requireNonNull(config.universesInController);
Objects.requireNonNull(config.producersInController);
Objects.requireNonNull(config.consumerPollTimeout);
requireTrue(config.controllerPartition >= 0 && config.controllerPartition < config.controllerPartitionCount,
"controller partition must be within [0, controllerPartitionCount)");
requireTrue(config.universesInController <= config.universeIds.size(),
"cannot have more universes in controller than universes");
requireTrue(config.producersInController <= config.controllerPartitionSize,
"cannot assign more producers to controllers than there are in the partition");
requireTrue(config.controllerPartitionSize * config.controllerPartitionCount == config.universeSize,
"controller partition size and count must match universe size");
}
private void requireTrue(boolean condition, String msg) {
if (!condition) {
throw new IllegalArgumentException(msg);
}
}
public E2EConfig build() {
verifyBase();
if (config.benchmarkType == BenchmarkType.zeph) {
verifyZeph();
}
return config;
}
}
}
| 27.126794 | 111 | 0.767528 |
6e16c6474e80ca600b77f596cc0157a72a2852d3 | 7,627 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.streams.filter.optimization.dependency;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.rocketmq.streams.common.optimization.HomologousVar;
import org.apache.rocketmq.streams.common.utils.CollectionUtil;
import org.apache.rocketmq.streams.filter.function.expression.LikeFunction;
import org.apache.rocketmq.streams.filter.function.expression.RegexFunction;
import org.apache.rocketmq.streams.filter.operator.expression.Expression;
import org.apache.rocketmq.streams.script.operator.expression.GroupScriptExpression;
import org.apache.rocketmq.streams.script.operator.expression.ScriptExpression;
import org.apache.rocketmq.streams.script.optimization.performance.IScriptOptimization;
import org.apache.rocketmq.streams.script.service.IScriptExpression;
import org.apache.rocketmq.streams.script.service.IScriptParamter;
public class CommonExpression {
protected String varName;//var name in stage
protected String value;//expression value eg:regex,like string
protected boolean isRegex;//if regex return true else false
protected String sourceVarName;//the var name in source
protected Integer index;//set by HomologousCompute, is cache result bitset index
protected List<IScriptExpression> scriptExpressions = new ArrayList<>();
protected IScriptExpression scriptExpression;
protected Expression expression;
public CommonExpression(IScriptExpression expression) {
if (!support(expression)) {
return;
}
this.scriptExpression = expression;
IScriptParamter varParameter = (IScriptParamter) expression.getScriptParamters().get(0);
IScriptParamter regexParameter = (IScriptParamter) expression.getScriptParamters().get(1);
String regex = IScriptOptimization.getParameterValue(regexParameter);
String varName = IScriptOptimization.getParameterValue(varParameter);
this.varName = varName;
this.value = regex;
this.isRegex = true;
}
public CommonExpression(Expression expression) {
if (!support(expression)) {
return;
}
this.expression = expression;
if (RegexFunction.isRegex(expression.getFunctionName())) {
value = (String) expression.getValue();
varName = expression.getVarName();
isRegex = true;
}
if (LikeFunction.isLikeFunciton(expression.getFunctionName())) {
value = (String) expression.getValue();
varName = expression.getVarName();
isRegex = false;
}
}
public static boolean support(IScriptExpression expression) {
if (GroupScriptExpression.class.isInstance(expression)) {
return false;
}
if (expression.getFunctionName() == null) {
return false;
}
if (expression.getScriptParamters() == null || expression.getScriptParamters().size() != 2) {
return false;
}
if (org.apache.rocketmq.streams.script.function.impl.string.RegexFunction.isRegexFunction(expression.getFunctionName())) {
return true;
}
return false;
}
public static boolean support(Expression expression) {
if (expression.getFunctionName() == null) {
return false;
}
if (RegexFunction.isRegex(expression.getFunctionName()) || LikeFunction.isLikeFunciton(expression.getFunctionName())) {
return true;
}
return false;
}
public String getVarName() {
return varName;
}
public void setVarName(String varName) {
this.varName = varName;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public boolean isRegex() {
return isRegex;
}
public void setRegex(boolean regex) {
isRegex = regex;
}
public List<IScriptExpression> getScriptExpressions() {
return scriptExpressions;
}
public void setScriptExpressions(
List<IScriptExpression> scriptExpressions) {
this.scriptExpressions = scriptExpressions;
}
public boolean init() {
Collections.sort(this.scriptExpressions, new Comparator<IScriptExpression>() {
@Override public int compare(IScriptExpression o1, IScriptExpression o2) {
List<String> varNames1 = o1.getDependentFields();
List<String> varNames2 = o2.getDependentFields();
for (String varName : varNames1) {
if (o2.getNewFieldNames() != null && o2.getNewFieldNames().contains(varName)) {
return 1;
}
}
for (String varName : varNames2) {
if (o1.getNewFieldNames() != null && o1.getNewFieldNames().contains(varName)) {
return -1;
}
}
return 0;
}
});
ScriptDependent scriptDependent = new ScriptDependent(this.scriptExpressions);
Set<String> varNames = scriptDependent.traceaField(this.varName, new AtomicBoolean(false), new ArrayList<>());
if (CollectionUtil.isEmpty(varNames)) {
this.sourceVarName = varName;
} else {
if (varNames.size() > 1) {
return false;
}
this.sourceVarName = varNames.iterator().next();
}
return true;
}
public void addPreviewScriptDependent(List<IScriptExpression> scriptExpressions) {
if (scriptExpressions == null) {
return;
}
this.scriptExpressions.addAll(scriptExpressions);
}
public String getSourceVarName() {
return sourceVarName;
}
public void setSourceVarName(String sourceVarName) {
this.sourceVarName = sourceVarName;
}
public void addHomologousVarToExpression() {
HomologousVar homologousVar = new HomologousVar();
homologousVar.setSourceVarName(this.sourceVarName);
homologousVar.setIndex(index);
homologousVar.setVarName(this.varName);
if (scriptExpression != null && ScriptExpression.class.isInstance(scriptExpression)) {
ScriptExpression scriptExpressionImp = (ScriptExpression) scriptExpression;
scriptExpressionImp.setHomologousVar(homologousVar);
}
if (expression != null) {
expression.setHomologousVar(homologousVar);
}
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
}
| 36.146919 | 130 | 0.664088 |
d17f743d186d2a8460e9529a6d299d03554ca6af | 1,120 | package se.artheus.minecraft.theallcord.entities.cables;
import net.minecraft.core.BlockPos;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.state.BlockState;
import se.artheus.minecraft.theallcord.networking.CableType;
import static se.artheus.minecraft.theallcord.blocks.Blocks.BLOCK_ITEM_CABLE_ELITE;
import static se.artheus.minecraft.theallcord.blocks.Blocks.BLOCK_ITEM_CABLE_ELITE_DENSE;
import static se.artheus.minecraft.theallcord.entities.BlockEntities.ENTITY_TYPE_CABLE_ELITE;
import static se.artheus.minecraft.theallcord.resource.ResourceLocations.ID_ENTITY_CABLE_ELITE;
public class CableEliteEntity extends AbstractNetworkCableEntity {
public CableEliteEntity(BlockPos blockPos, BlockState blockState) {
super(CableType.ELITE, ENTITY_TYPE_CABLE_ELITE, blockPos, blockState);
}
@Override
public String getTagPrefix() {
return ID_ENTITY_CABLE_ELITE.getPath();
}
@Override
public ItemStack asItemStack() {
return isDense() ? new ItemStack(BLOCK_ITEM_CABLE_ELITE_DENSE):new ItemStack(BLOCK_ITEM_CABLE_ELITE);
}
}
| 38.62069 | 109 | 0.808036 |
cda2d5e4143f218e1306e4256597ab68417c86b4 | 151 | package org.apache.airavata.mft.core.api;
public interface TransportOperator {
public long getResourceSize(String resourceId) throws Exception;
}
| 25.166667 | 68 | 0.807947 |
b0d7079966d071d849f06e71ed2ddc1e2cd1ed04 | 2,176 | /*
* Minecraft Forge
* Copyright (c) 2016.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.server.command;
import io.netty.channel.Channel;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.text.TextComponentBase;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.translation.I18n;
import net.minecraftforge.fml.common.network.NetworkRegistry;
public class TextComponentHelper
{
private TextComponentHelper() {}
/**
* Detects when sending to a vanilla client and falls back to sending english,
* since they don't have the lang data necessary to translate on the client.
*/
public static TextComponentBase createComponentTranslation(ICommandSender sender, final String translation, final Object... args)
{
if (isVanillaClient(sender))
{
return new TextComponentString(I18n.translateToLocalFormatted(translation, args));
}
return new TextComponentTranslation(translation, args);
}
private static boolean isVanillaClient(ICommandSender sender)
{
if (sender instanceof EntityPlayerMP)
{
EntityPlayerMP playerMP = (EntityPlayerMP) sender;
Channel channel = playerMP.connection.netManager.channel();
return !channel.attr(NetworkRegistry.FML_MARKER).get();
}
return false;
}
} | 38.175439 | 133 | 0.735754 |
9786fe8de52a00a491fc6a689acf4f986a7f9b19 | 20,660 | /*
* IntPTI: integer error fixing by proper-type inference
* Copyright (c) 2017.
*
* Open-source component:
*
* CPAchecker
* Copyright (C) 2007-2014 Dirk Beyer
*
* Guava: Google Core Libraries for Java
* Copyright (C) 2010-2006 Google
*
*
*/
package org.sosy_lab.cpachecker.cpa.range;
import com.google.common.base.Optional;
import org.sosy_lab.cpachecker.cfa.ast.FileLocation;
import org.sosy_lab.cpachecker.cfa.ast.c.CArraySubscriptExpression;
import org.sosy_lab.cpachecker.cfa.ast.c.CBinaryExpression;
import org.sosy_lab.cpachecker.cfa.ast.c.CBinaryExpression.BinaryOperator;
import org.sosy_lab.cpachecker.cfa.ast.c.CComplexCastExpression;
import org.sosy_lab.cpachecker.cfa.ast.c.CExpression;
import org.sosy_lab.cpachecker.cfa.ast.c.CFieldReference;
import org.sosy_lab.cpachecker.cfa.ast.c.CIdExpression;
import org.sosy_lab.cpachecker.cfa.ast.c.CLeftHandSide;
import org.sosy_lab.cpachecker.cfa.ast.c.CLeftHandSideVisitor;
import org.sosy_lab.cpachecker.cfa.ast.c.CPointerExpression;
import org.sosy_lab.cpachecker.cfa.ast.c.CUnaryExpression;
import org.sosy_lab.cpachecker.cfa.ast.c.CUnaryExpression.UnaryOperator;
import org.sosy_lab.cpachecker.cfa.types.c.CArrayType;
import org.sosy_lab.cpachecker.cfa.types.c.CPointerType;
import org.sosy_lab.cpachecker.cfa.types.c.CType;
import org.sosy_lab.cpachecker.core.interfaces.AbstractState;
import org.sosy_lab.cpachecker.cpa.pointer2.Pointer2State;
import org.sosy_lab.cpachecker.cpa.shape.ShapeState;
import org.sosy_lab.cpachecker.exceptions.UnrecognizedCCodeException;
import org.sosy_lab.cpachecker.util.AbstractStates;
import org.sosy_lab.cpachecker.util.Types;
import org.sosy_lab.cpachecker.util.access.AccessPath;
import org.sosy_lab.cpachecker.util.access.AddressingSegment;
import org.sosy_lab.cpachecker.util.access.ArrayConstIndexSegment;
import org.sosy_lab.cpachecker.util.access.FieldAccessSegment;
import org.sosy_lab.cpachecker.util.access.PathSegment;
import org.sosy_lab.cpachecker.util.access.PointerDereferenceSegment;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Stack;
/**
* This visitor computes access path for left-hand-side expressions.
* In particular, if an array expression has uncertain index, no valid access path will be generated
*
* NOTE: since path visitor has state, it should be used for only once and then be recycled.
*/
public final class LeftHandAccessPathVisitor implements CLeftHandSideVisitor<Optional<AccessPath>,
UnrecognizedCCodeException> {
private final ExpressionRangeVisitor rangeVisitor;
/**
* Other components of abstract states, used for strengthen
*/
private List<AbstractState> otherStates = null;
/**
* If this flag is ON, then we compose two array indexes as one.
* For example, a[3] and [4..6] is composed into a[7..9]
*
* NOTE: this flag can be set to TRUE or FALSE without limitation.
*/
private boolean composeMode = false;
/**
* If this flag is ON, then we stop generation of access path because we do not know what the
* exact memory location that this pointer points to.
*
* NOTE: once this flag becomes TRUE, it cannot be set to FALSE again!
*/
private boolean refuseDereference = false;
public LeftHandAccessPathVisitor(ExpressionRangeVisitor pVisitor) {
rangeVisitor = pVisitor;
otherStates = pVisitor.getOtherStates();
}
@Override
public Optional<AccessPath> visit(CArraySubscriptExpression pIastArraySubscriptExpression)
throws UnrecognizedCCodeException {
CExpression array = pIastArraySubscriptExpression.getArrayExpression();
AccessPath arrayPath;
if (array instanceof CLeftHandSide) {
arrayPath = ((CLeftHandSide) array).accept(this).orNull();
} else {
arrayPath = handleNonLeftValue(array).orNull();
}
if (arrayPath == null) {
return Optional.absent();
}
AccessPath resultPath = null;
CPointerType pointerType = Types.extractPointerType(array.getExpressionType());
if (pointerType != null) {
// then, the array subscript is equivalent to a pointer dereference operation
if (refuseDereference) {
return Optional.absent();
}
// examine if the last segment is address-of
if (arrayPath.getLastSegment().equals(AddressingSegment.INSTANCE)) {
arrayPath.removeLastSegment();
resultPath = arrayPath;
} else {
composeArrayIndexSegments(arrayPath, new ArrayConstIndexSegment(0));
if (otherStates != null) {
// strengthen with other pointer/alias/shape analyses
AbstractState pointerState = AbstractStates.extractStateByTypes(otherStates, ShapeState
.class, Pointer2State.class);
if (pointerState instanceof ShapeState) {
// The remaining segments after uncertain array segment could not contain dereference
// segment, since `refuseDereference` flag works.
List<PathSegment> remains = splitAccessPath(arrayPath);
Set<AccessPath> targets = ((ShapeState) pointerState).getPointsToTargetForAccessPath
(arrayPath);
if (!targets.isEmpty()) {
// we only pick one of the resultant access path, thus the analysis precision may lose
resultPath = targets.iterator().next();
for (PathSegment r : remains) {
// thus, we can directly append remaining segments
resultPath.appendSegment(r);
}
}
} else if (pointerState instanceof Pointer2State) {
List<PathSegment> remains = splitAccessPath(arrayPath);
Set<AccessPath> targets = ((Pointer2State) pointerState)
.getPointsToTargetForAccessPath(arrayPath, rangeVisitor.getMachineModel());
if (!targets.isEmpty()) {
resultPath = targets.iterator().next();
for (PathSegment r : remains) {
resultPath.appendSegment(r);
}
}
}
}
}
composeMode = true;
} else {
resultPath = arrayPath;
}
if (resultPath != null) {
CExpression index = pIastArraySubscriptExpression.getSubscriptExpression();
Range indexRange = index.accept(rangeVisitor).compress();
CompInteger integerNum = indexRange.numOfIntegers();
if (integerNum.equals(CompInteger.ZERO)) {
return Optional.absent();
} else if (!integerNum.equals(CompInteger.ONE)) {
refuseDereference = true;
composeArrayIndexSegments(resultPath, new ArrayUncertainIndexSegment(indexRange));
} else {
Long concreteIndex = indexRange.getLow().longValue();
if (concreteIndex == null) {
return Optional.absent();
}
composeArrayIndexSegments(resultPath, new ArrayConstIndexSegment(concreteIndex));
}
composeMode = false;
return Optional.of(resultPath);
}
return Optional.absent();
}
@Override
public Optional<AccessPath> visit(CFieldReference pIastFieldReference)
throws UnrecognizedCCodeException {
CExpression fieldOwner = pIastFieldReference.getFieldOwner();
AccessPath ownerPath;
boolean containsPtr = false;
if (fieldOwner instanceof CLeftHandSide) {
ownerPath = ((CLeftHandSide) fieldOwner).accept(this).orNull();
if (ownerPath == null) {
return Optional.absent();
}
if (pIastFieldReference.isPointerDereference()) {
if (refuseDereference) {
return Optional.absent();
}
ownerPath.appendSegment(new PointerDereferenceSegment());
containsPtr = true;
}
} else if (pIastFieldReference.isPointerDereference()) {
// the star operation is reduced if the owner is a non-LHS
ownerPath = handleNonLeftValue(fieldOwner).orNull();
if (ownerPath == null) {
return Optional.absent();
}
if (ownerPath.getLastSegment().equals(AddressingSegment.INSTANCE)) {
ownerPath.removeLastSegment();
}
} else {
// that is impossible
return Optional.absent();
}
AccessPath resultPath = null;
if (containsPtr) {
if (otherStates != null) {
AbstractState pointerState = AbstractStates.extractStateByTypes(otherStates, ShapeState
.class, Pointer2State.class);
if (pointerState instanceof ShapeState) {
List<PathSegment> remains = splitAccessPath(ownerPath);
Set<AccessPath> targets = ((ShapeState) pointerState).getPointsToTargetForAccessPath
(ownerPath);
if (!targets.isEmpty()) {
resultPath = targets.iterator().next();
for (PathSegment r : remains) {
resultPath.appendSegment(r);
}
}
} else if (pointerState instanceof Pointer2State) {
List<PathSegment> remains = splitAccessPath(ownerPath);
Set<AccessPath> targets = ((Pointer2State) pointerState)
.getPointsToTargetForAccessPath(ownerPath, rangeVisitor.getMachineModel());
if (!targets.isEmpty()) {
resultPath = targets.iterator().next();
for (PathSegment r : remains) {
resultPath.appendSegment(r);
}
}
}
}
} else {
resultPath = ownerPath;
}
composeMode = false;
if (resultPath != null) {
resultPath.appendSegment(new FieldAccessSegment(pIastFieldReference.getFieldName()));
return Optional.of(resultPath);
}
return Optional.absent();
}
@Override
public Optional<AccessPath> visit(CIdExpression pIastIdExpression)
throws UnrecognizedCCodeException {
composeMode = false;
AccessPath ap = new AccessPath(pIastIdExpression.getDeclaration());
return Optional.of(ap);
}
@Override
public Optional<AccessPath> visit(CPointerExpression pointerExpression)
throws UnrecognizedCCodeException {
CExpression refExpression = pointerExpression.getOperand();
AccessPath refPath;
boolean containsPtr = false;
if (refExpression instanceof CLeftHandSide) {
refPath = ((CLeftHandSide) refExpression).accept(this).orNull();
if (refPath == null) {
return Optional.absent();
}
if (refuseDereference) {
return Optional.absent();
}
refPath.appendSegment(new PointerDereferenceSegment());
containsPtr = true;
} else {
refPath = handleNonLeftValue(refExpression).orNull();
if (refPath == null) {
return Optional.absent();
}
if (refPath.getLastSegment().equals(AddressingSegment.INSTANCE)) {
refPath.removeLastSegment();
}
}
composeMode = false;
// use pointer analysis info.
if (containsPtr) {
AccessPath result = null;
if (otherStates != null) {
AbstractState pointerState = AbstractStates.extractStateByTypes(otherStates, ShapeState
.class, Pointer2State.class);
if (pointerState instanceof ShapeState) {
List<PathSegment> remains = splitAccessPath(refPath);
Set<AccessPath> targets = ((ShapeState) pointerState).getPointsToTargetForAccessPath
(refPath);
if (!targets.isEmpty()) {
result = targets.iterator().next();
for (PathSegment r : remains) {
result.appendSegment(r);
}
}
} else if (pointerState instanceof Pointer2State) {
List<PathSegment> remains = splitAccessPath(refPath);
Set<AccessPath> targets = ((Pointer2State) pointerState)
.getPointsToTargetForAccessPath(refPath, rangeVisitor.getMachineModel());
if (!targets.isEmpty()) {
result = targets.iterator().next();
for (PathSegment r : remains) {
result.appendSegment(r);
}
}
}
}
return (result == null) ? Optional.<AccessPath>absent() : Optional.of(result);
} else {
return Optional.of(refPath);
}
}
/**
* Compute actual path or actual path plus a tail & (address-of) for non-LHS.
* Note: this method is used for handling non-LHS inside pointer reference.
*/
private Optional<AccessPath> handleNonLeftValue(CExpression expression)
throws UnrecognizedCCodeException {
if (expression instanceof CUnaryExpression) {
UnaryOperator operator = ((CUnaryExpression) expression).getOperator();
if (operator == UnaryOperator.AMPER) {
CExpression operand = ((CUnaryExpression) expression).getOperand();
assert (operand instanceof CLeftHandSide);
AccessPath prePath = ((CLeftHandSide) operand).accept(this).orNull();
if (prePath != null) {
composeMode = true;
prePath.appendSegment(new AddressingSegment());
// actual path + address-of operation (&)
return Optional.of(prePath);
}
return Optional.absent();
}
} else if (expression instanceof CBinaryExpression) {
CBinaryExpression binExp = (CBinaryExpression) expression;
CExpression op1 = binExp.getOperand1();
CExpression op2 = binExp.getOperand2();
BinaryOperator operator = binExp.getOperator();
CType type1 = op1.getExpressionType();
CType type2 = op2.getExpressionType();
CPointerType pointerType1 = Types.extractPointerType(type1);
CPointerType pointerType2 = Types.extractPointerType(type2);
CArrayType arrayType1 = Types.extractArrayType(type1);
CArrayType arrayType2 = Types.extractArrayType(type2);
AccessPath actualPath = null;
if (pointerType1 != null && Types.isNumericalType(type2)) {
actualPath = handleBinaryPointerExpression(op1, pointerType1, operator, op2);
} else if (arrayType1 != null && Types.isNumericalType(type2)) {
actualPath = handleBinaryArrayExpression(op1, operator, op2);
} else if (pointerType2 != null && Types.isNumericalType(type1)) {
if (operator == BinaryOperator.PLUS) {
actualPath = handleBinaryPointerExpression(op2, pointerType2, operator, op1);
}
} else if (arrayType2 != null && Types.isNumericalType(type1)) {
if (operator == BinaryOperator.PLUS) {
actualPath = handleBinaryArrayExpression(op2, operator, op1);
}
}
if (actualPath != null) {
return Optional.of(actualPath);
}
}
// other cases
return Optional.absent();
}
private AccessPath handleBinaryPointerExpression(
CExpression pointer,
CPointerType pointerType,
BinaryOperator operator,
CExpression index)
throws UnrecognizedCCodeException {
// if pointer contains undetermined array index, it would be refused in handling pointer
// expression
CPointerExpression pointerExp = new CPointerExpression(FileLocation.DUMMY, pointerType
.getType(), pointer);
// prePath is an actual path
AccessPath prePath = pointerExp.accept(this).orNull();
composeMode = true;
if (prePath == null) {
return null;
}
Range indexRange = index.accept(rangeVisitor).compress();
switch (operator) {
case PLUS:
break;
case MINUS:
indexRange = indexRange.negate();
break;
default:
throw new AssertionError("Unsupported binary operator in pointer expression");
}
CompInteger integerNum = indexRange.numOfIntegers();
if (integerNum.equals(CompInteger.ZERO)) {
return null;
} else if (!integerNum.equals(CompInteger.ONE)) {
refuseDereference = true;
composeArrayIndexSegments(prePath, new ArrayUncertainIndexSegment(indexRange));
} else {
Long concreteIndex = indexRange.getLow().longValue();
if (concreteIndex == null) {
return null;
}
composeArrayIndexSegments(prePath, new ArrayConstIndexSegment(concreteIndex));
}
// After composing index to an actual path, the result is still an actual path.
// Therefore we directly return this path.
return prePath;
}
private AccessPath handleBinaryArrayExpression(
CExpression array,
BinaryOperator operator,
CExpression index)
throws UnrecognizedCCodeException {
AccessPath prePath;
if (array instanceof CLeftHandSide) {
prePath = ((CLeftHandSide) array).accept(this).orNull();
} else {
prePath = handleNonLeftValue(array).orNull();
}
if (prePath == null) {
return null;
}
composeArrayIndexSegments(prePath, new ArrayConstIndexSegment(0));
composeMode = true;
Range indexRange = index.accept(rangeVisitor).compress();
switch (operator) {
case PLUS:
break;
case MINUS:
indexRange = indexRange.negate();
break;
default:
throw new AssertionError("Unsupported binary operator in array expression");
}
CompInteger integerNum = indexRange.numOfIntegers();
if (integerNum.equals(CompInteger.ZERO)) {
return null;
} else if (!integerNum.equals(CompInteger.ONE)) {
refuseDereference = false;
composeArrayIndexSegments(prePath, new ArrayUncertainIndexSegment(indexRange));
} else {
Long concreteIndex = indexRange.getLow().longValue();
if (concreteIndex == null) {
return null;
}
composeArrayIndexSegments(prePath, new ArrayConstIndexSegment(concreteIndex));
}
return prePath;
}
private void composeArrayIndexSegments(AccessPath path, ArrayConstIndexSegment indexSegment) {
PathSegment lastSegment = path.getLastSegment();
if (composeMode) {
long topIndex = indexSegment.getIndex();
if (lastSegment instanceof ArrayConstIndexSegment) {
long lastIndex = ((ArrayConstIndexSegment) lastSegment).getIndex();
ArrayConstIndexSegment newLastSegment = new ArrayConstIndexSegment(lastIndex + topIndex);
path.removeLastSegment();
path.appendSegment(newLastSegment);
} else if (lastSegment instanceof ArrayUncertainIndexSegment) {
Range lastIndex = ((ArrayUncertainIndexSegment) lastSegment).getIndexRange();
lastIndex = lastIndex.plus(topIndex);
ArrayUncertainIndexSegment newLastSegment = new ArrayUncertainIndexSegment(lastIndex);
path.removeLastSegment();
path.appendSegment(newLastSegment);
} else {
path.appendSegment(indexSegment);
}
} else {
path.appendSegment(indexSegment);
}
}
private void composeArrayIndexSegments(AccessPath path, ArrayUncertainIndexSegment indexSegment) {
PathSegment lastSegment = path.getLastSegment();
if (composeMode) {
Range topIndex = indexSegment.getIndexRange();
if (lastSegment instanceof ArrayUncertainIndexSegment) {
Range lastIndex = ((ArrayUncertainIndexSegment) lastSegment).getIndexRange();
lastIndex = lastIndex.plus(topIndex);
ArrayUncertainIndexSegment newSegment = new ArrayUncertainIndexSegment(lastIndex);
path.removeLastSegment();
path.appendSegment(newSegment);
} else if (lastSegment instanceof ArrayConstIndexSegment) {
Long lastIndex = ((ArrayConstIndexSegment) lastSegment).getIndex();
Range newIndex = topIndex.plus(lastIndex);
ArrayUncertainIndexSegment newSegment = new ArrayUncertainIndexSegment(newIndex);
path.removeLastSegment();
path.appendSegment(newSegment);
} else {
path.appendSegment(indexSegment);
}
} else {
path.appendSegment(indexSegment);
}
}
@Override
public Optional<AccessPath> visit(CComplexCastExpression complexCastExpression)
throws UnrecognizedCCodeException {
return Optional.absent();
}
Range computePointerDiff(AccessPath path1, AccessPath path2) {
return Range.UNBOUND;
}
/**
* For strengthen with shape analysis, we should process access path by pruning undetermined
* array index segments.
*
* @param path an access path
* @return a list of path segments which is the truncated parts of the original access path
*/
private List<PathSegment> splitAccessPath(AccessPath path) {
List<PathSegment> segments = path.path();
Stack<PathSegment> remains = new Stack<>();
int r = segments.size();
for (PathSegment segment : segments) {
if (segment instanceof ArrayUncertainIndexSegment) {
break;
}
r--;
}
while (r > 0) {
remains.push(path.getLastSegment());
path.removeLastSegment();
r--;
}
List<PathSegment> results = new ArrayList<>();
while (!remains.isEmpty()) {
results.add(remains.pop());
}
return results;
}
}
| 38.616822 | 100 | 0.679671 |
438749c2c40f2a87996be59557257fe0ac1a3605 | 712 | package fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.modules.http.api;
public enum Constants {
;
public static enum Parameters {
;
public static final String LAYER_NAME = "layer";
public static final String LAYERS = "layers[]";
public static final String DOCUMENT_ID = "docId";
public static final String ELEMENT_ID = "eltId";
public static final String NODE_ID = "parentId";
public static final String EXPRESSION = "expr";
}
public static enum NodeIdFunctors {
;
public static final String CHILDREN = "children";
public static final String FEATURES = "features";
public static final String ANNOTATIONS = "annotations";
public static final String EVALUATE = "evaluate";
}
}
| 28.48 | 74 | 0.738764 |
16f997b61338321c24bf63037844c4d3f24e3678 | 295 | package br.com.recode.exemplo09.repositorios;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.com.recode.exemplo09.entidades.Aluno;
@Repository
public interface AlunoRepository extends JpaRepository<Aluno, String> {
} | 26.818182 | 71 | 0.840678 |
0e2d019615b20abed6d7dac6dda3062cb6a8c823 | 19,883 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.gsuiteaddons.v1.stub;
import static com.google.cloud.gsuiteaddons.v1.GSuiteAddOnsClient.ListDeploymentsPagedResponse;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.gsuiteaddons.v1.Authorization;
import com.google.cloud.gsuiteaddons.v1.CreateDeploymentRequest;
import com.google.cloud.gsuiteaddons.v1.DeleteDeploymentRequest;
import com.google.cloud.gsuiteaddons.v1.Deployment;
import com.google.cloud.gsuiteaddons.v1.GetAuthorizationRequest;
import com.google.cloud.gsuiteaddons.v1.GetDeploymentRequest;
import com.google.cloud.gsuiteaddons.v1.GetInstallStatusRequest;
import com.google.cloud.gsuiteaddons.v1.InstallDeploymentRequest;
import com.google.cloud.gsuiteaddons.v1.InstallStatus;
import com.google.cloud.gsuiteaddons.v1.ListDeploymentsRequest;
import com.google.cloud.gsuiteaddons.v1.ListDeploymentsResponse;
import com.google.cloud.gsuiteaddons.v1.ReplaceDeploymentRequest;
import com.google.cloud.gsuiteaddons.v1.UninstallDeploymentRequest;
import com.google.common.collect.ImmutableMap;
import com.google.longrunning.stub.GrpcOperationsStub;
import com.google.protobuf.Empty;
import io.grpc.MethodDescriptor;
import io.grpc.protobuf.ProtoUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* gRPC stub implementation for the GSuiteAddOns service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@Generated("by gapic-generator-java")
public class GrpcGSuiteAddOnsStub extends GSuiteAddOnsStub {
private static final MethodDescriptor<GetAuthorizationRequest, Authorization>
getAuthorizationMethodDescriptor =
MethodDescriptor.<GetAuthorizationRequest, Authorization>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.gsuiteaddons.v1.GSuiteAddOns/GetAuthorization")
.setRequestMarshaller(
ProtoUtils.marshaller(GetAuthorizationRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Authorization.getDefaultInstance()))
.build();
private static final MethodDescriptor<CreateDeploymentRequest, Deployment>
createDeploymentMethodDescriptor =
MethodDescriptor.<CreateDeploymentRequest, Deployment>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.gsuiteaddons.v1.GSuiteAddOns/CreateDeployment")
.setRequestMarshaller(
ProtoUtils.marshaller(CreateDeploymentRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Deployment.getDefaultInstance()))
.build();
private static final MethodDescriptor<ReplaceDeploymentRequest, Deployment>
replaceDeploymentMethodDescriptor =
MethodDescriptor.<ReplaceDeploymentRequest, Deployment>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.gsuiteaddons.v1.GSuiteAddOns/ReplaceDeployment")
.setRequestMarshaller(
ProtoUtils.marshaller(ReplaceDeploymentRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Deployment.getDefaultInstance()))
.build();
private static final MethodDescriptor<GetDeploymentRequest, Deployment>
getDeploymentMethodDescriptor =
MethodDescriptor.<GetDeploymentRequest, Deployment>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.gsuiteaddons.v1.GSuiteAddOns/GetDeployment")
.setRequestMarshaller(
ProtoUtils.marshaller(GetDeploymentRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Deployment.getDefaultInstance()))
.build();
private static final MethodDescriptor<ListDeploymentsRequest, ListDeploymentsResponse>
listDeploymentsMethodDescriptor =
MethodDescriptor.<ListDeploymentsRequest, ListDeploymentsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.gsuiteaddons.v1.GSuiteAddOns/ListDeployments")
.setRequestMarshaller(
ProtoUtils.marshaller(ListDeploymentsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListDeploymentsResponse.getDefaultInstance()))
.build();
private static final MethodDescriptor<DeleteDeploymentRequest, Empty>
deleteDeploymentMethodDescriptor =
MethodDescriptor.<DeleteDeploymentRequest, Empty>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.gsuiteaddons.v1.GSuiteAddOns/DeleteDeployment")
.setRequestMarshaller(
ProtoUtils.marshaller(DeleteDeploymentRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance()))
.build();
private static final MethodDescriptor<InstallDeploymentRequest, Empty>
installDeploymentMethodDescriptor =
MethodDescriptor.<InstallDeploymentRequest, Empty>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.gsuiteaddons.v1.GSuiteAddOns/InstallDeployment")
.setRequestMarshaller(
ProtoUtils.marshaller(InstallDeploymentRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance()))
.build();
private static final MethodDescriptor<UninstallDeploymentRequest, Empty>
uninstallDeploymentMethodDescriptor =
MethodDescriptor.<UninstallDeploymentRequest, Empty>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.gsuiteaddons.v1.GSuiteAddOns/UninstallDeployment")
.setRequestMarshaller(
ProtoUtils.marshaller(UninstallDeploymentRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance()))
.build();
private static final MethodDescriptor<GetInstallStatusRequest, InstallStatus>
getInstallStatusMethodDescriptor =
MethodDescriptor.<GetInstallStatusRequest, InstallStatus>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.cloud.gsuiteaddons.v1.GSuiteAddOns/GetInstallStatus")
.setRequestMarshaller(
ProtoUtils.marshaller(GetInstallStatusRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(InstallStatus.getDefaultInstance()))
.build();
private final UnaryCallable<GetAuthorizationRequest, Authorization> getAuthorizationCallable;
private final UnaryCallable<CreateDeploymentRequest, Deployment> createDeploymentCallable;
private final UnaryCallable<ReplaceDeploymentRequest, Deployment> replaceDeploymentCallable;
private final UnaryCallable<GetDeploymentRequest, Deployment> getDeploymentCallable;
private final UnaryCallable<ListDeploymentsRequest, ListDeploymentsResponse>
listDeploymentsCallable;
private final UnaryCallable<ListDeploymentsRequest, ListDeploymentsPagedResponse>
listDeploymentsPagedCallable;
private final UnaryCallable<DeleteDeploymentRequest, Empty> deleteDeploymentCallable;
private final UnaryCallable<InstallDeploymentRequest, Empty> installDeploymentCallable;
private final UnaryCallable<UninstallDeploymentRequest, Empty> uninstallDeploymentCallable;
private final UnaryCallable<GetInstallStatusRequest, InstallStatus> getInstallStatusCallable;
private final BackgroundResource backgroundResources;
private final GrpcOperationsStub operationsStub;
private final GrpcStubCallableFactory callableFactory;
public static final GrpcGSuiteAddOnsStub create(GSuiteAddOnsStubSettings settings)
throws IOException {
return new GrpcGSuiteAddOnsStub(settings, ClientContext.create(settings));
}
public static final GrpcGSuiteAddOnsStub create(ClientContext clientContext) throws IOException {
return new GrpcGSuiteAddOnsStub(GSuiteAddOnsStubSettings.newBuilder().build(), clientContext);
}
public static final GrpcGSuiteAddOnsStub create(
ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException {
return new GrpcGSuiteAddOnsStub(
GSuiteAddOnsStubSettings.newBuilder().build(), clientContext, callableFactory);
}
/**
* Constructs an instance of GrpcGSuiteAddOnsStub, using the given settings. This is protected so
* that it is easy to make a subclass, but otherwise, the static factory methods should be
* preferred.
*/
protected GrpcGSuiteAddOnsStub(GSuiteAddOnsStubSettings settings, ClientContext clientContext)
throws IOException {
this(settings, clientContext, new GrpcGSuiteAddOnsCallableFactory());
}
/**
* Constructs an instance of GrpcGSuiteAddOnsStub, using the given settings. This is protected so
* that it is easy to make a subclass, but otherwise, the static factory methods should be
* preferred.
*/
protected GrpcGSuiteAddOnsStub(
GSuiteAddOnsStubSettings settings,
ClientContext clientContext,
GrpcStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory);
GrpcCallSettings<GetAuthorizationRequest, Authorization> getAuthorizationTransportSettings =
GrpcCallSettings.<GetAuthorizationRequest, Authorization>newBuilder()
.setMethodDescriptor(getAuthorizationMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("name", String.valueOf(request.getName()));
return params.build();
})
.build();
GrpcCallSettings<CreateDeploymentRequest, Deployment> createDeploymentTransportSettings =
GrpcCallSettings.<CreateDeploymentRequest, Deployment>newBuilder()
.setMethodDescriptor(createDeploymentMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("parent", String.valueOf(request.getParent()));
return params.build();
})
.build();
GrpcCallSettings<ReplaceDeploymentRequest, Deployment> replaceDeploymentTransportSettings =
GrpcCallSettings.<ReplaceDeploymentRequest, Deployment>newBuilder()
.setMethodDescriptor(replaceDeploymentMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("deployment.name", String.valueOf(request.getDeployment().getName()));
return params.build();
})
.build();
GrpcCallSettings<GetDeploymentRequest, Deployment> getDeploymentTransportSettings =
GrpcCallSettings.<GetDeploymentRequest, Deployment>newBuilder()
.setMethodDescriptor(getDeploymentMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("name", String.valueOf(request.getName()));
return params.build();
})
.build();
GrpcCallSettings<ListDeploymentsRequest, ListDeploymentsResponse>
listDeploymentsTransportSettings =
GrpcCallSettings.<ListDeploymentsRequest, ListDeploymentsResponse>newBuilder()
.setMethodDescriptor(listDeploymentsMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("parent", String.valueOf(request.getParent()));
return params.build();
})
.build();
GrpcCallSettings<DeleteDeploymentRequest, Empty> deleteDeploymentTransportSettings =
GrpcCallSettings.<DeleteDeploymentRequest, Empty>newBuilder()
.setMethodDescriptor(deleteDeploymentMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("name", String.valueOf(request.getName()));
return params.build();
})
.build();
GrpcCallSettings<InstallDeploymentRequest, Empty> installDeploymentTransportSettings =
GrpcCallSettings.<InstallDeploymentRequest, Empty>newBuilder()
.setMethodDescriptor(installDeploymentMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("name", String.valueOf(request.getName()));
return params.build();
})
.build();
GrpcCallSettings<UninstallDeploymentRequest, Empty> uninstallDeploymentTransportSettings =
GrpcCallSettings.<UninstallDeploymentRequest, Empty>newBuilder()
.setMethodDescriptor(uninstallDeploymentMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("name", String.valueOf(request.getName()));
return params.build();
})
.build();
GrpcCallSettings<GetInstallStatusRequest, InstallStatus> getInstallStatusTransportSettings =
GrpcCallSettings.<GetInstallStatusRequest, InstallStatus>newBuilder()
.setMethodDescriptor(getInstallStatusMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("name", String.valueOf(request.getName()));
return params.build();
})
.build();
this.getAuthorizationCallable =
callableFactory.createUnaryCallable(
getAuthorizationTransportSettings, settings.getAuthorizationSettings(), clientContext);
this.createDeploymentCallable =
callableFactory.createUnaryCallable(
createDeploymentTransportSettings, settings.createDeploymentSettings(), clientContext);
this.replaceDeploymentCallable =
callableFactory.createUnaryCallable(
replaceDeploymentTransportSettings,
settings.replaceDeploymentSettings(),
clientContext);
this.getDeploymentCallable =
callableFactory.createUnaryCallable(
getDeploymentTransportSettings, settings.getDeploymentSettings(), clientContext);
this.listDeploymentsCallable =
callableFactory.createUnaryCallable(
listDeploymentsTransportSettings, settings.listDeploymentsSettings(), clientContext);
this.listDeploymentsPagedCallable =
callableFactory.createPagedCallable(
listDeploymentsTransportSettings, settings.listDeploymentsSettings(), clientContext);
this.deleteDeploymentCallable =
callableFactory.createUnaryCallable(
deleteDeploymentTransportSettings, settings.deleteDeploymentSettings(), clientContext);
this.installDeploymentCallable =
callableFactory.createUnaryCallable(
installDeploymentTransportSettings,
settings.installDeploymentSettings(),
clientContext);
this.uninstallDeploymentCallable =
callableFactory.createUnaryCallable(
uninstallDeploymentTransportSettings,
settings.uninstallDeploymentSettings(),
clientContext);
this.getInstallStatusCallable =
callableFactory.createUnaryCallable(
getInstallStatusTransportSettings, settings.getInstallStatusSettings(), clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
public GrpcOperationsStub getOperationsStub() {
return operationsStub;
}
@Override
public UnaryCallable<GetAuthorizationRequest, Authorization> getAuthorizationCallable() {
return getAuthorizationCallable;
}
@Override
public UnaryCallable<CreateDeploymentRequest, Deployment> createDeploymentCallable() {
return createDeploymentCallable;
}
@Override
public UnaryCallable<ReplaceDeploymentRequest, Deployment> replaceDeploymentCallable() {
return replaceDeploymentCallable;
}
@Override
public UnaryCallable<GetDeploymentRequest, Deployment> getDeploymentCallable() {
return getDeploymentCallable;
}
@Override
public UnaryCallable<ListDeploymentsRequest, ListDeploymentsResponse> listDeploymentsCallable() {
return listDeploymentsCallable;
}
@Override
public UnaryCallable<ListDeploymentsRequest, ListDeploymentsPagedResponse>
listDeploymentsPagedCallable() {
return listDeploymentsPagedCallable;
}
@Override
public UnaryCallable<DeleteDeploymentRequest, Empty> deleteDeploymentCallable() {
return deleteDeploymentCallable;
}
@Override
public UnaryCallable<InstallDeploymentRequest, Empty> installDeploymentCallable() {
return installDeploymentCallable;
}
@Override
public UnaryCallable<UninstallDeploymentRequest, Empty> uninstallDeploymentCallable() {
return uninstallDeploymentCallable;
}
@Override
public UnaryCallable<GetInstallStatusRequest, InstallStatus> getInstallStatusCallable() {
return getInstallStatusCallable;
}
@Override
public final void close() {
try {
backgroundResources.close();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to close resource", e);
}
}
@Override
public void shutdown() {
backgroundResources.shutdown();
}
@Override
public boolean isShutdown() {
return backgroundResources.isShutdown();
}
@Override
public boolean isTerminated() {
return backgroundResources.isTerminated();
}
@Override
public void shutdownNow() {
backgroundResources.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return backgroundResources.awaitTermination(duration, unit);
}
}
| 46.564403 | 99 | 0.72479 |
f3e88f6fd4964585cbb069f1ce3db4ed7f72e28e | 2,954 | package com.common.viewmodel;
public class LiveDataEvent {
public static final String SUCCESS = "10000";
/**
* 登录状态
*
* @param LOGIN_SUCCESS
* @return
*/
public static final int LOGIN_SUCCESS = 0x01;
/**
* 登录错误
*
* @param LOGIN_FAIL
* @return -
*/
public static final int LOGIN_FAIL = 0x02;
public static final int ALL_NAME_DATA = 0x03;
public static final int ALL_NAME_INT = 0x00;
public static final int CLASS_DATA_NUM = 0x1;
public static final int CLASS_NAME_DATA = 0x04;
/**
* all数据getData,通用字段
*
* @param CLASS_DATA
* @return
*/
public static final int CLASS_DATA = 0x05;
// public static final int GET_SMSCODE_SUCCESS = 0x07;
public static final int GROUP_PRISONER = 0x011;
public static final int HANDOVER_DATA = 0x08;
/**
* 加载进度,进度条显示隐藏
*
* @param JUST_PROGRESS_INT,JUST_PROGRESS_VISIBLE
* @return
*/
public static final int JUST_PROGRESS_INT = 0x018;
public static final int JUST_PROGRESS_VISIBLE = 0x019;
/**
* 进度条显示隐藏
*
* @param FINDCLASSNAME,PROGRESSVISIBER
* @return
*/
public static final int EmployeesByNum = 0x05;
public static final int LOGIN_SUCCESS_FAIL = 0x06;
/**
* 巡视点名,随机生成
*
* @param ROLL_CALL_DATA
* @return
*/
public static final int ROLL_CALL_DATA = 0x15;
public static final int HANDOVER_INFO = 0x16;
public static final int TALK_ISDELETE = 0x21;
public static final int TALK_NUM_DATA = 0x22;
public static final int UploadCall = 0x23;
public static final int JUST_SELECT_LOGIN = 0x24;
public static final int JUST_SELECT_PARENT = 0x25;
public static final int JUST_SELECT_CHILD = 0x26;
public static final int JUST_INHERIT_DATA = 0x27;
public static final int SCORE_FAIL = 0x28;
/**
* 接口返回type,判断接口是否成功
*/
public static final String JUST_SUCCESS = SUCCESS;
public static final int JUST_SUCCESS_TAG = 10000;
public static final int JUST_ERROR_FAIL_SUBMIT = 0x30;
public static final int EMC_LOGIN_SUCCESS = 0x31;
public static final int EMC_MEETING_FAIL = 0x32;
public static final int UPDATE_SUCCESS = 0x33;
public static final int UPDATE_FAIL = 0x34;
public static final int SCORE_DETAIL_SUCCESS = 0x35;
public static final int LOGIN_GO = 0x36;
/**
* 可判断所有错误
*/
public static final int JUST_ERROR_FAIL = 0x37;
/**
* 只判断数据库的错误
*/
public static final int ERROR = 0x38;
public int action;
public Object object;
public Object object2;
public LiveDataEvent(int action, Object object) {
this.action = action;
this.object = object;
}
public LiveDataEvent(int action, Object object, Object object2) {
this.action = action;
this.object = object;
this.object2 = object2;
}
}
| 23.078125 | 69 | 0.650643 |
7d05edb9d04d12c9015ceaa9473d0fb81f405104 | 682 | /**
* Richard
* Email: richardvu.work@gmail.com
* Skype: luongvu.work@gmail.com
* Phone: (+84) 0935710974 - (+84) 0935810974
* Country: Viet Nam
* Year: 2020
*/
package com.richard.app.io.entities;
import lombok.Getter;
import lombok.Setter;
/**
* @author richard
*
*/
@Getter
@Setter
public class Person {
//Instance variables (data or "state")
private String name;
private int age;
// Classes can contain
// 1. Data
// 2. Subroutines (methods)
public void speak() {
for (int i = 0; i < 3; i++) {
System.out.println("My name is: " + name + " and I am " + age + " years old ");
}
}
public void sayHello() {
System.out.println("Hello there!");
}
}
| 17.05 | 82 | 0.630499 |
713b670317cb132d81027f34e06b297eceafd88d | 634 | package com.fox2code.fabriczero.access.emc;
import com.fox2code.fabriczero.reflectutils.ReflectedClass;
import java.util.*;
public class EMCHashMap<T> extends HashMap<String, T> {
private static final Set<String> compatiblesMods =
new HashSet<>(Arrays.asList("optifine", "lithium", "phosphor"));
@Override
public T put(String key, T value) {
if (compatiblesMods.contains(key)) try {
ReflectedClass.of(value).get("conflicts")
.removeIf(r -> compatiblesMods.contains(r.asString()));
} catch (Throwable ignored) {}
return super.put(key, value);
}
}
| 31.7 | 76 | 0.654574 |
7a7639bc791e92ddeef625de94511135658e4542 | 884 | package server;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import consts.Constants;
/**
* Class for the Server.
*
* @author Florin Sia
*/
public class Server {
/**
* Starts the server.
*
* @param args
*/
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
int portNumber;
ServerSocket serverSocket;
if (args.length != 1) {
System.out.println("Using default port");
portNumber = Constants.DEFAULT_PORT;
} else {
portNumber = Integer.parseInt(args[0]);
}
try {
serverSocket = new ServerSocket(portNumber);
System.out.println("Server Ready");
while (true) {
executor.execute(new ServerThread(serverSocket.accept()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 20.55814 | 62 | 0.692308 |
f792fc49e8f0c96f2f0b27db03a0721444fd07fb | 5,056 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.rs.security.oauth.services;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;
import net.oauth.OAuth;
import net.oauth.OAuthMessage;
import net.oauth.OAuthProblemException;
import net.oauth.OAuthValidator;
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.common.util.StringUtils;
import org.apache.cxf.jaxrs.ext.MessageContext;
import org.apache.cxf.rs.security.oauth.data.AccessToken;
import org.apache.cxf.rs.security.oauth.data.AccessTokenRegistration;
import org.apache.cxf.rs.security.oauth.data.RequestToken;
import org.apache.cxf.rs.security.oauth.provider.OAuthDataProvider;
import org.apache.cxf.rs.security.oauth.provider.OAuthServiceException;
import org.apache.cxf.rs.security.oauth.utils.OAuthConstants;
import org.apache.cxf.rs.security.oauth.utils.OAuthUtils;
public class AccessTokenHandler {
private static final Logger LOG = LogUtils.getL7dLogger(AccessTokenHandler.class);
private static final String[] REQUIRED_PARAMETERS =
new String[] {
OAuth.OAUTH_CONSUMER_KEY,
OAuth.OAUTH_TOKEN,
OAuth.OAUTH_SIGNATURE_METHOD,
OAuth.OAUTH_SIGNATURE,
OAuth.OAUTH_TIMESTAMP,
OAuth.OAUTH_NONCE
};
public Response handle(MessageContext mc,
OAuthDataProvider dataProvider,
OAuthValidator validator) {
try {
OAuthMessage oAuthMessage =
OAuthUtils.getOAuthMessage(mc, mc.getHttpServletRequest(), REQUIRED_PARAMETERS);
RequestToken requestToken = dataProvider.getRequestToken(oAuthMessage.getToken());
if (requestToken == null) {
throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
}
String oauthVerifier = oAuthMessage.getParameter(OAuth.OAUTH_VERIFIER);
if (StringUtils.isEmpty(oauthVerifier)) {
if (requestToken.getSubject() != null && requestToken.isPreAuthorized()) {
LOG.fine("Preauthorized request token");
} else {
throw new OAuthProblemException(OAuthConstants.VERIFIER_INVALID);
}
} else if (!oauthVerifier.equals(requestToken.getVerifier())) {
throw new OAuthProblemException(OAuthConstants.VERIFIER_INVALID);
}
OAuthUtils.validateMessage(oAuthMessage,
requestToken.getClient(),
requestToken,
dataProvider,
validator);
AccessTokenRegistration reg = new AccessTokenRegistration();
reg.setRequestToken(requestToken);
AccessToken accessToken = dataProvider.createAccessToken(reg);
//create response
Map<String, Object> responseParams = new HashMap<>();
responseParams.put(OAuth.OAUTH_TOKEN, accessToken.getTokenKey());
responseParams.put(OAuth.OAUTH_TOKEN_SECRET, accessToken.getTokenSecret());
String responseString = OAuth.formEncode(responseParams.entrySet());
return Response.ok(responseString).build();
} catch (OAuthProblemException e) {
LOG.log(Level.WARNING, "An OAuth-related problem: {0}", new Object[] {e.fillInStackTrace()});
int code = e.getHttpStatusCode();
if (code == HttpServletResponse.SC_OK) {
code = OAuth.Problems.CONSUMER_KEY_UNKNOWN.equals(e.getProblem())
? 401 : 400;
}
return OAuthUtils.handleException(mc, e, code);
} catch (OAuthServiceException e) {
return OAuthUtils.handleException(mc, e, HttpServletResponse.SC_BAD_REQUEST);
} catch (Exception e) {
LOG.log(Level.SEVERE, "Unexpected internal server exception: {0}",
new Object[] {e.fillInStackTrace()});
return OAuthUtils.handleException(mc, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
| 43.586207 | 105 | 0.665744 |
1d9d4faffe2533b6e2f2a5fdad82d2965d2c912a | 361 | package com.hyf.facebook.demo.messengerPlatform;
import org.junit.Test;
/**
*
* @author winfun
* @date 2021/2/22 4:52 下午
**/
public class FacebookUtilTest {
public static String accessToken = "";
@Test
public void test(){
FacebookUtil util = new FacebookUtil();
System.out.println(util.hasGetStarted(accessToken));
}
}
| 16.409091 | 60 | 0.65651 |
962ef9e9822758610cf1f121edd91086aa74e671 | 3,312 | package wraith.smithee.mixin;
import net.minecraft.resource.NamespaceResourceManager;
import net.minecraft.resource.Resource;
import net.minecraft.resource.ResourceImpl;
import net.minecraft.util.Identifier;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import wraith.smithee.Smithee;
import wraith.smithee.SmitheeClient;
import wraith.smithee.registry.ItemRegistry;
import wraith.smithee.utils.Utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@Mixin(NamespaceResourceManager.class)
public class NamespaceResourceManagerMixin {
@Inject(method = "getResource(Lnet/minecraft/util/Identifier;)Lnet/minecraft/resource/Resource;", at = @At("HEAD"), cancellable = true)
public void getResource(Identifier id, CallbackInfoReturnable<Resource> cir) {
String[] segments = id.getPath().split("/");
String path = segments[segments.length - 1];
if (!id.getNamespace().equals(Smithee.MOD_ID) || !path.endsWith(".png")) {
return;
}
String pathWithoutExtension = path.split("\\.")[0];
segments = pathWithoutExtension.split("_");
int maxI = Utils.getMaterialFromPathIndex(pathWithoutExtension);
if (maxI >= segments.length) {
return;
}
StringBuilder material = new StringBuilder();
int i = 0;
for (; i < maxI; ++i) {
if (i > 0) {
material.append("_");
}
material.append(segments[i]);
}
StringBuilder part = new StringBuilder();
for (; i < segments.length; ++i) {
part.append("_").append(segments[i]);
}
part = new StringBuilder(part.substring(1));
if ((!ItemRegistry.MATERIALS.contains(material.toString()) && !ItemRegistry.EMBOSS_MATERIALS.contains(material.toString())) || (!ItemRegistry.BASE_RECIPE_VALUES.containsKey(part.toString()) && !SmitheeClient.RENDERING_TOOL_PARTS.contains(pathWithoutExtension) && !"whetstone".equals(part.toString()) && !"embossment".equals(part.toString()) && !"chisel".equals(part.toString()) && !"shard".equals(part.toString()))) {
return;
}
File texture = new File("config/smithee/textures/" + path);
File metadata = new File("config/smithee/textures/" + path + ".mcmeta");
if (texture.exists()) {
try {
cir.setReturnValue(new ResourceImpl(Smithee.MOD_ID, id, new FileInputStream(texture), metadata.exists() ? new FileInputStream(metadata) : null));
cir.cancel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
File templatePalette = new File("config/smithee/templates/template_palette.png");
File palette = new File("config/smithee/palettes/" + material + ".png");
File template = new File("config/smithee/templates/" + part + ".png");
cir.setReturnValue(new ResourceImpl(Smithee.MOD_ID, id, Utils.recolor(template, templatePalette, palette, pathWithoutExtension), null));
cir.cancel();
}
}
}
| 46.647887 | 425 | 0.657609 |
9ac491a6dc70de739d60eb65f3b9c94832d5b45a | 5,581 | /*
* This file is part of TDA - Thread Dump Analysis Tool.
*
* TDA is free software; you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* TDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public License
* along with TDA; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* $Id: TableCategory.java,v 1.7 2008-03-09 06:36:51 irockel Exp $
*/
package com.pironet.tda;
import com.pironet.tda.filter.FilterChecker;
import com.pironet.tda.utils.ColoredTable;
import com.pironet.tda.utils.PrefManager;
import com.pironet.tda.utils.TableSorter;
import com.pironet.tda.utils.ThreadsTableModel;
import com.pironet.tda.utils.ThreadsTableSelectionModel;
import java.util.EventListener;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* table category type, displays its content in a table.
*
* @author irockel
*/
public class TableCategory extends AbstractCategory {
private transient JTable filteredTable;
/**
* Creates a new instance of TableCategory
*/
public TableCategory(String name, int iconID) {
this(name, iconID, true);
}
/**
* Creates a new instance of TableCategory
*/
public TableCategory(String name, int iconID, boolean filtering) {
setName(name);
setFilterEnabled(filtering);
setIconID(iconID);
}
/**
* @inherited
*/
public JComponent getCatComponent(EventListener listener) {
if (isFilterEnabled() && ((filteredTable == null) || (getLastUpdated() < PrefManager.get().getFiltersLastChanged()))) {
// first refresh filter checker with current filters
setFilterChecker(FilterChecker.getFilterChecker());
// apply new filter settings.
DefaultMutableTreeNode filteredRootNode = filterNodes(getRootNode());
if (filteredRootNode != null && filteredRootNode.getChildCount() > 0) {
ThreadsTableModel ttm = new ThreadsTableModel(filterNodes(getRootNode()));
// create table instance (filtered)
setupTable(ttm, listener);
} else {
// just an empty table
filteredTable = new JTable();
}
setLastUpdated();
} else if (!isFilterEnabled() && ((filteredTable == null) || (getLastUpdated() < PrefManager.get().getFiltersLastChanged()))) {
// create unfiltered table view.
if (getRootNode().getChildCount() > 0) {
ThreadsTableModel ttm = new ThreadsTableModel(getRootNode());
// create table instance (unfiltered)
setupTable(ttm, listener);
}
}
return (filteredTable);
}
/**
* setup the table instance with the specified table model
* (either filtered or none-filtered).
*
* @param ts the table sorter/model to use.
* @param listener the event listener to add to the table
*/
private void setupTable(TableModel tm, EventListener listener) {
TableSorter ts = new TableSorter(tm);
filteredTable = new ColoredTable(ts);
ts.setTableHeader(filteredTable.getTableHeader());
filteredTable.setSelectionModel(new ThreadsTableSelectionModel(filteredTable));
filteredTable.getSelectionModel().addListSelectionListener((ListSelectionListener) listener);
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setHorizontalAlignment(JLabel.RIGHT);
// currently only two different views have to be dealt with,
// with more the model should be subclassed.
if (tm.getColumnCount() > 3) {
filteredTable.getColumnModel().getColumn(0).setPreferredWidth(300);
filteredTable.getColumnModel().getColumn(1).setPreferredWidth(30);
filteredTable.getColumnModel().getColumn(2).setPreferredWidth(15);
filteredTable.getColumnModel().getColumn(2).setCellRenderer(renderer);
filteredTable.getColumnModel().getColumn(3).setCellRenderer(renderer);
filteredTable.getColumnModel().getColumn(4).setCellRenderer(renderer);
} else {
filteredTable.getColumnModel().getColumn(0).setPreferredWidth(300);
filteredTable.getColumnModel().getColumn(1).setPreferredWidth(30);
filteredTable.getColumnModel().getColumn(2).setPreferredWidth(50);
filteredTable.getColumnModel().getColumn(1).setCellRenderer(renderer);
}
}
/**
* get the currently selected user object.
*
* @return the selected object or null otherwise.
*/
public ThreadInfo getCurrentlySelectedUserObject() {
return (filteredTable == null || filteredTable.getSelectedRow() < 0 ? null : (ThreadInfo) ((DefaultMutableTreeNode) getRootNode().getChildAt(filteredTable.getSelectedRow())).getUserObject());
}
}
| 39.58156 | 199 | 0.680702 |
c67c50ad0d93f1422fcb5c61edc68884240cd052 | 2,304 | /*-
* #%L
* Slice - Core
* %%
* Copyright (C) 2012 Wunderman Thompson Technology
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.cognifide.slice.core.internal.context;
import com.cognifide.slice.api.context.ContextProvider;
import com.cognifide.slice.api.context.ContextScope;
import com.cognifide.slice.core.internal.provider.ContextScopeProvider;
import com.google.inject.Key;
import com.google.inject.Provider;
/**
* @author Witold Szczerba
* @author Rafał Malinowski
*
* This Guice Scope stored all data in Context objects that are provided by ContextProvider instances.
* ContextProvider object are stored per-thread basis, so each thread can have its own Context (it is possible
* to create ContextProvider that shared data between thread, so this is not a requirement).
*
* ContextProvider objects can be changed at any time and also Context objects that there providers are
* providing can change. Thanks to that objects that are ContextScoped can be stored per-thread, per-request
* or even per-second. It only requires good implementation of ContextProvider and Context interfaces.
*/
public class SliceContextScope implements ContextScope {
private final ThreadLocal<ContextProvider> threadContextProvider;
public SliceContextScope() {
threadContextProvider = new ThreadLocal<ContextProvider>();
}
public void setContextProvider(final ContextProvider contextProvider) {
threadContextProvider.set(contextProvider);
}
public ContextProvider getContextProvider() {
return threadContextProvider.get();
}
@Override
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
return new ContextScopeProvider<T>(this, unscoped, key);
}
}
| 36.571429 | 111 | 0.74783 |
3a7aa11be602c017041922a3997280ec92cb8772 | 860 | package com.hdh.lifeup.model.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.hdh.lifeup.base.BaseDO;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* UserAuthDO class<br/>
*
* @author hdonghong
* @since 2018/08/22
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("`user_auth`")
public class UserAuthDO extends BaseDO {
private static final long serialVersionUID = 129185751196807386L;
@TableId
private Long authId;
/** 关联userInfo */
private Long userId;
/** 授权验证的类型,比如qq、yb、phone */
private String authType;
/** '第三方应用或者本站平台的唯一标识,比如手机号,微信openid' */
private String authIdentifier;
/** 'authType是手机号的话对应的是平台用户的密码' */
private String accessToken;
}
| 22.631579 | 69 | 0.732558 |
541a0f64e84c08a44041fb5e05034f20f15c8102 | 10,769 | /*
* Copyright 2020 MiLaboratory, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.milaboratory.util.sorting;
import cc.redberry.pipe.CUtils;
import cc.redberry.pipe.OutputPort;
import cc.redberry.pipe.OutputPortCloseable;
import cc.redberry.pipe.util.CountLimitingOutputPort;
import com.milaboratory.core.sequence.NucleotideSequence;
import com.milaboratory.primitivio.PrimitivIState;
import com.milaboratory.primitivio.PrimitivOState;
import com.milaboratory.test.TestUtil;
import com.milaboratory.util.TempFileManager;
import org.apache.commons.math3.random.RandomGenerator;
import org.apache.commons.math3.random.Well19937c;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
public class HashSorterTest {
@Test
public void numberOfBits() {
Assert.assertEquals(1, HashSorter.minimalNumberOfBits(10, 5));
Assert.assertEquals(1, HashSorter.minimalNumberOfBits(10, 7));
Assert.assertEquals(2, HashSorter.minimalNumberOfBits(10, 4));
Assert.assertEquals(0, HashSorter.minimalNumberOfBits(10, 10));
}
@Test
public void testMapping1() {
HashSorter.BucketMapping<Long> mapping = new HashSorter.BucketMapping<>(
Long::intValue, Comparator.<Long>naturalOrder(),
4, 0, new Object[0]);
Assert.assertEquals(16, mapping.getNumberOfBuckets());
for (int i = 0; i < 16; i++) {
Assert.assertFalse(mapping.isSingletonBucket(i));
Assert.assertEquals(i, mapping.getBucketId((long) i));
}
}
@Test
public void testMapping2() {
HashSorter.BucketMapping<Long> mapping = new HashSorter.BucketMapping<>(
Long::intValue, Comparator.<Long>naturalOrder(),
4, 0, new Object[]{3 + 16L});
Assert.assertEquals(18, mapping.getNumberOfBuckets());
for (int i = 0; i < 4; i++) {
Assert.assertFalse(mapping.isSingletonBucket(i));
Assert.assertEquals(i, mapping.getBucketId((long) i));
}
for (int i = 4; i < 16; i++) {
Assert.assertFalse(mapping.isSingletonBucket(i + 2));
Assert.assertEquals(i + 2, mapping.getBucketId((long) i));
}
Assert.assertEquals(4, mapping.getBucketId(3 + 16L));
}
@Test
public void testMapping3() {
HashSorter.BucketMapping<Long> mapping = new HashSorter.BucketMapping<>(
Long::intValue, Comparator.<Long>naturalOrder(),
4, 0, new Object[]{3 + 16L, 3 + 3 * 16L});
Assert.assertEquals(20, mapping.getNumberOfBuckets());
for (int i = 0; i < 4; i++) {
Assert.assertFalse(mapping.isSingletonBucket(i));
Assert.assertEquals(i, mapping.getBucketId((long) i));
}
for (int i = 4; i < 16; i++) {
Assert.assertFalse(mapping.isSingletonBucket(i + 4));
Assert.assertEquals(i + 4, mapping.getBucketId((long) i));
}
Assert.assertTrue(mapping.isSingletonBucket(4));
Assert.assertEquals(4, mapping.getBucketId(3 + 16L));
Assert.assertFalse(mapping.isSingletonBucket(5));
Assert.assertEquals(5, mapping.getBucketId(3 + 2 * 16L));
Assert.assertTrue(mapping.isSingletonBucket(6));
Assert.assertEquals(6, mapping.getBucketId(3 + 3 * 16L));
Assert.assertFalse(mapping.isSingletonBucket(7));
Assert.assertEquals(7, mapping.getBucketId(3 + 4 * 16L));
}
@Test
public void testMapping4() {
HashSorter.BucketMapping<Long> mapping = new HashSorter.BucketMapping<>(
Long::intValue, Comparator.<Long>naturalOrder(),
4, 0, new Object[]{3 + 16L, 4 + 3 * 16L});
Assert.assertEquals(20, mapping.getNumberOfBuckets());
for (int i = 0; i < 4; i++) {
Assert.assertFalse(mapping.isSingletonBucket(i));
Assert.assertEquals(i, mapping.getBucketId((long) i));
}
Assert.assertFalse(mapping.isSingletonBucket(4 + 2));
Assert.assertEquals(4 + 2, mapping.getBucketId((long) 4));
for (int i = 5; i < 16; i++) {
Assert.assertFalse(mapping.isSingletonBucket(i + 4));
Assert.assertEquals(i + 4, mapping.getBucketId((long) i));
}
Assert.assertTrue(mapping.isSingletonBucket(4));
Assert.assertEquals(4, mapping.getBucketId(3 + 16L));
Assert.assertFalse(mapping.isSingletonBucket(5));
Assert.assertEquals(5, mapping.getBucketId(3 + 2 * 16L));
Assert.assertFalse(mapping.isSingletonBucket(6));
Assert.assertEquals(6, mapping.getBucketId(4 + 16L));
Assert.assertTrue(mapping.isSingletonBucket(7));
Assert.assertEquals(7, mapping.getBucketId(4 + 3 * 16L));
Assert.assertFalse(mapping.isSingletonBucket(8));
Assert.assertEquals(8, mapping.getBucketId(4 + 4 * 16L));
}
@Test
public void test1() {
List<NucleotideSequence> seqsList = new ArrayList<>();
for (int i = 0; i < 1 << 15; i++)
seqsList.add(TestUtil.randomSequence(NucleotideSequence.ALPHABET, 20, 200));
RandomGenerator rg = new Well19937c(1234);
int N = 5000000;
AtomicInteger unorderedHash = new AtomicInteger(0);
OutputPort<NucleotideSequence> seqs = new OutputPort<NucleotideSequence>() {
@Override
public synchronized NucleotideSequence take() {
NucleotideSequence seq = seqsList.get(rg.nextInt(seqsList.size()));
unorderedHash.accumulateAndGet(seq.hashCode(), (left, right) -> left + right);
return seq;
}
};
seqs = new CountLimitingOutputPort<>(seqs, N);
File dir = TempFileManager.getTempDir();
System.out.println(dir);
HashSorter<NucleotideSequence> c = new HashSorter<>(
NucleotideSequence.class,
Objects::hashCode, Comparator.naturalOrder(),
5, dir.toPath(), 4, 6,
PrimitivOState.INITIAL, PrimitivIState.INITIAL,
1 << 23, 128);
Comparator<NucleotideSequence> ec = c.getEffectiveComparator();
try (OutputPortCloseable<NucleotideSequence> port = c.port(seqs)) {
long actualN = 0;
int uh = unorderedHash.get();
NucleotideSequence previous = null;
for (NucleotideSequence ns : CUtils.it(port)) {
++actualN;
uh -= ns.hashCode();
if (previous != null) {
int compare = ec.compare(previous, ns);
Assert.assertTrue(compare <= 0);
}
previous = ns;
}
Assert.assertEquals(N, actualN);
Assert.assertEquals(0, uh);
c.printStat();
}
}
@Test
public void test2() {
TestUtil.assumeLongTest();
List<NucleotideSequence> seqsList = new ArrayList<>();
for (int i = 0; i < 15; i++)
seqsList.add(TestUtil.randomSequence(NucleotideSequence.ALPHABET, 15000, 20000));
RandomGenerator rg = new Well19937c(1234);
int N = 500000;
AtomicInteger unorderedHash = new AtomicInteger(0);
OutputPort<NucleotideSequence> seqs = new OutputPort<NucleotideSequence>() {
@Override
public synchronized NucleotideSequence take() {
NucleotideSequence seq = seqsList.get(rg.nextInt(seqsList.size()));
unorderedHash.accumulateAndGet(seq.hashCode(), Integer::sum);
return seq;
}
};
seqs = new CountLimitingOutputPort<>(seqs, N);
File dir = TempFileManager.getTempDir();
System.out.println(dir);
HashSorter<NucleotideSequence> c = new HashSorter<>(
NucleotideSequence.class,
Objects::hashCode, Comparator.naturalOrder(),
5, dir.toPath(), 4, 6,
PrimitivOState.INITIAL, PrimitivIState.INITIAL,
1 << 20, 1 << 15);
Comparator<NucleotideSequence> ec = c.getEffectiveComparator();
try (OutputPortCloseable<NucleotideSequence> port = c.port(seqs)) {
long actualN = 0;
int uh = unorderedHash.get();
NucleotideSequence previous = null;
for (NucleotideSequence ns : CUtils.it(port)) {
++actualN;
uh -= ns.hashCode();
if (previous != null) {
int compare = ec.compare(previous, ns);
Assert.assertTrue(compare <= 0);
}
previous = ns;
}
Assert.assertEquals(N, actualN);
Assert.assertEquals(0, uh);
c.printStat();
}
}
@Test
public void testSingleton() {
NucleotideSequence seq = TestUtil.randomSequence(NucleotideSequence.ALPHABET, 15000, 20000);
int N = 50000;
AtomicInteger unorderedHash = new AtomicInteger(0);
OutputPort<NucleotideSequence> seqs = new OutputPort<NucleotideSequence>() {
@Override
public synchronized NucleotideSequence take() {
return seq;
}
};
seqs = new CountLimitingOutputPort<>(seqs, N);
File dir = TempFileManager.getTempDir();
System.out.println(dir);
HashSorter<NucleotideSequence> c = new HashSorter<>(
NucleotideSequence.class,
Objects::hashCode, Comparator.naturalOrder(),
5, dir.toPath(), 4, 6,
PrimitivOState.INITIAL, PrimitivIState.INITIAL,
1 << 20, 128);
Comparator<NucleotideSequence> ec = c.getEffectiveComparator();
try (OutputPortCloseable<NucleotideSequence> port = c.port(seqs)) {
long actualN = 0;
for (NucleotideSequence ignored : CUtils.it(port))
++actualN;
Assert.assertEquals(N, actualN);
c.printStat();
Assert.assertEquals(1, c.getNumberOfNodes());
}
}
}
| 39.16 | 100 | 0.609249 |
14ba578e1475e22afbd4a905c61dadbabc851a31 | 427 | package com.exercise.mysys.domain;
/**
* @ProjectName 食品企业订货销售系统
* @Author 朱向阳
* @Date 2018/7/22 17:46
* @Description: 退货单查询类
*/
public class returnGoodResult {
public String id;
public String good_name;
public String customer_name;
public String employee_name;
public String number;
public String money;
public String effective;
public String create_date;
public String formatdate;
}
| 21.35 | 34 | 0.711944 |
2bbaa6c75e5882a020a68de61003eac329391da5 | 2,421 | package mm.hlca;
import mm.icl.hlc.HLC.TimeUtil;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Calendar;
public class ContextCSVReader
{
// static final String userId = "9735";
// static final String llcLabel = "Sitting";
// TimeUtil util = new TimeUtil();
// Calendar cal1 = util.parseString("2016 04 18 10:11:25");
//Delimiters used in the CSV file
private static final String COMMA_DELIMITER = ",";
public static void main(String args[])
// public void bilalTest()
{
TimeUtil util = new TimeUtil();
BufferedReader br = null;
try
{
//Reading the csv file
br = new BufferedReader(new FileReader("E:/ICL_LOG/TDB/Activity.csv"));//ContextCSV
//Create List for holding Employee objects
List<ContextCSV> contextList = new ArrayList<ContextCSV>();
String line = "";
//Read to skip the header
br.readLine();
//Reading from the second line
while ((line = br.readLine()) != null)
{
String[] ContextCSVDetails = line.split(COMMA_DELIMITER);
if(ContextCSVDetails.length > 0 )
{
ContextCSV context_llc = new ContextCSV(ContextCSVDetails[0], ContextCSVDetails[1],ContextCSVDetails[2]);
contextList.add(context_llc);
}
}
//Lets print the Employee List
for(ContextCSV c : contextList)
{
System.out.println(c.getllcLabel()+" "+ c.getuserId()+" "+ util.parseString(c.getcal()));
// System.out.println(util.parseString(c.getcal())); // System.out.println(c.getcal()); // System.out.println(c.getuserId()); // System.out.println(c.getllcLabel());
}
}
catch(Exception ee)
{
ee.printStackTrace();
}
finally
{
try
{
br.close();
}
catch(IOException ie)
{
System.out.println("Error occured while closing the BufferedReader");
ie.printStackTrace();
}
}
}
} | 31.855263 | 225 | 0.529946 |
9391a304c1e190e20a4c3f2290d598821639493f | 15,526 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.gobblin.source.extractor.extract;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.ack.Ackable;
import org.apache.gobblin.commit.CommitStep;
import org.apache.gobblin.configuration.WorkUnitState;
import org.apache.gobblin.metrics.MetricContextUtils;
import org.apache.gobblin.publisher.DataPublisher;
import org.apache.gobblin.runtime.StateStoreBasedWatermarkStorage;
import org.apache.gobblin.source.extractor.CheckpointableWatermark;
import org.apache.gobblin.source.extractor.DataRecordException;
import org.apache.gobblin.stream.FlushControlMessage;
import org.apache.gobblin.stream.FlushRecordEnvelope;
import org.apache.gobblin.stream.RecordEnvelope;
import org.apache.gobblin.stream.StreamEntity;
import org.apache.gobblin.util.ConfigUtils;
import org.apache.gobblin.util.reflection.GobblinConstructorUtils;
import org.apache.gobblin.writer.LastWatermarkTracker;
import org.apache.gobblin.writer.WatermarkStorage;
import org.apache.gobblin.writer.WatermarkTracker;
/**
* An abstract class that implements a {@link EventBasedExtractor}. The {@link FlushingExtractor} injects a
* {@link FlushControlMessage} at a frequency determined by {@value #FLUSH_INTERVAL_SECONDS_KEY}.
* The {@link FlushControlMessage} blocks further messages being pushed until the outstanding {@link FlushControlMessage}
* has been acked by the real writer. On a successful ack, the extractor invokes a publish on the underlying DataPublisher,
* which moves the data from the task output location to the final publish location. After a successful publish, the FlushingExtractor
* commits the watermarks to the {@link WatermarkStorage}. Note the watermark committed to the watermark storage is the
* last successfully acked Watermark. Individual extractor implementations should start seeking from the next watermark
* past this watermark. For example, in the case of a Kafka extractor, the consumer should seek to the offset that is
* one more than the last committed watermark.
*
* Individual extractor implementations that extend the FlushingExtractor need to implement the following method:
* <ul>
* <li>readRecordEnvelopeImpl() - to return the next {@link RecordEnvelope}</li>.
* </ul>
*
* The FlushingExtractor allows applications to plug-in pre and post {@link CommitStep}s as actions to be performed before and after
* each commit.
* @param <D> type of {@link RecordEnvelope}
*/
@Slf4j
public abstract class FlushingExtractor<S, D> extends EventBasedExtractor<S, D> {
public static final String GOBBLIN_EXTRACTOR_PRECOMMIT_STEPS = "gobblin.extractor.precommit.steps";
public static final String GOBBLIN_EXTRACTOR_POSTCOMMIT_STEPS = "gobblin.extractor.postcommit.steps";
public static final String FLUSH_INTERVAL_SECONDS_KEY = "stream.flush.interval.secs";
public static final Long DEFAULT_FLUSH_INTERVAL_SECONDS = 60L;
public static final String FLUSH_DATA_PUBLISHER_CLASS = "flush.data.publisher.class";
public static final String DEFAULT_FLUSH_DATA_PUBLISHER_CLASS = "org.apache.gobblin.publisher.BaseDataPublisher";
public static final String WATERMARK_COMMIT_TIME_METRIC = "state.store.metrics.watermarkCommitTime";
public static final String COMMIT_STEP_METRIC_PREFIX = "commit.step.";
@Getter
protected Map<String, CheckpointableWatermark> lastCommittedWatermarks;
private final List<String> preCommitSteps;
private final List<String> postCommitSteps;
private final Map<String, CommitStep> commitStepMap = Maps.newHashMap();
private final AtomicLong watermarkCommitTime = new AtomicLong(0L);
private final List<AtomicLong> preCommitStepTimes = Lists.newArrayList();
private final List<AtomicLong> postCommitStepTimes = Lists.newArrayList();
protected Config config;
@Setter
private Optional<WatermarkStorage> watermarkStorage;
@Getter
protected WatermarkTracker watermarkTracker;
protected Long flushIntervalMillis;
protected Long timeOfLastFlush = System.currentTimeMillis();
private FlushAckable lastFlushAckable;
private boolean hasOutstandingFlush = false;
private Optional<DataPublisher> flushPublisher = Optional.absent();
protected WorkUnitState workUnitState;
public FlushingExtractor(WorkUnitState state) {
super(state);
this.workUnitState = state;
this.config = ConfigFactory.parseProperties(state.getProperties());
this.flushIntervalMillis =
ConfigUtils.getLong(config, FLUSH_INTERVAL_SECONDS_KEY, DEFAULT_FLUSH_INTERVAL_SECONDS) * 1000;
this.watermarkTracker = new LastWatermarkTracker(false);
this.watermarkStorage = Optional.of(new StateStoreBasedWatermarkStorage(state));
this.preCommitSteps = ConfigUtils.getStringList(config, GOBBLIN_EXTRACTOR_PRECOMMIT_STEPS);
this.postCommitSteps = ConfigUtils.getStringList(config, GOBBLIN_EXTRACTOR_POSTCOMMIT_STEPS);
preCommitSteps.stream().map(commitStep -> new AtomicLong(0L)).forEach(this.preCommitStepTimes::add);
postCommitSteps.stream().map(commitStep -> new AtomicLong(0L)).forEach(this.postCommitStepTimes::add);
initFlushPublisher();
MetricContextUtils.registerGauge(this.getMetricContext(), WATERMARK_COMMIT_TIME_METRIC, this.watermarkCommitTime);
initCommitStepMetrics(this.preCommitSteps, this.postCommitSteps);
}
private void initCommitStepMetrics(List<String>... commitStepLists) {
for (List<String> commitSteps : commitStepLists) {
for (String commitStepAlias : commitSteps) {
String metricName = COMMIT_STEP_METRIC_PREFIX + commitStepAlias + ".time";
MetricContextUtils.registerGauge(this.getMetricContext(), metricName, new AtomicLong(0L));
}
}
}
private StreamEntity<D> generateFlushMessageIfNecessary() {
Long currentTime = System.currentTimeMillis();
if ((currentTime - timeOfLastFlush) > this.flushIntervalMillis) {
return generateFlushMessage(currentTime);
}
return null;
}
private StreamEntity<D> generateFlushMessage(Long currentTime) {
log.debug("Injecting flush control message");
FlushControlMessage<D> flushMessage = FlushControlMessage.<D>builder().flushReason("Timed flush").build();
FlushAckable flushAckable = new FlushAckable();
// add a flush ackable to wait for the flush to complete before returning from this flush call
flushMessage.addCallBack(flushAckable);
//Preserve the latest flushAckable.
this.lastFlushAckable = flushAckable;
this.hasOutstandingFlush = true;
timeOfLastFlush = currentTime;
return flushMessage;
}
/**
* Create an {@link DataPublisher} for publishing after a flush. The {@link DataPublisher} is created through a
* DataPublisherFactory which makes requests
* to a {@link org.apache.gobblin.broker.iface.SharedResourcesBroker} to support sharing
* {@link DataPublisher} instances when appropriate.
* @return the {@link DataPublisher}
*/
private void initFlushPublisher() {
if (this.flushPublisher.isPresent()) {
return;
}
String publisherClassName =
ConfigUtils.getString(this.config, FLUSH_DATA_PUBLISHER_CLASS, DEFAULT_FLUSH_DATA_PUBLISHER_CLASS);
try {
this.flushPublisher = (Optional<DataPublisher>) Optional.of(
GobblinConstructorUtils.invokeLongestConstructor(Class.forName(publisherClassName), this.workUnitState));
} catch (ReflectiveOperationException e) {
log.error("Error in instantiating Data Publisher");
throw new RuntimeException(e);
}
}
@Override
public StreamEntity<D> readStreamEntityImpl() throws DataRecordException, IOException {
//Block until an outstanding flush has been Ack-ed.
if (this.hasOutstandingFlush) {
Throwable error = this.lastFlushAckable.waitForAck();
if (error != null) {
throw new RuntimeException("Error waiting for flush ack", error);
}
//Reset outstandingFlush flag
this.hasOutstandingFlush = false;
//Run pre-commit steps
doCommitSequence(preCommitSteps, true);
//Publish task output to final publish location.
publishTaskOutput();
//Provide a callback to the underlying extractor to handle logic for flush ack.
onFlushAck();
//Run post-commit steps
doCommitSequence(postCommitSteps, false);
}
StreamEntity<D> entity = generateFlushMessageIfNecessary();
if (entity != null) {
return entity;
}
//return the next read record.
RecordEnvelope<D> recordEnvelope = readRecordEnvelopeImpl();
if (recordEnvelope instanceof FlushRecordEnvelope) {
StreamEntity<D> flushMessage = generateFlushMessage(System.currentTimeMillis());
return flushMessage;
}
if (recordEnvelope != null) {
this.watermarkTracker.unacknowledgedWatermark(recordEnvelope.getWatermark());
}
return recordEnvelope;
}
/**
* A method that instantiates a {@link CommitStep} given an alias.
* @param commitStepAlias alias or fully qualified class name of the {@link CommitStep}.
* @throws IOException
*/
public CommitStep initCommitStep(String commitStepAlias, boolean isPrecommit) throws IOException {
return null;
}
private void doCommitSequence(List<String> commitSteps, boolean isPrecommit) throws IOException {
for (int i = 0; i < commitSteps.size(); i++) {
long startTimeMillis = System.currentTimeMillis();
String commitStepAlias = commitSteps.get(i);
CommitStep commitStep = commitStepMap.get(commitStepAlias);
if (commitStep == null) {
commitStep = initCommitStep(commitSteps.get(i), isPrecommit);
commitStepMap.put(commitStepAlias, commitStep);
}
log.info("Calling commit step: {}", commitStepAlias);
commitStep.execute();
long commitStepTime = System.currentTimeMillis() - startTimeMillis;
if (isPrecommit) {
preCommitStepTimes.get(i).set(commitStepTime);
} else {
postCommitStepTimes.get(i).set(commitStepTime);
}
}
}
/**
* A callback for the underlying extractor to implement logic for handling the completion of a flush. Underlying
* Extractor can override this method
*/
protected void onFlushAck() throws IOException {
checkPointWatermarks();
}
/**
* A method that returns the latest committed watermarks back to the caller. This method will be typically called
* by the underlying extractor during the initialization phase to retrieve the latest watermarks.
* @param checkPointableWatermarkClass a {@link CheckpointableWatermark} class
* @param partitions a collection of partitions assigned to the extractor
* @return the latest committed watermarks as a map of (source, watermark) pairs. For example, in the case of a KafkaStreamingExtractor,
* this map would be a collection of (TopicPartition, KafkaOffset) pairs.
*/
public Map<String, CheckpointableWatermark> getCommittedWatermarks(Class checkPointableWatermarkClass,
Iterable<String> partitions) {
Preconditions.checkArgument(CheckpointableWatermark.class.isAssignableFrom(checkPointableWatermarkClass),
"Watermark class " + checkPointableWatermarkClass.toString() + " is not a CheckPointableWatermark class");
try {
this.lastCommittedWatermarks =
this.watermarkStorage.get().getCommittedWatermarks(checkPointableWatermarkClass, partitions);
} catch (Exception e) {
// failed to get watermarks ... log a warning message
log.warn("Failed to get watermarks... will start from the beginning", e);
this.lastCommittedWatermarks = Collections.EMPTY_MAP;
}
return this.lastCommittedWatermarks;
}
/**
* Publish task output to final publish location.
*/
protected void publishTaskOutput() throws IOException {
if (!this.flushPublisher.isPresent()) {
throw new IOException("Publish called without a flush publisher");
}
this.flushPublisher.get().publish(Collections.singletonList(workUnitState));
}
/**
* Persist the watermarks in {@link WatermarkTracker#unacknowledgedWatermarks(Map)} to {@link WatermarkStorage}.
* The method is called when after a {@link FlushControlMessage} has been acknowledged. To make retrieval of
* the last committed watermarks efficient, this method caches the watermarks present in the unacknowledged watermark
* map.
*
* @throws IOException
*/
private void checkPointWatermarks() throws IOException {
Map<String, CheckpointableWatermark> unacknowledgedWatermarks =
this.watermarkTracker.getAllUnacknowledgedWatermarks();
if (this.watermarkStorage.isPresent()) {
long commitBeginTime = System.currentTimeMillis();
this.watermarkStorage.get().commitWatermarks(unacknowledgedWatermarks.values());
this.watermarkCommitTime.set(System.currentTimeMillis() - commitBeginTime);
//Cache the last committed watermarks
for (Map.Entry<String, CheckpointableWatermark> entry : unacknowledgedWatermarks.entrySet()) {
this.lastCommittedWatermarks.put(entry.getKey(), entry.getValue());
}
} else {
log.warn("No watermarkStorage found; Skipping checkpointing");
}
}
/**
* A method to be implemented by the underlying extractor that returns the next record as an instance of
* {@link RecordEnvelope}
* @return the next {@link RecordEnvelope} instance read from the source
*/
public abstract RecordEnvelope<D> readRecordEnvelopeImpl() throws DataRecordException, IOException;
/**
* {@link Ackable} for waiting for the flush control message to be processed
*/
private static class FlushAckable implements Ackable {
private Throwable error;
private final CountDownLatch processed;
public FlushAckable() {
this.processed = new CountDownLatch(1);
}
@Override
public void ack() {
this.processed.countDown();
}
@Override
public void nack(Throwable error) {
this.error = error;
this.processed.countDown();
}
/**
* Wait for ack
* @return any error encountered
*/
public Throwable waitForAck() {
try {
this.processed.await();
return this.error;
} catch (InterruptedException e) {
throw new RuntimeException("interrupted while waiting for ack");
}
}
}
}
| 42.190217 | 138 | 0.752029 |
50173a11565fa645b6e71bf824f86d29ab1bc417 | 18,579 | /*******************************************************************************
* Copyright (c) 2013-2016 LAAS-CNRS (www.laas.fr)
* 7 Colonel Roche 31077 Toulouse - France
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Initial Contributors:
* Thierry Monteil : Project manager, technical co-manager
* Mahdi Ben Alaya : Technical co-manager
* Samir Medjiah : Technical co-manager
* Khalil Drira : Strategy expert
* Guillaume Garzone : Developer
* François Aïssaoui : Developer
*
* New contributors :
*******************************************************************************/
package org.eclipse.om2m.core.controller;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.om2m.commons.constants.Constants;
import org.eclipse.om2m.commons.constants.MimeMediaType;
import org.eclipse.om2m.commons.constants.Operation;
import org.eclipse.om2m.commons.constants.ResourceType;
import org.eclipse.om2m.commons.constants.ResponseStatusCode;
import org.eclipse.om2m.commons.constants.ShortName;
import org.eclipse.om2m.commons.entities.AccessControlPolicyEntity;
import org.eclipse.om2m.commons.entities.AeEntity;
import org.eclipse.om2m.commons.entities.CSEBaseEntity;
import org.eclipse.om2m.commons.entities.ContainerEntity;
import org.eclipse.om2m.commons.entities.GroupEntity;
import org.eclipse.om2m.commons.entities.RemoteCSEEntity;
import org.eclipse.om2m.commons.entities.ResourceEntity;
import org.eclipse.om2m.commons.entities.SubscriptionEntity;
import org.eclipse.om2m.commons.exceptions.BadRequestException;
import org.eclipse.om2m.commons.exceptions.ConflictException;
import org.eclipse.om2m.commons.exceptions.NotImplementedException;
import org.eclipse.om2m.commons.exceptions.ResourceNotFoundException;
import org.eclipse.om2m.commons.resource.RequestPrimitive;
import org.eclipse.om2m.commons.resource.ResponsePrimitive;
import org.eclipse.om2m.commons.resource.Subscription;
import org.eclipse.om2m.commons.utils.Util.DateUtil;
import org.eclipse.om2m.core.datamapper.DataMapperSelector;
import org.eclipse.om2m.core.entitymapper.EntityMapperFactory;
import org.eclipse.om2m.core.notifier.Notifier;
import org.eclipse.om2m.core.persistence.PersistenceService;
import org.eclipse.om2m.core.router.Patterns;
import org.eclipse.om2m.core.urimapper.UriMapper;
import org.eclipse.om2m.core.util.ControllerUtil;
import org.eclipse.om2m.core.util.ControllerUtil.CreateUtil;
import org.eclipse.om2m.core.util.ControllerUtil.UpdateUtil;
import org.eclipse.om2m.persistence.service.DAO;
import org.eclipse.om2m.persistence.service.DBService;
import org.eclipse.om2m.persistence.service.DBTransaction;
/**
* Controller for Subscription
*
*/
public class SubscriptionController extends Controller{
@Override
public ResponsePrimitive doCreate(RequestPrimitive request) {
ResponsePrimitive response = new ResponsePrimitive(request);
// Get the DAO of the parent
DAO<?> dao = (DAO<?>) Patterns.getDAO(request.getTargetId(), dbs);
if (dao == null){
throw new ResourceNotFoundException("Cannot find parent resource");
}
// Get the parent entity
ResourceEntity parentEntity = (ResourceEntity) dao.find(transaction, request.getTargetId());
// Check the parent existence
if (parentEntity == null){
throw new ResourceNotFoundException("Cannot find parent resource");
}
// Get lists to change in the method corresponding to specific object
List<AccessControlPolicyEntity> acpsToCheck = null;
// Distinguish parents
// Case of CSEBase
if(parentEntity.getResourceType().intValue() == (ResourceType.CSE_BASE)){
CSEBaseEntity cseBase = (CSEBaseEntity) parentEntity;
acpsToCheck = cseBase.getAccessControlPolicies();
}
if(parentEntity.getResourceType().intValue() == (ResourceType.AE)){
AeEntity ae = (AeEntity) parentEntity;
acpsToCheck = ae.getAccessControlPolicies();
}
if(parentEntity.getResourceType().intValue() == (ResourceType.REMOTE_CSE)){
RemoteCSEEntity remoteCSE = (RemoteCSEEntity) parentEntity;
acpsToCheck = remoteCSE.getAccessControlPolicies();
}
if(parentEntity.getResourceType().intValue() == (ResourceType.GROUP)){
GroupEntity group = (GroupEntity) parentEntity;
acpsToCheck = group.getAccessControlPolicies();
}
if(parentEntity.getResourceType().intValue() == (ResourceType.CONTAINER)){
ContainerEntity container = (ContainerEntity) parentEntity;
acpsToCheck = container.getAccessControlPolicies();
}
if(parentEntity.getResourceType().intValue() == (ResourceType.ACCESS_CONTROL_POLICY)){
AccessControlPolicyEntity acp = (AccessControlPolicyEntity) parentEntity;
acpsToCheck = new ArrayList<>();
acpsToCheck.add(acp); // TODO check the acp to check in case of acp parent for subs
}
if(parentEntity.getResourceType().intValue() == ResourceType.REMOTE_CSE){
RemoteCSEEntity csr = (RemoteCSEEntity) parentEntity;
acpsToCheck = csr.getAccessControlPolicies();
}
if(acpsToCheck == null){
throw new NotImplementedException("Subscription is not yet supported on this resource");
}
// Check access control policy of the originator
checkACP(acpsToCheck, request.getFrom(), Operation.RETRIEVE);
// Check if content is present
if (request.getContent() == null){
throw new BadRequestException("A content is requiered for Subscription creation");
}
Subscription subscription = null;
try {
if(request.getRequestContentType().equals(MimeMediaType.OBJ)){
subscription = (Subscription) request.getContent();
} else {
subscription = (Subscription) DataMapperSelector.getDataMapperList().
get(request.getRequestContentType()).stringToObj((String)request.getContent());
}
} catch (ClassCastException e){
throw new BadRequestException("Incorrect resource representation in content", e);
}
if(subscription == null){
throw new BadRequestException("Error in provided content");
}
// Check attributes
// @resourceName NP
// resourceType NP
// resourceID NP
// parentID NP
// creationTime NP
// lastModifiedTime NP
// labels O
SubscriptionEntity subscriptionEntity = new SubscriptionEntity();
CreateUtil.fillEntityFromGenericResource(subscription, subscriptionEntity);
// notificationUri M
if(subscription.getNotificationURI().isEmpty()){
throw new BadRequestException("Notification URI is mandatory");
} else {
subscriptionEntity.getNotificationURI().addAll(subscription.getNotificationURI());
}
// expirationTime O
if(subscription.getExpirationTime() != null){
subscriptionEntity.setExpirationTime(subscription.getExpirationTime());
}
// eventNotificationCriteria O
if(subscription.getEventNotificationCriteria() != null){
// TODO Subscription EventNotoficationCriteria handling
}
// expirationCounter O
if(subscription.getExpirationCounter() != null){
subscriptionEntity.setExpirationCounter(subscription.getExpirationCounter());
}
// groupID O
if(subscription.getGroupID() != null){
subscriptionEntity.setGroupID(subscription.getGroupID());
}
// notificationForwardingUri O
if(subscription.getNotificationForwardingURI() != null){
}
// batchNotify O
if(subscription.getBatchNotify() != null){
// TODO BatchNotify
}
// rateLimit O
if(subscription.getRateLimit() != null){
// TODO RateLimit
}
// preSubscriptionNotification O
if(subscription.getPreSubscriptionNotify() != null){
subscriptionEntity.setPreSubscriptionNotify(
subscription.getPreSubscriptionNotify());
}
// pendingNotification O
if(subscription.getPendingNotification() != null){
subscriptionEntity.setPendingNotification(subscription.getPendingNotification());
}
// notificationStoragePriority O
if(subscription.getNotificationStoragePriority() != null){
subscriptionEntity.setNotificationStoragePriority(
subscription.getNotificationStoragePriority());
}
// latestNotify O
if(subscription.isLatestNotify() != null){
subscriptionEntity.setLatestNotify(subscription.isLatestNotify());
}
// notificationContentType O
if(subscription.getNotificationContentType() != null){
subscriptionEntity.setNotificationContentType(
subscription.getNotificationContentType());
}
// notificationEventCat O
if(subscription.getNotificationEventCat() != null){
subscriptionEntity.setNotificationEventCat(
subscription.getNotificationEventCat());
}
// creator O
if(subscription.getCreator() != null){
subscriptionEntity.setCreator(subscription.getCreator());
}
// subscriberURI O
if(subscription.getSubscriberURI() != null){
subscriptionEntity.setSubscriberURI(subscription.getSubscriberURI());
}
if(!subscription.getAccessControlPolicyIDs().isEmpty()){
subscriptionEntity.setAcpList(
ControllerUtil.buildAcpEntityList(subscription.getAccessControlPolicyIDs(), transaction));
} else {
subscriptionEntity.getAcpList().addAll(acpsToCheck);
}
String generatedId = generateId();
subscriptionEntity.setResourceID("/" + Constants.CSE_ID + "/" + ShortName.SUB + Constants.PREFIX_SEPERATOR + generatedId);
subscriptionEntity.setCreationTime(DateUtil.now());
subscriptionEntity.setLastModifiedTime(DateUtil.now());
subscriptionEntity.setParentID(parentEntity.getResourceID());
subscriptionEntity.setResourceType(ResourceType.SUBSCRIPTION);
if (subscription.getName() != null){
if (!Patterns.checkResourceName(subscription.getName())){
throw new BadRequestException("Name provided is incorrect. Must be:" + Patterns.ID_STRING);
}
subscriptionEntity.setName(subscription.getName());
} else
if(request.getName() != null){
if(!Patterns.checkResourceName(request.getName())){
throw new BadRequestException("Name provided is incorrect. Must be:" + Patterns.ID_STRING);
}
subscriptionEntity.setName(request.getName());
} else {
subscriptionEntity.setName(ShortName.SUB + "_" + generatedId);
}
Notifier.performVerificationRequest(request, subscriptionEntity);
subscriptionEntity.setHierarchicalURI(parentEntity.getHierarchicalURI() + "/" + subscriptionEntity.getName());
if(!UriMapper.addNewUri(subscriptionEntity.getHierarchicalURI(), subscriptionEntity.getResourceID(), ResourceType.SUBSCRIPTION)){
throw new ConflictException("Name already present in the parent collection.");
}
subscriptionEntity.setParentEntity(parentEntity);
dbs.getDAOFactory().getSubsciptionDAO().create(transaction, subscriptionEntity);
transaction.commit();
response.setResponseStatusCode(ResponseStatusCode.CREATED);
setLocationAndCreationContent(request, response, subscriptionEntity);
return response;
}
@Override
public ResponsePrimitive doRetrieve(RequestPrimitive request) {
ResponsePrimitive response = new ResponsePrimitive(request);
SubscriptionEntity subscriptionEntity = dbs.getDAOFactory()
.getSubsciptionDAO().find(transaction, request.getTargetId());
if (subscriptionEntity == null){
throw new ResourceNotFoundException();
}
checkACP(subscriptionEntity.getAcpList(), request.getFrom(),
Operation.RETRIEVE);
// Create the object used to create the representation of the resource
Subscription subscription = EntityMapperFactory.getSubscriptionMapper().mapEntityToResource(subscriptionEntity, request);
response.setContent(subscription);
response.setResponseStatusCode(ResponseStatusCode.OK);
return response;
}
@Override
public ResponsePrimitive doUpdate(RequestPrimitive request) {
ResponsePrimitive response = new ResponsePrimitive(request);
DBService dbs = PersistenceService.getInstance().getDbService();
DBTransaction transaction = dbs.getDbTransaction();
transaction.open();
SubscriptionEntity subscriptionEntity = dbs.getDAOFactory()
.getSubsciptionDAO().find(transaction, request.getTargetId());
if (subscriptionEntity == null){
throw new ResourceNotFoundException();
}
checkACP(subscriptionEntity.getAcpList(), request.getFrom(),
Operation.UPDATE);
// Check if content is present
if (request.getContent() == null){
throw new BadRequestException("A content is requiered for Subscription update");
}
Subscription subscription = null;
try {
if(request.getRequestContentType().equals(MimeMediaType.OBJ)){
subscription = (Subscription) request.getContent();
} else {
subscription = (Subscription) DataMapperSelector.getDataMapperList().
get(request.getRequestContentType()).stringToObj((String)request.getContent());
}
} catch (ClassCastException e){
throw new BadRequestException("Incorrect resource representation in content", e);
}
if(subscription == null){
throw new BadRequestException("Error in provided content");
}
// Check attributes
// NP Attributes are ignored
// resourceName NP
// resourceType NP
// resourceID NP
// parentID NP
// creationTime NP
// lastTimeModified NP
UpdateUtil.checkNotPermittedParameters(subscription);
// preSubscriptionNotify NP
if(subscription.getPreSubscriptionNotify() != null){
throw new BadRequestException("PreSubscriptionNotify is NP");
}
// subscriberURI NP
if(subscription.getSubscriberURI() != null){
throw new BadRequestException("SubscripberURI is NP");
}
Subscription modifiedAttributes = new Subscription();
// ACPIDs O
if(!subscription.getAccessControlPolicyIDs().isEmpty()){
for(AccessControlPolicyEntity acpe : subscriptionEntity.getAcpList()){
checkSelfACP(acpe, request.getFrom(), Operation.UPDATE);
}
subscriptionEntity.getAcpList().clear();
subscriptionEntity.setAcpList(ControllerUtil.buildAcpEntityList(subscription.getAccessControlPolicyIDs(), transaction));
modifiedAttributes.getAccessControlPolicyIDs().addAll(subscription.getAccessControlPolicyIDs());
}
// expirationTime O
if(subscription.getExpirationTime() != null){
subscriptionEntity.setExpirationTime(subscription.getExpirationTime());
modifiedAttributes.setExpirationTime(subscription.getExpirationTime());
}
// labels O
if(!subscription.getLabels().isEmpty()){
subscriptionEntity.getLabelsEntities().clear();
subscriptionEntity.setLabelsEntitiesFromSring(subscription.getLabels());
modifiedAttributes.getLabels().addAll(subscription.getLabels());
}
// eventNotificationCriteria O
if(subscription.getEventNotificationCriteria() != null){
// TODO eventNotificationCriteria
}
// expirationCounter O
if(subscription.getExpirationCounter() != null){
subscriptionEntity.setExpirationCounter(subscription.getExpirationCounter());
modifiedAttributes.setExpirationCounter(subscription.getExpirationCounter());
}
// notificationUri O
if(!subscription.getNotificationURI().isEmpty()){
subscriptionEntity.getNotificationURI().clear();
subscriptionEntity.getNotificationURI().addAll(subscription.getNotificationURI());
modifiedAttributes.getNotificationURI().addAll(subscription.getNotificationURI());
}
// groupID O
if(subscription.getGroupID() != null){
subscriptionEntity.setGroupID(subscription.getGroupID());
modifiedAttributes.setGroupID(subscription.getGroupID());
}
// notificationForwardingUri O
if(subscription.getNotificationForwardingURI() != null){
subscriptionEntity.setNotificationForwardingURI(subscription.getNotificationForwardingURI());
modifiedAttributes.setNotificationForwardingURI(subscription.getNotificationForwardingURI());
}
// batchNotify O
if(subscription.getBatchNotify() != null){
// TODO batch notify
}
// rateLimit O
if(subscription.getRateLimit() != null){
// TODO rate limit
}
// pendingNotification O
if(subscription.getPendingNotification() != null){
subscriptionEntity.setPendingNotification(subscription.getPendingNotification());
modifiedAttributes.setPendingNotification(subscription.getPendingNotification());
}
// notificationStorePriority O
if(subscription.getNotificationStoragePriority() != null){
subscriptionEntity.setNotificationStoragePriority(subscription.getNotificationStoragePriority());
modifiedAttributes.setNotificationStoragePriority(subscription.getNotificationStoragePriority());
}
// latestNotify O
if(subscription.isLatestNotify() != null){
subscriptionEntity.setLatestNotify(subscription.isLatestNotify());
modifiedAttributes.setLatestNotify(subscription.isLatestNotify());
}
// notificationContentType O
if(subscription.getNotificationContentType() != null){
subscriptionEntity.setNotificationContentType(subscription.getNotificationContentType());
modifiedAttributes.setNotificationContentType(subscription.getNotificationContentType());
}
// notificationEventCat O
if(subscription.getNotificationEventCat() != null){
subscriptionEntity.setNotificationEventCat(subscription.getNotificationEventCat());
modifiedAttributes.setNotificationEventCat(subscription.getNotificationEventCat());
}
// creator O
if(subscription.getCreator() != null){
subscriptionEntity.setCreator(subscription.getCreator());
modifiedAttributes.setCreator(subscription.getCreator());
}
// Update last time modified
subscriptionEntity.setLastModifiedTime(DateUtil.now());
modifiedAttributes.setLastModifiedTime(subscriptionEntity.getLastModifiedTime());
response.setContent(modifiedAttributes);
dbs.getDAOFactory().getSubsciptionDAO().update(transaction, subscriptionEntity);
transaction.commit();
response.setResponseStatusCode(ResponseStatusCode.UPDATED);
return response;
}
@Override
public ResponsePrimitive doDelete(RequestPrimitive request) {
ResponsePrimitive response = new ResponsePrimitive(request);
// Get the database service
DBService dbs = PersistenceService.getInstance().getDbService();
DBTransaction transaction = dbs.getDbTransaction();
transaction.open();
SubscriptionEntity se = dbs.getDAOFactory()
.getSubsciptionDAO().find(transaction, request.getTargetId());
if (se == null){
throw new ResourceNotFoundException();
}
checkACP(se.getAcpList(), request.getFrom(),
Operation.DELETE);
// Delete the resource in UriMapper table
UriMapper.deleteUri(se.getHierarchicalURI());
// Delete the resource
dbs.getDAOFactory().getSubsciptionDAO().delete(transaction, se);
transaction.commit();
response.setResponseStatusCode(ResponseStatusCode.DELETED);
return response;
}
}
| 37.158 | 131 | 0.765542 |
7b9c9eb5cf15d45d6570879ffb989a36fc032111 | 2,601 | package android.support.v4.app;
/**
* A support dialog fragment that allow show in state loss mode
*/
public class DialogFragmentStateless extends DialogFragment
{
/**
* Display the dialog, adding the fragment using an existing transaction and then committing the
* transaction whilst allowing state loss.<br>
*
* I would recommend you use {@link #show(FragmentTransaction, String)} most of the time but
* this is for dialogs you reallly don't care about. (Debug/Tracking/Adverts etc.)
*
* @param transaction
* An existing transaction in which to add the fragment.
* @param tag
* The tag for this fragment, as per
* {@link FragmentTransaction#add(Fragment, String) FragmentTransaction.add}.
* @return Returns the identifier of the committed transaction, as per
* {@link FragmentTransaction#commit() FragmentTransaction.commit()}.
* @see DialogFragmentStateless#showAllowingStateLoss(FragmentManager, String)
*/
public int showAllowingStateLoss(FragmentTransaction transaction, String tag)
{
mDismissed = false;
mShownByMe = true;
transaction.add(this, tag);
mViewDestroyed = false;
mBackStackId = transaction.commitAllowingStateLoss();
return mBackStackId;
}
/**
* Display the dialog, adding the fragment to the given FragmentManager. This is a convenience
* for explicitly creating a transaction, adding the fragment to it with the given tag, and
* committing it without careing about state. This does <em>not</em> add the transaction to the
* back stack. When the fragment is dismissed, a new transaction will be executed to remove it
* from the activity.<br>
*
* I would recommend you use {@link #show(FragmentManager, String)} most of the time but this is
* for dialogs you reallly don't care about. (Debug/Tracking/Adverts etc.)
*
*
* @param manager
* The FragmentManager this fragment will be added to.
* @param tag
* The tag for this fragment, as per
* {@link FragmentTransaction#add(Fragment, String) FragmentTransaction.add}.
* @see DialogFragmentStateless#showAllowingStateLoss(FragmentTransaction, String)
*/
public void showAllowingStateLoss(FragmentManager manager, String tag)
{
mDismissed = false;
mShownByMe = true;
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commitAllowingStateLoss();
}
}
| 41.951613 | 100 | 0.672434 |
84aa3be42c5f2d5a5f914a606526773e9681d7d3 | 2,409 | package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("37")
class Record_295 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 295: FirstName is Mitsi")
void FirstNameOfRecord295() {
assertEquals("Mitsi", customers.get(294).getFirstName());
}
@Test
@DisplayName("Record 295: LastName is Molleda")
void LastNameOfRecord295() {
assertEquals("Molleda", customers.get(294).getLastName());
}
@Test
@DisplayName("Record 295: Company is Jackson, Debra O Esq")
void CompanyOfRecord295() {
assertEquals("Jackson, Debra O Esq", customers.get(294).getCompany());
}
@Test
@DisplayName("Record 295: Address is 8825 Runamuck Pl")
void AddressOfRecord295() {
assertEquals("8825 Runamuck Pl", customers.get(294).getAddress());
}
@Test
@DisplayName("Record 295: City is Anchorage")
void CityOfRecord295() {
assertEquals("Anchorage", customers.get(294).getCity());
}
@Test
@DisplayName("Record 295: County is Anchorage")
void CountyOfRecord295() {
assertEquals("Anchorage", customers.get(294).getCounty());
}
@Test
@DisplayName("Record 295: State is AK")
void StateOfRecord295() {
assertEquals("AK", customers.get(294).getState());
}
@Test
@DisplayName("Record 295: ZIP is 99502")
void ZIPOfRecord295() {
assertEquals("99502", customers.get(294).getZIP());
}
@Test
@DisplayName("Record 295: Phone is 907-562-5969")
void PhoneOfRecord295() {
assertEquals("907-562-5969", customers.get(294).getPhone());
}
@Test
@DisplayName("Record 295: Fax is 907-562-2526")
void FaxOfRecord295() {
assertEquals("907-562-2526", customers.get(294).getFax());
}
@Test
@DisplayName("Record 295: Email is mitsi@molleda.com")
void EmailOfRecord295() {
assertEquals("mitsi@molleda.com", customers.get(294).getEmail());
}
@Test
@DisplayName("Record 295: Web is http://www.mitsimolleda.com")
void WebOfRecord295() {
assertEquals("http://www.mitsimolleda.com", customers.get(294).getWeb());
}
}
| 25.09375 | 75 | 0.728518 |
31fed9f8dfe802c5367018ec36f9a585a6222274 | 14,901 | /******************************************************************************
* Product: iDempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2012 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.idempiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.product;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.model.I_M_AttributeSet;
import org.compiere.orm.MTable;
import org.compiere.orm.PO;
import org.idempiere.orm.I_Persistent;
import org.idempiere.common.util.KeyNamePair;
import org.idempiere.orm.POInfo;
/** Generated Model for M_AttributeSet
* @author iDempiere (generated)
* @version Release 5.1 - $Id$ */
public class X_M_AttributeSet extends PO implements I_M_AttributeSet, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20171031L;
/** Standard Constructor */
public X_M_AttributeSet (Properties ctx, int M_AttributeSet_ID, String trxName)
{
super (ctx, M_AttributeSet_ID, trxName);
/** if (M_AttributeSet_ID == 0)
{
setIsGuaranteeDate (false);
setIsGuaranteeDateMandatory (false);
setIsInstanceAttribute (false);
setIsLot (false);
setIsLotMandatory (false);
setIsSerNo (false);
setIsSerNoMandatory (false);
setMandatoryType (null);
setM_AttributeSet_ID (0);
setName (null);
} */
}
/** Load Constructor */
public X_M_AttributeSet (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_AttributeSet[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Guarantee Days.
@param GuaranteeDays
Number of days the product is guaranteed or available
*/
public void setGuaranteeDays (int GuaranteeDays)
{
set_Value (COLUMNNAME_GuaranteeDays, Integer.valueOf(GuaranteeDays));
}
/** Get Guarantee Days.
@return Number of days the product is guaranteed or available
*/
public int getGuaranteeDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GuaranteeDays);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set IsAutoGenerateLot.
@param IsAutoGenerateLot IsAutoGenerateLot */
public void setIsAutoGenerateLot (boolean IsAutoGenerateLot)
{
set_Value (COLUMNNAME_IsAutoGenerateLot, Boolean.valueOf(IsAutoGenerateLot));
}
/** Get IsAutoGenerateLot.
@return IsAutoGenerateLot */
public boolean isAutoGenerateLot ()
{
Object oo = get_Value(COLUMNNAME_IsAutoGenerateLot);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Guarantee Date.
@param IsGuaranteeDate
Product has Guarantee or Expiry Date
*/
public void setIsGuaranteeDate (boolean IsGuaranteeDate)
{
set_Value (COLUMNNAME_IsGuaranteeDate, Boolean.valueOf(IsGuaranteeDate));
}
/** Get Guarantee Date.
@return Product has Guarantee or Expiry Date
*/
public boolean isGuaranteeDate ()
{
Object oo = get_Value(COLUMNNAME_IsGuaranteeDate);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Mandatory Guarantee Date.
@param IsGuaranteeDateMandatory
The entry of a Guarantee Date is mandatory when creating a Product Instance
*/
public void setIsGuaranteeDateMandatory (boolean IsGuaranteeDateMandatory)
{
set_Value (COLUMNNAME_IsGuaranteeDateMandatory, Boolean.valueOf(IsGuaranteeDateMandatory));
}
/** Get Mandatory Guarantee Date.
@return The entry of a Guarantee Date is mandatory when creating a Product Instance
*/
public boolean isGuaranteeDateMandatory ()
{
Object oo = get_Value(COLUMNNAME_IsGuaranteeDateMandatory);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Instance Attribute.
@param IsInstanceAttribute
The product attribute is specific to the instance (like Serial No, Lot or Guarantee Date)
*/
public void setIsInstanceAttribute (boolean IsInstanceAttribute)
{
set_Value (COLUMNNAME_IsInstanceAttribute, Boolean.valueOf(IsInstanceAttribute));
}
/** Get Instance Attribute.
@return The product attribute is specific to the instance (like Serial No, Lot or Guarantee Date)
*/
public boolean isInstanceAttribute ()
{
Object oo = get_Value(COLUMNNAME_IsInstanceAttribute);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Lot.
@param IsLot
The product instances have a Lot Number
*/
public void setIsLot (boolean IsLot)
{
set_Value (COLUMNNAME_IsLot, Boolean.valueOf(IsLot));
}
/** Get Lot.
@return The product instances have a Lot Number
*/
public boolean isLot ()
{
Object oo = get_Value(COLUMNNAME_IsLot);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Mandatory Lot.
@param IsLotMandatory
The entry of Lot info is mandatory when creating a Product Instance
*/
public void setIsLotMandatory (boolean IsLotMandatory)
{
set_Value (COLUMNNAME_IsLotMandatory, Boolean.valueOf(IsLotMandatory));
}
/** Get Mandatory Lot.
@return The entry of Lot info is mandatory when creating a Product Instance
*/
public boolean isLotMandatory ()
{
Object oo = get_Value(COLUMNNAME_IsLotMandatory);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Serial No.
@param IsSerNo
The product instances have Serial Numbers
*/
public void setIsSerNo (boolean IsSerNo)
{
set_Value (COLUMNNAME_IsSerNo, Boolean.valueOf(IsSerNo));
}
/** Get Serial No.
@return The product instances have Serial Numbers
*/
public boolean isSerNo ()
{
Object oo = get_Value(COLUMNNAME_IsSerNo);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Mandatory Serial No.
@param IsSerNoMandatory
The entry of a Serial No is mandatory when creating a Product Instance
*/
public void setIsSerNoMandatory (boolean IsSerNoMandatory)
{
set_Value (COLUMNNAME_IsSerNoMandatory, Boolean.valueOf(IsSerNoMandatory));
}
/** Get Mandatory Serial No.
@return The entry of a Serial No is mandatory when creating a Product Instance
*/
public boolean isSerNoMandatory ()
{
Object oo = get_Value(COLUMNNAME_IsSerNoMandatory);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Lot Char End Overwrite.
@param LotCharEOverwrite
Lot/Batch End Indicator overwrite - default »
*/
public void setLotCharEOverwrite (String LotCharEOverwrite)
{
set_Value (COLUMNNAME_LotCharEOverwrite, LotCharEOverwrite);
}
/** Get Lot Char End Overwrite.
@return Lot/Batch End Indicator overwrite - default »
*/
public String getLotCharEOverwrite ()
{
return (String)get_Value(COLUMNNAME_LotCharEOverwrite);
}
/** Set Lot Char Start Overwrite.
@param LotCharSOverwrite
Lot/Batch Start Indicator overwrite - default «
*/
public void setLotCharSOverwrite (String LotCharSOverwrite)
{
set_Value (COLUMNNAME_LotCharSOverwrite, LotCharSOverwrite);
}
/** Get Lot Char Start Overwrite.
@return Lot/Batch Start Indicator overwrite - default «
*/
public String getLotCharSOverwrite ()
{
return (String)get_Value(COLUMNNAME_LotCharSOverwrite);
}
/** MandatoryType AD_Reference_ID=324 */
public static final int MANDATORYTYPE_AD_Reference_ID=324;
/** Not Mandatory = N */
public static final String MANDATORYTYPE_NotMandatory = "N";
/** Always Mandatory = Y */
public static final String MANDATORYTYPE_AlwaysMandatory = "Y";
/** When Shipping = S */
public static final String MANDATORYTYPE_WhenShipping = "S";
/** Set Mandatory Type.
@param MandatoryType
The specification of a Product Attribute Instance is mandatory
*/
public void setMandatoryType (String MandatoryType)
{
set_Value (COLUMNNAME_MandatoryType, MandatoryType);
}
/** Get Mandatory Type.
@return The specification of a Product Attribute Instance is mandatory
*/
public String getMandatoryType ()
{
return (String)get_Value(COLUMNNAME_MandatoryType);
}
/** Set Attribute Set.
@param M_AttributeSet_ID
Product Attribute Set
*/
public void setM_AttributeSet_ID (int M_AttributeSet_ID)
{
if (M_AttributeSet_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, Integer.valueOf(M_AttributeSet_ID));
}
/** Get Attribute Set.
@return Product Attribute Set
*/
public int getM_AttributeSet_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSet_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set M_AttributeSet_UU.
@param M_AttributeSet_UU M_AttributeSet_UU */
public void setM_AttributeSet_UU (String M_AttributeSet_UU)
{
set_Value (COLUMNNAME_M_AttributeSet_UU, M_AttributeSet_UU);
}
/** Get M_AttributeSet_UU.
@return M_AttributeSet_UU */
public String getM_AttributeSet_UU ()
{
return (String)get_Value(COLUMNNAME_M_AttributeSet_UU);
}
public org.compiere.model.I_M_LotCtl getM_LotCtl() throws RuntimeException
{
return (org.compiere.model.I_M_LotCtl)MTable.get(getCtx(), org.compiere.model.I_M_LotCtl.Table_Name)
.getPO(getM_LotCtl_ID(), get_TrxName()); }
/** Set Lot Control.
@param M_LotCtl_ID
Product Lot Control
*/
public void setM_LotCtl_ID (int M_LotCtl_ID)
{
if (M_LotCtl_ID < 1)
set_Value (COLUMNNAME_M_LotCtl_ID, null);
else
set_Value (COLUMNNAME_M_LotCtl_ID, Integer.valueOf(M_LotCtl_ID));
}
/** Get Lot Control.
@return Product Lot Control
*/
public int getM_LotCtl_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtl_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_M_SerNoCtl getM_SerNoCtl() throws RuntimeException
{
return (org.compiere.model.I_M_SerNoCtl)MTable.get(getCtx(), org.compiere.model.I_M_SerNoCtl.Table_Name)
.getPO(getM_SerNoCtl_ID(), get_TrxName()); }
/** Set Serial No Control.
@param M_SerNoCtl_ID
Product Serial Number Control
*/
public void setM_SerNoCtl_ID (int M_SerNoCtl_ID)
{
if (M_SerNoCtl_ID < 1)
set_Value (COLUMNNAME_M_SerNoCtl_ID, null);
else
set_Value (COLUMNNAME_M_SerNoCtl_ID, Integer.valueOf(M_SerNoCtl_ID));
}
/** Get Serial No Control.
@return Product Serial Number Control
*/
public int getM_SerNoCtl_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_SerNoCtl_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set SerNo Char End Overwrite.
@param SerNoCharEOverwrite
Serial Number End Indicator overwrite - default empty
*/
public void setSerNoCharEOverwrite (String SerNoCharEOverwrite)
{
set_Value (COLUMNNAME_SerNoCharEOverwrite, SerNoCharEOverwrite);
}
/** Get SerNo Char End Overwrite.
@return Serial Number End Indicator overwrite - default empty
*/
public String getSerNoCharEOverwrite ()
{
return (String)get_Value(COLUMNNAME_SerNoCharEOverwrite);
}
/** Set SerNo Char Start Overwrite.
@param SerNoCharSOverwrite
Serial Number Start Indicator overwrite - default #
*/
public void setSerNoCharSOverwrite (String SerNoCharSOverwrite)
{
set_Value (COLUMNNAME_SerNoCharSOverwrite, SerNoCharSOverwrite);
}
/** Get SerNo Char Start Overwrite.
@return Serial Number Start Indicator overwrite - default #
*/
public String getSerNoCharSOverwrite ()
{
return (String)get_Value(COLUMNNAME_SerNoCharSOverwrite);
}
/** Set Use Guarantee Date for Material Policy.
@param UseGuaranteeDateForMPolicy Use Guarantee Date for Material Policy */
public void setUseGuaranteeDateForMPolicy (boolean UseGuaranteeDateForMPolicy)
{
set_Value (COLUMNNAME_UseGuaranteeDateForMPolicy, Boolean.valueOf(UseGuaranteeDateForMPolicy));
}
/** Get Use Guarantee Date for Material Policy.
@return Use Guarantee Date for Material Policy */
public boolean isUseGuaranteeDateForMPolicy ()
{
Object oo = get_Value(COLUMNNAME_UseGuaranteeDateForMPolicy);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | 27.241316 | 106 | 0.703174 |
e38cc69dcc1d43fd2084c409f72179b2bd7cf3e6 | 23,431 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flinkextended.flink.ml.lib.tensorflow;
import org.apache.commons.lang.ArrayUtils;
import org.apache.flink.types.Row;
import org.flinkextended.flink.ml.lib.tensorflow.utils.TensorConversion;
import com.google.common.base.Preconditions;
import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tensorflow.SavedModelBundle;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.proto.framework.ConfigProto;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.proto.framework.MetaGraphDef;
import org.tensorflow.proto.framework.SignatureDef;
import org.tensorflow.proto.framework.TensorInfo;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* TFPredict load tensorflow saved model do inference.
*/
public class TFInference {
private static Logger LOG = LoggerFactory.getLogger(TFInference.class);
private static final String TAG = "serve";
private final String[] inputNames;
private final DataType[] inputDataTypes;
private final int[] inputRanks;
private final String[] inputTensorNames;
private final String[] outputNames;
private DataType[] outputDataTypes;
private final int[] outputRanks;
private final String[] outputTensorNames;
private Properties properties;
private Map<String, Integer> inputNameToRank = new HashMap<>();
private final SavedModelBundle model;
private final SignatureDef modelSig;
private final Set<String> inputTensorNameSet;
private File downloadModelPath;
/***
* TFPredict constructor
* @param modelDir saved model dir
* @param properties some properties
* @param inputNames input field names
* @param inputDataTypes input DataType
* @param outputNames output field names
* @param outputDataTypes output TypeDef
* @throws Exception
*/
public TFInference(String modelDir,
String[] inputNames,
DataType[] inputDataTypes,
int[] inputRanks,
String[] outputNames,
DataType[] outputDataTypes,
int[] outputRanks,
Properties properties)
throws Exception {
this.inputNames = inputNames;
this.inputDataTypes = inputDataTypes;
this.inputRanks = inputRanks;
this.outputNames = outputNames;
this.outputDataTypes = outputDataTypes;
this.outputRanks = outputRanks;
this.properties = properties;
for(int i = 0; i < inputRanks.length; i++){
this.inputRanks[i]++;
}
for(int i = 0; i < outputRanks.length; i++){
this.outputRanks[i]++;
}
for(int i = 0; i < inputNames.length; i++){
inputNameToRank.put(this.inputNames[i], this.inputRanks[i]);
}
// load model
Path modelPath = new Path(modelDir);
String scheme = modelPath.toUri().getScheme();
ConfigProto configProto = ConfigProto.newBuilder()
.setAllowSoftPlacement(true) // allow less GPUs than configured
.build();
// local fs is assumed when no scheme provided
if (StringUtils.isEmpty(scheme) || scheme.equals("file")) {
model = SavedModelBundle.loader(modelDir)
.withConfigProto(configProto)
.withTags(TAG)
.load();
} else if (scheme.equals("hdfs")) {
// download the model from hdfs
FileSystem fs = modelPath.getFileSystem(new Configuration());
downloadModelPath = Files.createTempDir();
Path localPath = new Path(downloadModelPath.getPath(), modelPath.getName());
LOG.info("Downloading model from {} to {}", modelPath, localPath);
fs.copyToLocalFile(modelPath, localPath);
//model = SavedModelBundle.load(localPath.toString(), TAG);
model = SavedModelBundle.loader(localPath.toString())
.withConfigProto(configProto)
.withTags(TAG)
.load();
} else {
throw new IllegalArgumentException("Model URI not supported: " + modelDir);
}
modelSig = MetaGraphDef.parseFrom(model.metaGraphDef().toByteArray()).getSignatureDefOrThrow("serving_default");
logSignature();
inputTensorNameSet = modelSig.getInputsMap().keySet();
inputTensorNames = inputTensorNameSet.toArray(new String[0]);
Set<String> inputNamesSet = new HashSet<>(Arrays.asList(inputNames));
// input tensor names must exist in the input fields
Preconditions.checkArgument(inputNamesSet.containsAll(inputTensorNameSet),
"Invalid input tensor names: " + Arrays.toString(inputTensorNames));
Set<String> outputTensorNameSet = modelSig.getOutputsMap().keySet();
outputTensorNames = outputTensorNameSet.toArray(new String[0]);
// output tensor names must exist in the model
Preconditions.checkArgument(modelSig.getOutputsMap().keySet().containsAll(Arrays.asList(outputTensorNames)),
"Invalid output tensor names: " + Arrays.toString(outputTensorNames));
}
/**
* do tensorflow inference
* @param batchRecord input rows
* @return inference rows
*/
public Row[] inference(List<Object[]> batchRecord) {
if(batchRecord.isEmpty()){
return null;
}else {
Session.Runner runner = model.session().runner();
int size = batchRecord.size();
Row[] rows = new Row[batchRecord.size()];
Map<String, Object> inNameToObjs = new HashMap<>(inputNames.length);
for (int i = 0; i < inputNames.length; i++) {
inNameToObjs.put(inputNames[i], extractCols(batchRecord, i, size, inputRanks[i], inputDataTypes[i]));
}
List<Tensor<?>> toClose = new ArrayList<>(inputTensorNameSet.size() + outputTensorNames.length);
try {
for (int i = 0; i < inputTensorNames.length; i++) {
TensorInfo inputInfo = modelSig.getInputsMap().get(inputTensorNames[i]);
Tensor<?> tensor = TensorConversion.toTensor(inNameToObjs.get(inputTensorNames[i]),
inputInfo, inputNameToRank.get(inputTensorNames[i]));
toClose.add(tensor);
runner.feed(inputInfo.getName(), tensor);
}
for (String outputTensorName : outputTensorNames) {
TensorInfo outputInfo = modelSig.getOutputsMap().get(outputTensorName);
runner.fetch(outputInfo.getName());
}
List<Tensor<?>> outTensors = runner.run();
toClose.addAll(outTensors);
Map<String, Tensor<?>> outNameToTensor = new HashMap<>();
for (int i = 0; i < outputTensorNames.length; i++) {
outNameToTensor.put(outputTensorNames[i], outTensors.get(i));
}
for (int i = 0; i < outputNames.length; i++) {
Object cols;
if (outNameToTensor.containsKey(outputNames[i])) {
cols = TensorConversion.fromTensor(outNameToTensor.get(outputNames[i]));
} else {
cols = inNameToObjs.get(outputNames[i]);
}
for (int j = 0; j < rows.length; j++) {
if (rows[j] == null) {
rows[j] = new Row(outputNames.length);
}
setRowField(rows[j], i, cols, j, outputRanks[i], this.outputDataTypes[i]);
//rows[j].setField(i, cols[j]);
}
}
} catch (Exception e) {
LOG.error("Error in inference: ", e);
} finally {
for (Tensor<?> tensor : toClose) {
tensor.close();
}
toClose.clear();
}
return rows;
}
}
private void setRowField(Row row, int index, Object object, int col, int rank, DataType dataType){
switch (dataType){
case DT_INT32: {
switch (rank){
case 1:{
int[] value = (int[])object;
row.setField(index, value[col]);
return;
}
case 2:{
int[][] value = (int[][])object;
row.setField(index, value[col]);
return;
}
case 3:{
int[][][] value = (int[][][])object;
row.setField(index, value[col]);
return;
}
case 4:{
int[][][][] value = (int[][][][])object;
row.setField(index, value[col]);
return;
}
case 5:{
int[][][][][] value = (int[][][][][])object;
row.setField(index, value[col]);
return;
}
case 6:{
int[][][][][][] value = (int[][][][][][])object;
row.setField(index, value[col]);
return;
}
default:
throw new UnsupportedOperationException(
"dim count can't supported: " + String.valueOf(rank));
}
}
case DT_INT64: {
switch (rank){
case 1:{
long[] value = (long[])object;
row.setField(index, value[col]);
return;
}
case 2:{
long[][] value = (long[][])object;
row.setField(index, value[col]);
return;
}
case 3:{
long[][][] value = (long[][][])object;
row.setField(index, value[col]);
return;
}
case 4:{
long[][][][] value = (long[][][][])object;
row.setField(index, value[col]);
return;
}
case 5:{
long[][][][][] value = (long[][][][][])object;
row.setField(index, value[col]);
return;
}
case 6:{
long[][][][][][] value = (long[][][][][][])object;
row.setField(index, value[col]);
return;
}
default:
throw new UnsupportedOperationException(
"dim count can't supported: " + String.valueOf(rank));
}
}
case DT_FLOAT: {
switch (rank){
case 1:{
float[] value = (float[])object;
row.setField(index, value[col]);
return;
}
case 2:{
float[][] value = (float[][])object;
row.setField(index, value[col]);
return;
}
case 3:{
float[][][] value = (float[][][])object;
row.setField(index, value[col]);
return;
}
case 4:{
float[][][][] value = (float[][][][])object;
row.setField(index, value[col]);
return;
}
case 5:{
float[][][][][] value = (float[][][][][])object;
row.setField(index, value[col]);
return;
}
case 6:{
float[][][][][][] value = (float[][][][][][])object;
row.setField(index, value[col]);
return;
}
default:
throw new UnsupportedOperationException(
"dim count can't supported: " + String.valueOf(rank));
}
}
case DT_DOUBLE: {
switch (rank){
case 1:{
double[] value = (double[])object;
row.setField(index, value[col]);
return;
}
case 2:{
double[][] value = (double[][])object;
row.setField(index, value[col]);
return;
}
case 3:{
double[][][] value = (double[][][])object;
row.setField(index, value[col]);
return;
}
case 4:{
double[][][][] value = (double[][][][])object;
row.setField(index, value[col]);
return;
}
case 5:{
double[][][][][] value = (double[][][][][])object;
row.setField(index, value[col]);
return;
}
case 6:{
double[][][][][][] value = (double[][][][][][])object;
row.setField(index, value[col]);
return;
}
default:
throw new UnsupportedOperationException(
"dim count can't supported: " + String.valueOf(rank));
}
}
case DT_STRING: {
switch (rank){
case 1:{
String[] value = (String[])object;
row.setField(index, value[col]);
return;
}
case 2:{
String[][] value = (String[][])object;
row.setField(index, value[col]);
return;
}
case 3:{
String[][][] value = (String[][][])object;
row.setField(index, value[col]);
return;
}
case 4:{
String[][][][] value = (String[][][][])object;
row.setField(index, value[col]);
return;
}
case 5:{
String[][][][][] value = (String[][][][][])object;
row.setField(index, value[col]);
return;
}
default:
throw new UnsupportedOperationException(
"dim count can't supported: " + String.valueOf(rank));
}
}
default:
throw new UnsupportedOperationException(
"Type can't be converted to tensor: " + dataType.name());
}
}
public void close() throws IOException {
if (model != null) {
model.close();
LOG.info("Model closed");
}
if (downloadModelPath != null) {
FileUtils.deleteQuietly(downloadModelPath);
}
}
private void logSignature() {
int numInputs = modelSig.getInputsCount();
StringBuilder builder = new StringBuilder();
int i = 1;
builder.append("\n----MODEL SIGNATURE--------------------------\n");
builder.append("Inputs:\n");
for (Map.Entry<String, TensorInfo> entry : modelSig.getInputsMap().entrySet()) {
TensorInfo t = entry.getValue();
builder.append(String.format(
"%d of %d: %-20s (Node name in graph: %-20s, type: %s)\n",
i++, numInputs, entry.getKey(), t.getName(), t.getDtype()));
}
int numOutputs = modelSig.getOutputsCount();
i = 1;
builder.append("Outputs:\n");
for (Map.Entry<String, TensorInfo> entry : modelSig.getOutputsMap().entrySet()) {
TensorInfo t = entry.getValue();
builder.append(String.format(
"%d of %d: %-20s (Node name in graph: %-20s, type: %s)\n",
i++, numOutputs, entry.getKey(), t.getName(), t.getDtype()));
}
builder.append("-------------------------------------------------");
System.out.println(builder.toString());
}
private Object extractCols(List<Object[]> cache, int index, int len, int rank, DataType dataType) {
switch (dataType){
case DT_INT32: {
switch (rank){
case 1:{
int[] res = new int[len];
for (int i = 0; i < res.length; i++) {
res[i] = (int)cache.get(i)[index];
}
return res;
}
case 2:{
int[][] res = new int[len][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Integer[]) cache.get(i)[index]);
}
return res;
}
case 3:{
int[][][] res = new int[len][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Integer[][]) cache.get(i)[index]);
}
return res;
}
case 4:{
int[][][][] res = new int[len][][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Integer[][][]) cache.get(i)[index]);
}
return res;
}
case 5:{
int[][][][][] res = new int[len][][][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Integer[][][][]) cache.get(i)[index]);
}
return res;
}
case 6:{
int[][][][][][] res = new int[len][][][][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Integer[][][][][]) cache.get(i)[index]);
}
return res;
}
default:
throw new UnsupportedOperationException(
"dim count can't supported: " + String.valueOf(rank));
}
}
case DT_INT64: {
switch (rank){
case 1:{
long[] res = new long[len];
for (int i = 0; i < res.length; i++) {
res[i] = (long)cache.get(i)[index];
}
return res;
}
case 2:{
long[][] res = new long[len][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Long[]) cache.get(i)[index]);
}
return res;
}
case 3:{
long[][][] res = new long[len][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Long[][]) cache.get(i)[index]);
}
return res;
}
case 4:{
long[][][][] res = new long[len][][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Long[][][]) cache.get(i)[index]);
}
return res;
}
case 5:{
long[][][][][] res = new long[len][][][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Long[][][][]) cache.get(i)[index]);
}
return res;
}
case 6:{
long[][][][][][] res = new long[len][][][][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Long[][][][][]) cache.get(i)[index]);
}
return res;
}
default:
throw new UnsupportedOperationException(
"dim count can't supported: " + String.valueOf(rank));
}
}
case DT_FLOAT: {
switch (rank){
case 1:{
float[] res = new float[len];
for (int i = 0; i < res.length; i++) {
res[i] = (float)cache.get(i)[index];
}
return res;
}
case 2:{
float[][] res = new float[len][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Float[]) cache.get(i)[index]);
}
return res;
}
case 3:{
float[][][] res = new float[len][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Float[][]) cache.get(i)[index]);
}
return res;
}
case 4:{
float[][][][] res = new float[len][][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Float[][][]) cache.get(i)[index]);
}
return res;
}
case 5:{
float[][][][][] res = new float[len][][][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Float[][][][]) cache.get(i)[index]);
}
return res;
}
case 6:{
float[][][][][][] res = new float[len][][][][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Float[][][][][]) cache.get(i)[index]);
}
return res;
}
default:
throw new UnsupportedOperationException(
"dim count can't supported: " + String.valueOf(rank));
}
}
case DT_DOUBLE: {
switch (rank){
case 1:{
double[] res = new double[len];
for (int i = 0; i < res.length; i++) {
res[i] = (double)cache.get(i)[index];
}
return res;
}
case 2:{
double[][] res = new double[len][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Double[]) cache.get(i)[index]);
}
return res;
}
case 3:{
double[][][] res = new double[len][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Double[][]) cache.get(i)[index]);
}
return res;
}
case 4:{
double[][][][] res = new double[len][][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Double[][][]) cache.get(i)[index]);
}
return res;
}
case 5:{
double[][][][][] res = new double[len][][][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Double[][][][]) cache.get(i)[index]);
}
return res;
}
case 6:{
double[][][][][][] res = new double[len][][][][][];
for (int i = 0; i < res.length; i++) {
res[i] = toPrimitive((Double[][][][][]) cache.get(i)[index]);
}
return res;
}
default:
throw new UnsupportedOperationException(
"dim count can't supported: " + String.valueOf(rank));
}
}
case DT_STRING: {
switch (rank){
case 1:{
String[] res = new String[len];
for (int i = 0; i < res.length; i++) {
res[i] = (String)cache.get(i)[index];
}
return res;
}
case 2:{
String[][] res = new String[len][];
for (int i = 0; i < res.length; i++) {
res[i] = (String[])cache.get(i)[index];
}
return res;
}
case 3:{
String[][][] res = new String[len][][];
for (int i = 0; i < res.length; i++) {
res[i] = (String[][])cache.get(i)[index];
}
return res;
}
case 4:{
String[][][][] res = new String[len][][][];
for (int i = 0; i < res.length; i++) {
res[i] = (String[][][])cache.get(i)[index];
}
return res;
}
case 5:{
String[][][][][] res = new String[len][][][][];
for (int i = 0; i < res.length; i++) {
res[i] = (String[][][][])cache.get(i)[index];
}
return res;
}
default:
throw new UnsupportedOperationException(
"dim count can't supported: " + String.valueOf(rank));
}
}
default:
throw new UnsupportedOperationException(
"Type can't be converted to tensor: " + dataType.name());
}
}
// helper functions to convert the nd-array of Object to primitives
private float[] toPrimitive(Float[] floats) {
return ArrayUtils.toPrimitive(floats);
}
private float[][] toPrimitive(Float[][] floats) {
return Arrays.stream(floats).map(this::toPrimitive).toArray(float[][]::new);
}
private float[][][] toPrimitive(Float[][][] floats) {
return Arrays.stream(floats).map(this::toPrimitive).toArray(float[][][]::new);
}
private float[][][][] toPrimitive(Float[][][][] floats) {
return Arrays.stream(floats).map(this::toPrimitive).toArray(float[][][][]::new);
}
private float[][][][][] toPrimitive(Float[][][][][] floats) {
return Arrays.stream(floats).map(this::toPrimitive).toArray(float[][][][][]::new);
}
private double[] toPrimitive(Double[] doubles) {
return ArrayUtils.toPrimitive(doubles);
}
private double[][] toPrimitive(Double[][] doubles) {
return Arrays.stream(doubles).map(this::toPrimitive).toArray(double[][]::new);
}
private double[][][] toPrimitive(Double[][][] doubles) {
return Arrays.stream(doubles).map(this::toPrimitive).toArray(double[][][]::new);
}
private double[][][][] toPrimitive(Double[][][][] doubles) {
return Arrays.stream(doubles).map(this::toPrimitive).toArray(double[][][][]::new);
}
private double[][][][][] toPrimitive(Double[][][][][] doubles) {
return Arrays.stream(doubles).map(this::toPrimitive).toArray(double[][][][][]::new);
}
private int[] toPrimitive(Integer[] ints) {
return ArrayUtils.toPrimitive(ints);
}
private int[][] toPrimitive(Integer[][] ints) {
return Arrays.stream(ints).map(this::toPrimitive).toArray(int[][]::new);
}
private int[][][] toPrimitive(Integer[][][] ints) {
return Arrays.stream(ints).map(this::toPrimitive).toArray(int[][][]::new);
}
private int[][][][] toPrimitive(Integer[][][][] ints) {
return Arrays.stream(ints).map(this::toPrimitive).toArray(int[][][][]::new);
}
private int[][][][][] toPrimitive(Integer[][][][][] ints) {
return Arrays.stream(ints).map(this::toPrimitive).toArray(int[][][][][]::new);
}
private long[] toPrimitive(Long[] longs) {
return ArrayUtils.toPrimitive(longs);
}
private long[][] toPrimitive(Long[][] longs) {
return Arrays.stream(longs).map(this::toPrimitive).toArray(long[][]::new);
}
private long[][][] toPrimitive(Long[][][] longs) {
return Arrays.stream(longs).map(this::toPrimitive).toArray(long[][][]::new);
}
private long[][][][] toPrimitive(Long[][][][] longs) {
return Arrays.stream(longs).map(this::toPrimitive).toArray(long[][][][]::new);
}
private long[][][][][] toPrimitive(Long[][][][][] longs) {
return Arrays.stream(longs).map(this::toPrimitive).toArray(long[][][][][]::new);
}
}
| 30.509115 | 114 | 0.585293 |
774cf396f48fddc23adc935b6a142b0a6938a483 | 3,172 | package client;
import common.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Client implements ClientInterface {
private ClientWindow window;
private Comms comms;
private User user = null;
public Client(Socket socket) {
this.comms = new Comms(socket);
}
public void build(ClientWindow window) {
this.window = window;
}
public User getUser() { return user; }
@Override
public User register(String username, String password, String address, Postcode postcode) {
User user = comms.registerNewUser(username, password, address, postcode);
this.user = user;
return user;
}
@Override
public User login(String username, String password) {
User user = comms.login(username, password);
this.user = user;
return user;
}
@Override
public List<Postcode> getPostcodes() {
return comms.getPostcodes();
}
@Override
public List<Dish> getDishes() {
return comms.getDishes();
}
@Override
public String getDishDescription(Dish dish) {
return dish.getDescription();
}
@Override
public Number getDishPrice(Dish dish) {
return dish.getPrice();
}
@Override
public Map<Dish, Number> getBasket(User user) {
return user.getBasket();
}
@Override
public Number getBasketCost(User user) {
ArrayList<Integer> prices = new ArrayList<>();
int price = 0;
user.getBasket().forEach((key, value) -> prices.add((int) key.getPrice() * (int)value));
for (Integer integer : prices) {
price += integer;
}
return price;
}
@Override
public void addDishToBasket(User user, Dish dish, Number quantity) {
user.addToBasket(dish, quantity);
notifyUpdate();
}
@Override
public Order checkoutBasket(User user) {
return comms.makeOrder(this.user, getBasketCost(this.user));
}
@Override
public void updateDishInBasket(User user, Dish dish, Number quantity) {
user.getBasket().put(dish, quantity);
notifyUpdate();
}
@Override
public void clearBasket(User user) {
user.getBasket().clear();
notifyUpdate();
}
@Override
public List<Order> getOrders(User user) {
return comms.getOrders();
}
@Override
public boolean isOrderComplete(Order order) {
return order.isComplete();
}
@Override
public String getOrderStatus(Order order) {
return order.getStatus();
}
@Override
public Number getOrderCost(Order order) {
return order.getCost();
}
@Override
public void cancelOrder(Order order) {
comms.cancelOrder(order);
notifyUpdate();
}
@Override
public void addUpdateListener(UpdateListener listener) { }
@Override
public void notifyUpdate() {
window.updated(new UpdateEvent());
}
}
| 24.030303 | 97 | 0.596784 |
b4a7c4f33e1507f5ce3a7154748f6ae0dfd017ff | 6,158 | /*
* The MIT License
*
* Copyright (c) 2016, AbsInt Angewandte Informatik GmbH
* Author: Dr.-Ing. Joerg Herter
* Email: herter@absint.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.absint.astree;
import java.io.*;
/**
* Stores an analysis (result) summary and provides an interface to the analysis result for the
* Astrée PlugIn classes.
*
*
* @author AbsInt Angewandte Informatik GmbH
*/
public class AnalysisSummary {
private int numberOfErrors;
private int numberOfAlarms;
private int numberOfFlowAnomalies;
private int numberOfRuleViolations;
private int numberOfTrueAlarms; // not implemented yet
private int numberOfUncommentedAlarms; // not implemented yet
/**
* Private constructor.
*/
private AnalysisSummary(int numberOfErrors, int numberOfAlarms,
int numberOfFlowAnomalies, int numberOfRuleViolations,
int numberOfTrueAlarms, int numberOfUncommentedAlarms ) {
this.numberOfErrors = numberOfErrors;
this.numberOfAlarms = numberOfAlarms;
this.numberOfFlowAnomalies = numberOfFlowAnomalies;
this.numberOfRuleViolations = numberOfRuleViolations;
this.numberOfTrueAlarms = numberOfTrueAlarms;
this.numberOfUncommentedAlarms = numberOfUncommentedAlarms;
}
/**
* Constructs an AnalyisSummary object from a report file (txt version).
*
* @param path Path (as {@link java.lang.String}) to the Astrée text report
* from which the object is to be constructed.
* @return AnalysisSummary object providing easy access to data of an Astrée report
*/
static public AnalysisSummary readFromReportFile(String path) {
int numberOfErrors = 0;
int numberOfAlarms = 0;
int numberOfFlowAnomalies = 0;
int numberOfRuleViolations = 0;
int numberOfTrueAlarms = 0; // not implemented yet
int numberOfUncommentedAlarms = 0; // not implemented yet
try{
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(path), "UTF-8" ));
String line = br.readLine();
boolean skipping = true;
while(line != null) {
if(!skipping) {
if(line.trim().startsWith("Errors:"))
numberOfErrors = Integer.parseInt(
line.substring(line.indexOf(":") + 1, line.length()).trim());
else if(line.trim().startsWith("Run-time errors:"))
numberOfAlarms = Integer.parseInt(
line.substring(line.indexOf(":") + 1, line.length()).trim());
else if(line.trim().startsWith("Flow anomalies:"))
numberOfFlowAnomalies = Integer.parseInt(
line.substring(line.indexOf(":") + 1, line.length()).trim());
else if(line.trim().startsWith("Rule violations:"))
numberOfRuleViolations = Integer.parseInt(
line.substring(line.indexOf(":") + 1, line.length()).trim());
}
// skip report until Summary section is reached
if(skipping && line.trim().startsWith("/* Result summary */"))
skipping = false;
line = br.readLine();
}
br.close();
} catch(IOException e) {
return null;
}
return new AnalysisSummary(numberOfErrors, numberOfAlarms,
numberOfFlowAnomalies, numberOfRuleViolations,
numberOfTrueAlarms, numberOfUncommentedAlarms );
}
/*
* Interface for Astrée PlugIn class.
*/
/**
* Returns the number of reported definite runtime errors ("errors").
*
* @return int
*/
public int getNumberOfErrors() {
return this.numberOfErrors;
}
/**
* Returns the number of reported potential runtime errors ("alarms").
*
* @return int
*/
public int getNumberOfAlarms() {
return this.numberOfAlarms;
}
/**
* Returns the number of reported flow anaomalies ("Type D alarms").
*
* @return int
*/
public int getNumberOfFlowAnomalies() {
return this.numberOfFlowAnomalies;
}
/**
* Returns the number of reported rule violations ("Type R alarms").
*
* @return int
*/
public int getNumberOfRuleViolations() {
return this.numberOfRuleViolations;
}
/**
* Returns the number of reported potential runtime errors ("alarms") classified as "true".
*
* @return int
*/
public int getNumberOfTrueAlarms() {
return this.numberOfTrueAlarms;
}
/**
* Returns the number of reported potential runtime errors ("alarms") not commented.
*
* @return int
*/
public int getNumberOfUncommentedAlarms() {
return this.numberOfUncommentedAlarms;
}
}
| 35.802326 | 110 | 0.620981 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.