text
stringlengths 10
2.72M
|
|---|
package retrogene.utilities;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;
public class QualityChecker {
Hashtable<Character,Integer> qualityTable;
public QualityChecker() throws IOException {
qualityTable = loadQualities();
}
public double qualityString(String errorString) {
double quality = 0;
double totalQuals = 0;
char charArray[] = errorString.toCharArray();
for (char itr : charArray) {
totalQuals++;
quality+=qualityTable.get(itr);
}
quality/=totalQuals;
return quality;
}
public Hashtable<Character,Integer> loadQualities() throws IOException {
BufferedReader qualityStream = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/retrogene/utilities/importFiles/qualities.txt"), "UTF-8"));
Hashtable<Character,Integer> qualityTable = new Hashtable<Character,Integer>();
String myLine;
String data[];
try {
while((myLine = qualityStream.readLine()) != null) {
data = myLine.split("\t");
qualityTable.put(data[0].charAt(0), Integer.parseInt(data[1]));
}
} catch (IOException e) {
e.printStackTrace();
}
qualityStream.close();
return qualityTable;
}
}
|
package Node;
public class LinkList {
public static Node GreateLink(){
Node a=new Node(1);
Node b=new Node(2);
Node c=new Node(3);
Node d=new Node(4);
a.next=b;
b.next=c;
c.next=d;
d.next=null;
return a;
}
//1. 遍历链表, 打印链表的每个元素
public static void TraverseE(Node head){
for(Node cur = head;cur!=null;cur=cur.next){
System.out.print(cur.val+" ");
}
}
// 2. 遍历链表, 找到链表的最后一个节点
public static Node TraverseL(Node head){
Node cur=head;
while(cur!=null && cur.next!=null){
cur = cur.next;
}
return cur;
}
//3. 遍历链表, 找到链表的倒数第二个节点
public static Node TraverseLS(Node head){
Node cur=head;
while(cur!=null && cur.next!=null && cur.next.next!=null){
cur = cur.next;
}
return cur;
}
//4.找到链表的第N个节点
public static Node TraverseN(Node head,int index){
Node cur=head;
if(index>=Length(head))
return null;
for (int i=1;i<index;i++){
cur=cur.next;
}
return cur;
}
//5.计算链表的长度
public static int Length(Node head){
int count=0;
for (Node cur =head;cur!=null;cur=cur.next){
count++;
}
return count;
}
//6.遍历链表,查找链表上是否存在某个元素
public static boolean Contains(Node head,int num){
Node cur =head;
for (;cur!=null;cur=cur.next){
if(cur.val==num){
return true;
}
}
return false;
}
public static void main(String[] args) {
Node head=GreateLink();
TraverseE(head);
System.out.println();
Node cur = TraverseL(head);
System.out.println(cur);
Node cur1 = TraverseLS(head);
System.out.println(cur1);
Node cur2= TraverseN(head,6);
System.out.println(cur2);
System.out.println(Length(head));
System.out.println(Contains(head,4));
}
}
|
/**
* 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.hadoop.mapred;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.mapred.JobStatusChangeEvent.EventType;
import org.apache.hadoop.mapreduce.Cluster.JobTrackerStatus;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.mapreduce.server.jobtracker.JTConfig;
import org.apache.hadoop.mapreduce.server.jobtracker.TaskTracker;
import org.apache.hadoop.mapreduce.split.JobSplit;
public class TestJobQueueTaskScheduler extends TestCase {
private static int jobCounter;
private static int taskCounter;
static void resetCounters() {
jobCounter = 0;
taskCounter = 0;
}
static class FakeJobInProgress extends JobInProgress {
private FakeTaskTrackerManager taskTrackerManager;
public FakeJobInProgress(JobConf jobConf,
FakeTaskTrackerManager taskTrackerManager, JobTracker jt)
throws IOException {
super(new JobID("test", ++jobCounter), jobConf, jt);
this.taskTrackerManager = taskTrackerManager;
this.startTime = System.currentTimeMillis();
this.status = new JobStatus(getJobID(), 0f, 0f, JobStatus.PREP,
jobConf.getUser(),
jobConf.getJobName(), "", "");
this.status.setJobPriority(JobPriority.NORMAL);
this.status.setStartTime(startTime);
}
@Override
public synchronized void initTasks() throws IOException {
// do nothing
}
@Override
public Task obtainNewLocalMapTask(TaskTrackerStatus tts, int clusterSize,
int ignored)
throws IOException {
return obtainNewMapTask(tts, clusterSize, ignored);
}
@Override
public Task obtainNewNonLocalMapTask(TaskTrackerStatus tts, int clusterSize,
int ignored)
throws IOException {
return obtainNewMapTask(tts, clusterSize, ignored);
}
@Override
public Task obtainNewMapTask(final TaskTrackerStatus tts, int clusterSize,
int ignored) throws IOException {
TaskAttemptID attemptId = getTaskAttemptID(TaskType.MAP);
Task task = new MapTask("", attemptId, 0, new JobSplit.TaskSplitIndex(), 1) {
@Override
public String toString() {
return String.format("%s on %s", getTaskID(), tts.getTrackerName());
}
};
taskTrackerManager.update(tts.getTrackerName(), task);
runningMapTasks++;
return task;
}
@Override
public Task obtainNewReduceTask(final TaskTrackerStatus tts,
int clusterSize, int ignored) throws IOException {
TaskAttemptID attemptId = getTaskAttemptID(TaskType.REDUCE);
Task task = new ReduceTask("", attemptId, 0, 10, 1) {
@Override
public String toString() {
return String.format("%s on %s", getTaskID(), tts.getTrackerName());
}
};
taskTrackerManager.update(tts.getTrackerName(), task);
runningReduceTasks++;
return task;
}
private TaskAttemptID getTaskAttemptID(TaskType type) {
JobID jobId = getJobID();
return new TaskAttemptID(jobId.getJtIdentifier(),
jobId.getId(), type, ++taskCounter, 0);
}
}
static class FakeTaskTrackerManager implements TaskTrackerManager {
int maps = 0;
int reduces = 0;
int maxMapTasksPerTracker = 2;
int maxReduceTasksPerTracker = 2;
List<JobInProgressListener> listeners =
new ArrayList<JobInProgressListener>();
QueueManager queueManager;
private Map<String, TaskTracker> trackers =
new HashMap<String, TaskTracker>();
public FakeTaskTrackerManager() {
JobConf conf = new JobConf();
queueManager = new QueueManager(conf);
TaskTracker tt1 = new TaskTracker("tt1");
tt1.setStatus(new TaskTrackerStatus("tt1", "tt1.host", 1,
new ArrayList<TaskStatus>(), 0,
maxMapTasksPerTracker,
maxReduceTasksPerTracker));
trackers.put("tt1", tt1);
TaskTracker tt2 = new TaskTracker("tt2");
tt2.setStatus(new TaskTrackerStatus("tt2", "tt2.host", 2,
new ArrayList<TaskStatus>(), 0,
maxMapTasksPerTracker,
maxReduceTasksPerTracker));
trackers.put("tt2", tt2);
}
@Override
public ClusterStatus getClusterStatus() {
int numTrackers = trackers.size();
return new ClusterStatus(numTrackers, 0,
10 * 60 * 1000,
maps, reduces,
numTrackers * maxMapTasksPerTracker,
numTrackers * maxReduceTasksPerTracker,
JobTrackerStatus.RUNNING);
}
@Override
public int getNumberOfUniqueHosts() {
return 0;
}
@Override
public Collection<TaskTrackerStatus> taskTrackers() {
List<TaskTrackerStatus> statuses = new ArrayList<TaskTrackerStatus>();
for (TaskTracker tt : trackers.values()) {
statuses.add(tt.getStatus());
}
return statuses;
}
@Override
public void addJobInProgressListener(JobInProgressListener listener) {
listeners.add(listener);
}
@Override
public void removeJobInProgressListener(JobInProgressListener listener) {
listeners.remove(listener);
}
@Override
public QueueManager getQueueManager() {
return queueManager;
}
@Override
public int getNextHeartbeatInterval() {
return JTConfig.JT_HEARTBEAT_INTERVAL_MIN_DEFAULT;
}
@Override
public void killJob(JobID jobid) {
return;
}
@Override
public JobInProgress getJob(JobID jobid) {
return null;
}
@Override
public boolean killTask(TaskAttemptID attemptId, boolean shouldFail) {
return true;
}
public void initJob(JobInProgress job) {
// do nothing
}
public void failJob(JobInProgress job) {
// do nothing
}
// Test methods
public void submitJob(JobInProgress job) throws IOException {
for (JobInProgressListener listener : listeners) {
listener.jobAdded(job);
}
}
public TaskTracker getTaskTracker(String trackerID) {
return trackers.get(trackerID);
}
public void update(String taskTrackerName, final Task t) {
if (t.isMapTask()) {
maps++;
} else {
reduces++;
}
TaskStatus status = new TaskStatus() {
@Override
public boolean getIsMap() {
return t.isMapTask();
}
@Override
public void addFetchFailedMap(TaskAttemptID mapTaskId) {
}
};
status.setRunState(TaskStatus.State.RUNNING);
trackers.get(taskTrackerName).getStatus().getTaskReports().add(status);
}
}
protected JobConf jobConf;
protected TaskScheduler scheduler;
private FakeTaskTrackerManager taskTrackerManager;
@Override
protected void setUp() throws Exception {
resetCounters();
jobConf = new JobConf();
jobConf.setNumMapTasks(10);
jobConf.setNumReduceTasks(10);
taskTrackerManager = new FakeTaskTrackerManager();
scheduler = createTaskScheduler();
scheduler.setConf(jobConf);
scheduler.setTaskTrackerManager(taskTrackerManager);
scheduler.start();
}
@Override
protected void tearDown() throws Exception {
if (scheduler != null) {
scheduler.terminate();
}
}
protected TaskScheduler createTaskScheduler() {
return new JobQueueTaskScheduler();
}
static void submitJobs(FakeTaskTrackerManager taskTrackerManager, JobConf jobConf,
int numJobs, int state)
throws IOException {
for (int i = 0; i < numJobs; i++) {
JobInProgress job = new FakeJobInProgress(jobConf, taskTrackerManager,
UtilsForTests.getJobTracker());
job.getStatus().setRunState(state);
taskTrackerManager.submitJob(job);
}
}
public void testTaskNotAssignedWhenNoJobsArePresent() throws IOException {
assertEquals(0, scheduler.assignTasks(tracker(taskTrackerManager, "tt1")).size());
}
public void testNonRunningJobsAreIgnored() throws IOException {
submitJobs(taskTrackerManager, jobConf, 1, JobStatus.PREP);
submitJobs(taskTrackerManager, jobConf, 1, JobStatus.SUCCEEDED);
submitJobs(taskTrackerManager, jobConf, 1, JobStatus.FAILED);
submitJobs(taskTrackerManager, jobConf, 1, JobStatus.KILLED);
assertEquals(0, scheduler.assignTasks(tracker(taskTrackerManager, "tt1")).size());
}
public void testDefaultTaskAssignment() throws IOException {
submitJobs(taskTrackerManager, jobConf, 2, JobStatus.RUNNING);
// All slots are filled with job 1
checkAssignment(scheduler, tracker(taskTrackerManager, "tt1"),
new String[] {"attempt_test_0001_m_000001_0 on tt1",
"attempt_test_0001_m_000002_0 on tt1",
"attempt_test_0001_r_000003_0 on tt1"});
checkAssignment(scheduler, tracker(taskTrackerManager, "tt1"),
new String[] {"attempt_test_0001_r_000004_0 on tt1"});
checkAssignment(scheduler, tracker(taskTrackerManager, "tt1"), new String[] {});
checkAssignment(scheduler, tracker(taskTrackerManager, "tt2"),
new String[] {"attempt_test_0001_m_000005_0 on tt2",
"attempt_test_0001_m_000006_0 on tt2",
"attempt_test_0001_r_000007_0 on tt2"});
checkAssignment(scheduler, tracker(taskTrackerManager, "tt2"),
new String[] {"attempt_test_0001_r_000008_0 on tt2"});
checkAssignment(scheduler, tracker(taskTrackerManager, "tt2"), new String[] {});
checkAssignment(scheduler, tracker(taskTrackerManager, "tt1"), new String[] {});
checkAssignment(scheduler, tracker(taskTrackerManager, "tt2"), new String[] {});
}
static TaskTracker tracker(FakeTaskTrackerManager taskTrackerManager,
String taskTrackerName) {
return taskTrackerManager.getTaskTracker(taskTrackerName);
}
static void checkAssignment(TaskScheduler scheduler, TaskTracker taskTracker,
String[] expectedTaskStrings) throws IOException {
List<Task> tasks = scheduler.assignTasks(taskTracker);
assertNotNull(tasks);
assertEquals(expectedTaskStrings.length, tasks.size());
for (int i=0; i < expectedTaskStrings.length; ++i) {
assertEquals(expectedTaskStrings[i], tasks.get(i).toString());
}
}
}
|
package cn.wycclub.exception;
/**
* 用户已存在(异常)
*
* @author WuYuchen
* @create 2018-02-13 23:58
**/
public class UserExistException extends RuntimeException {
public UserExistException() {
}
public UserExistException(String message) {
super(message);
}
public UserExistException(String message, Throwable cause) {
super(message, cause);
}
public UserExistException(Throwable cause) {
super(cause);
}
public UserExistException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
package br.com.utfpr.eventos.validation;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import br.com.utfpr.eventos.models.Event;
public class EventValidation implements Validator {
public boolean supports(Class<?> clazz) {
return Event.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "name", "field.required");
ValidationUtils.rejectIfEmpty(errors, "price", "field.required");
ValidationUtils.rejectIfEmpty(errors, "date", "field.required");
ValidationUtils.rejectIfEmpty(errors, "max", "field.required");
ValidationUtils.rejectIfEmpty(errors, "adress", "field.required");
}
}
|
package com.gtfs.action;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.gtfs.bean.LicOblApplicationMst;
import com.gtfs.bean.LicPolicyDtls;
import com.gtfs.dto.LicPolicyDtlsDto;
import com.gtfs.service.interfaces.LicMarkingToQcDtlsService;
import com.gtfs.service.interfaces.LicPolicyDtlsService;
@Component
@Scope("session")
public class IndividualMarkingRnlAction implements Serializable{
private Logger log = Logger.getLogger(IndividualMarkingRnlAction.class);
@Autowired
private LoginAction loginAction;
@Autowired
private LicPolicyDtlsService licPolicyDtlsService;
@Autowired
private LicMarkingToQcDtlsService licMarkingToQcDtlsService;
private Date policyFromDate;
private Date policyToDate;
private Boolean renderedListPanel;
private List<LicPolicyDtlsDto> licPolicyDtlsDtoList = new ArrayList<LicPolicyDtlsDto>();
private List<LicPolicyDtlsDto> selectedList = new ArrayList<LicPolicyDtlsDto>();
public void refresh(){
renderedListPanel = false;
policyFromDate = null;
policyToDate = null;
if(licPolicyDtlsDtoList != null){
licPolicyDtlsDtoList.clear();
}
if(selectedList != null){
selectedList.clear();
}
}
public String onLoad(){
refresh();
return "/licHubRenewalActivity/licRnlIndividualMarking.xhtml";
}
public void search(){
try{
if(licPolicyDtlsDtoList != null){
licPolicyDtlsDtoList.clear();
}
List<Object> list = licPolicyDtlsService.findIndividualMarkingDtlsByDateForRenewal(policyFromDate, policyToDate, loginAction.getUserList().get(0).getBranchMst().getBranchId());
if(list == null || list.size()==0 || list.contains(null)){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Error : ", "No Record(s) Found"));
return;
}
Iterator<Object> listIterator = list.iterator();
while(listIterator.hasNext()){
Object[] objects = (Object[]) listIterator.next();
LicPolicyDtlsDto licPolicyDtlsDto = new LicPolicyDtlsDto();
licPolicyDtlsDto.setPolicyNo((String) objects[0]);
licPolicyDtlsDto.setPayDate((Date) objects[1]);
licPolicyDtlsDto.setInsuredName((String) objects[2]);
licPolicyDtlsDto.setProposerName((String) objects[3]);
licPolicyDtlsDto.setProduct((String) objects[4]);
licPolicyDtlsDto.setHealthFlag((String) objects[5]);
licPolicyDtlsDto.setPayMode((String) objects[6]);
licPolicyDtlsDto.setDueYears((Long) objects[7]);
licPolicyDtlsDto.setFromDueDate((Date) objects[8]);
licPolicyDtlsDto.setToDueDate((Date) objects[9]);
licPolicyDtlsDto.setPayNature((String) objects[10]);
licPolicyDtlsDtoList.add(licPolicyDtlsDto);
}
renderedListPanel = true;
}catch(Exception e){
log.info("IndividualMarkingRnlAction search Error : ", e);
}
}
public void onSave(){
try{
if(selectedList == null || selectedList.size()==0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Error : ", "Please Select a Policy to Save"));
return;
}
Date now = new Date();
List<LicPolicyDtls> licPolicyDtlsToSave = new ArrayList<LicPolicyDtls>();
for(LicPolicyDtlsDto obj : selectedList){
List<LicPolicyDtls> dtls = licPolicyDtlsService.findPolicyDtlsByPolicyNoAndDueDateRange(obj.getPolicyNo(), obj.getFromDueDate(), obj.getToDueDate());
Iterator<LicPolicyDtls> iterator = dtls.iterator();
while(iterator.hasNext()){
LicPolicyDtls licPolicyDtls = iterator.next();
licPolicyDtls.getLicMarkingToQcDtls().setIndMrkBy(loginAction.getUserList().get(0).getUserid());
licPolicyDtls.getLicMarkingToQcDtls().setIndMrkDate(now);
licPolicyDtls.getLicMarkingToQcDtls().setIndMrkFlag("Y");
licPolicyDtls.getLicMarkingToQcDtls().setModifiedBy(loginAction.getUserList().get(0).getUserid());
licPolicyDtls.getLicMarkingToQcDtls().setModifiedDate(now);
licPolicyDtls.setPremListReadyFlag("Y");
licPolicyDtlsToSave.add(licPolicyDtls);
}
}
Boolean status = licMarkingToQcDtlsService.updateForIndividualMarkingForRenewal(licPolicyDtlsToSave);
if(status){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
"Save Successful : ", "POD Tagging Successfully Completed."));
refresh();
}else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Save UnSuccessful : ", "POD Tagging Unsuccessful"));
}
}catch(Exception e){
log.info("IndividualMarkingRnlAction save Error : ", e);
}
}
/* GETTER SETTER */
public Date getPolicyFromDate() {
return policyFromDate;
}
public void setPolicyFromDate(Date policyFromDate) {
this.policyFromDate = policyFromDate;
}
public Date getPolicyToDate() {
return policyToDate;
}
public void setPolicyToDate(Date policyToDate) {
this.policyToDate = policyToDate;
}
public List<LicPolicyDtlsDto> getSelectedList() {
return selectedList;
}
public void setSelectedList(List<LicPolicyDtlsDto> selectedList) {
this.selectedList = selectedList;
}
public List<LicPolicyDtlsDto> getLicPolicyDtlsDtoList() {
return licPolicyDtlsDtoList;
}
public void setLicPolicyDtlsDtoList(List<LicPolicyDtlsDto> licPolicyDtlsDtoList) {
this.licPolicyDtlsDtoList = licPolicyDtlsDtoList;
}
public Boolean getRenderedListPanel() {
return renderedListPanel;
}
public void setRenderedListPanel(Boolean renderedListPanel) {
this.renderedListPanel = renderedListPanel;
}
}
|
package com.team.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.team.mapper.LogMapper;
import com.team.mapper.MemberMapper;
import com.team.mapper.ProjectMapper;
import com.team.mapper.TaskMapper;
import com.team.service.LogService;
import com.team.vo.Log;
import com.team.vo.LogReceiver;
import com.team.vo.Member;
import com.team.vo.Project;
import com.team.vo.ProjectMember;
@Service("logService")
public class LogServiceImpl implements LogService {
@Autowired
@Qualifier("logMapper")
private LogMapper logMapper;
@Autowired
@Qualifier("projectMapper")
private ProjectMapper projectMapper;
@Autowired
@Qualifier("taskMapper")
private TaskMapper taskMapper;
@Autowired
@Qualifier("memberMapper")
private MemberMapper memberMapper;
@Override
public void writeLog(Log log) {
logMapper.insertLog(log);
// 같은 프로젝트 멤버에게 로그 전송
for (ProjectMember member : projectMapper.selectMemberByProjectNo(log.getProjectNo())) {
logMapper.insertLogReceiver(new LogReceiver(log.getLogNo(), member.getEmail()));
System.out.println(member.toString());
}
}
@Override
public List<Log> findLogByProjectNo(HashMap<String, Object> params) {
List<Log> logs = new ArrayList<>();
for (Log log : logMapper.selectLogByProjectNo(params)) {
log.setTask(taskMapper.selectTaskByTaskNo(log.getTaskNo())); // 업무 가져오기
log.setSender(memberMapper.selectMemberByEmail(log.getEmail()));// 보낸사람정보 가져오기
logs.add(log);
}
return logs;
}
@Override
public void logCheckByReceiver(HashMap<String, Object> params) {
logMapper.updateCheckedByReceiver(params);
}
@Override
public void logDeleteByReceiver(HashMap<String, Object> params) {
logMapper.deleteLogByReceiver(params);
}
@Override
public int uncheckedLogCount(HashMap<String, Object> params) {
return logMapper.countLog(params);
}
@Override
public Date findLatestWriteDate(HashMap<String, Object> params) {
return logMapper.selectLatestWritedate(params);
}
}
|
import java.util.Scanner;
public class InteractRunner {
public static void main(String[] args) {
Calculator calc = new Calculator();
String exit = "нет";
String clean = "нет";
Scanner sc = new Scanner(System.in);
while(!exit.equals("да")) {
System.out.print("Введите первую цифру:");
calc.setLeft(Float.valueOf(sc.next()));
System.out.print("Введите вторую цифру:");
calc.setRight(Float.valueOf(sc.next()));
System.out.print("Введите символ операции.\n"
+ "Выберите между: +, -, *, /, ^");
calc.setOperation(sc.next());
calc.doOperation();
System.out.println("Результат - " + calc.getResult());
System.out.println("Очистить результат? Выберите между да или нет:");
clean = sc.next();
if(clean.equals("да")) {
calc.cleanResult();
}
System.out.print("Выходим? Выберите между да или нет:");
exit = sc.next();
}
sc.close();
}
}
|
package de.zarncke.lib.io.store;
import java.io.IOException;
import java.io.InputStream;
import de.zarncke.lib.io.IOTools;
import de.zarncke.lib.region.Region;
import de.zarncke.lib.region.RegionUtil;
/**
* Store which reads resources from the classpath.
* Caution: {@link ResourceStore ResourceStores} are always differnt.
*
* @author Gunnar Zarncke
*/
public class ResourceStore extends AbstractStore {
private static final String RESOURCE_SEPARATOR = "/";
private final Class<?> base;
private final Store parent;
private final String path;
public ResourceStore(final Class<?> base) {
this(base, null);
}
public ResourceStore(final Class<?> base, final String path) {
this(base, path, null);
}
public ResourceStore(final Class<?> base, final String path, final Store parent) {
this.base = base;
this.path = path;
this.parent = parent;
}
@Override
public boolean exists() {
return canRead();
}
private InputStream getStream() {
return this.base.getResourceAsStream(this.path);
}
@Override
public Store element(final String name) {
String childPath;
if (this.path == null) {
childPath = name;
} else if (name == null) {
childPath = this.path;
} else if (name.startsWith("/")) {
childPath = name;
} else if (this.path.endsWith("/")) {
childPath = this.path + name;
} else {
childPath = this.path + RESOURCE_SEPARATOR + name;
}
return new ResourceStore(this.base, childPath, this);
}
public String getName() {
if (this.path == null) {
return null;
}
int p = this.path.lastIndexOf(RESOURCE_SEPARATOR);
return this.path.substring(p + 1);
}
@Override
public Store getParent() {
return this.parent;
}
@Override
public boolean canRead() {
try {
InputStream ins = getStream();
if (ins == null) {
return false;
}
ins.close();
return true;
} catch (Exception e) {
// note: JDK throws NPE if stream not present we don't log any details
return false;
}
}
@Override
public InputStream getInputStream() throws IOException {
InputStream is = getStream();
if (is == null) {
throw new IOException("cannot read " + this.base + ":" + this.path);
}
return is;
}
@Override
public Region asRegion() throws IOException {
// TODO consider returning a region which fills as the stream is read
return RegionUtil.asRegion(IOTools.getAllBytes(getStream()));
}
@Override
public String toString() {
return this.base + ":" + this.path;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pkFiguras;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* Diseñe un programa (en consola) que encuentre el área y perímetro de un
* rectángulo o un círculo mostrando un menú para que seleccione, cuadrado o
* circulo luego pida los datos necesarios para das solución y muestre en
* pantalla el nombre de la figura su área en unidades cuadradas y su perímetro
* en unidades simples, recuerde que no existen áreas o perímetros menores o
* iguales a cero.
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String num0="",figura= "",paso="";
int num=0,radio=0, altura=0, base=0, lado=0;
do {
Scanner leer = new Scanner(System.in);
System.out.println("\n:::::::::::::::::::::::::::::::::::::::::");
System.out.println("( *** AREA Y PERIMETRO DE FIGURAS ***)\n");
System.out.println("Digite el nombre de la figura, que desea calcular el area y perimetro: \n::::::::::");
System.out.println("1.Triangulo");
System.out.println("2.Cuadrado");
System.out.println("3.Rectangulo");
System.out.println("4.Circulo\n:::::::::::");
figura = leer.nextLine();
switch (figura) {
case "triangulo":
case "TRIANGULO":
case "Triangulo":
// Triangulo
Triangulo tria = new Triangulo();
System.out.println("\nBIENVENIDO AL AREA Y PERIMETRO DEL TRIANGULO\n");
System.out.println("*Por favor ingrese el valor de la base:");
base = leer.nextInt();
System.out.println("*Por favor ingrese el valor de la altura:");
altura = leer.nextInt();
System.out.println("*Por favor ingrese el valor del lado:");
lado = leer.nextInt();
tria.setBase(base);
tria.setAltura(altura);
tria.setLado(lado);
tria.setNomFigura(figura);
tria.calcularArea();
tria.calcularPerim();
System.out.println("................................\n");
break;
case "cuadrado":
case "CUADRADO":
case "Cuadrado":
// Cuadrado
Cuadrado cuad = new Cuadrado();
System.out.println("\nBIENVENIDO AL AREA Y PERIMETRO DEL CUADRADO\n");
System.out.println("*Por favor ingrese el valor del lado:");
lado = leer.nextInt();
cuad.setNomFigura(figura);
cuad.setLado(lado);
cuad.calcularArea();
cuad.calcularPerim();
System.out.println("...................................\n");
break;
case "rectangulo":
case "RECTANGULO":
case "Rectangulo":
// Rectangulo
Rectangulo rectan = new Rectangulo();
System.out.println("\nBIENVENIDO AL AREA Y PERIMETRO DEL RECTANGULO\n");
System.out.println("*Por favor ingrese el valor de la altura:");
altura = leer.nextInt();
System.out.println("");
System.out.println("*Por favor ingrese el valor de la base: ");
base = leer.nextInt();
rectan.setNomFigura(figura);
rectan.setBaseRect(base);
rectan.setAltura(altura);
rectan.calcularArea();
rectan.calcularPerim();
System.out.println("...................................\n");
break;
case "Circulo":
case "circulo":
case "CIRCULO":
// Circulo
Circulo circu = new Circulo();
System.out.println("\nBIENVENIDO AL AREA Y PERIMETRO DEL CIRCULO\n");
System.out.println("*Por favor ingrese el valor del radio: ");
radio=leer.nextInt();
circu.setNomFigura(figura);
circu.setRadioCirculo(radio);
circu.calcularArea();
circu.calcularPerim();
System.out.println("...................................\n");
break;
default:
System.out.println("!!Error opción fuera de rango!!\n");
// throw new AssertionError();
}
num = 0;
System.out.println("*Para repetir Menú digite (1) de lo contrario cualquier tecla.");
num = leer.nextInt();
} while (num == 1);
}
}
|
package com.travel.services;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Optional;
import com.travel.models.Route;
import com.travel.repositories.RouteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RouteServiceImpl implements RouteService {
@Autowired
private RouteRepository routeRepository;
@Override
public void save(Route route) {
// Just a helper to print out all object properties before saving
try {
for (Field field : route.getClass().getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
Object value = field.get(route);
System.out.printf("%s: %s%n", name, value);
}
} catch(IllegalAccessException error) {
System.out.printf("exception", error);
}
routeRepository.save(route);
}
@Override
public List<Route> findAll() {
return routeRepository.findAll();
}
@Override
public Route findById(Long id) {
Optional<Route> optionalRoute = routeRepository.findById(id);
if(optionalRoute.isPresent()){
return optionalRoute.get();
}
return null;
}
@Override
public void deleteById(Long id) {
routeRepository.deleteById(id);
}
}
|
import java.lang.NullPointerException;
public abstract class Conta {
private int numero;
private String nome;
private double saldo;
private String senha;
protected final String spacer = "-------------------------------------------";
public Conta(int numero, String nome) {
this.numero = numero;
this.nome = nome;
this.saldo = 0.0;
this.senha = Hashing.hash("0000");
}
public Conta() {
this.saldo = 0.0;
this.senha = Hashing.hash("0000");
}
public void setNumero(int numero) { this.numero = numero; }
public int getNumero() { return numero; }
public void setNome(String nome) { this.nome = nome; }
public String getNome() { return nome; }
public void sacar(double valor) throws SaldoInvalidoException, ValorInvalidoException {
if (valor > 0) {
if (valor <= saldo) {
saldo -= valor;
} else {
throw new SaldoInvalidoException();
}
} else {
throw new ValorInvalidoException();
}
}
public void depositar(double valor) throws ValorInvalidoException {
if (valor > 0) {
saldo += valor;
} else {
throw new ValorInvalidoException();
}
}
public double getSaldo() {
return this.saldo;
}
public void setSaldo(double saldo) {
this.saldo = saldo;
}
public void alterarSenha(String senhaAntiga, String senhaNova) throws NullPointerException {
try {
if (comparaSenha(senhaAntiga)) {
this.senha = Hashing.hash(senhaNova);
}
} catch (NullPointerException npe) {
throw npe;
}
}
public boolean comparaSenha(String attempt) throws NullPointerException {
try {
//Hashing h = Hashing.getInstance();
//if (senha.equals(h.hash(attempt))) {
if (senha.equals(Hashing.hash(attempt))) {
return true;
} else {
return false;
}
} catch (NullPointerException npe) {
throw npe;
}
}
public void exibir() { System.out.printf("\t%d - %s (R$%.2f)\n", numero, nome, saldo); }
public String to_string() { return String.format("Conta #%d\nSr(a). %s\nSaldo: R$%.2f", numero, nome, saldo); }
//---------TEMPLATES---------
public void incrementarRendimentos() {}
public boolean cobrarJuros(double juros) { return false; }//{System.out.printf("Using base function for acc %d\n", this.numero);}
}
|
package org.carter.peyton.training.rap.db.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.carter.peyton.training.rap.db.dao.DeviceDAO;
import org.carter.peyton.training.rap.db.entities.Device;
public class DeviceDAOImpl implements DeviceDAO {
private EntityManagerFactory emf;
@SuppressWarnings("unchecked")
@Override
public List<Device> getDeviceList() {
emf = Persistence.createEntityManagerFactory("org.carter.peyton.training.rap.db");
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("Select d from Device d");
List<Device> listDevices = query.getResultList();
em.close();
return listDevices;
}
}
|
package Tools;
public class Constants {
/////////////////////database queries///////////////////////
//Creates
public static final String create_database_query = "create database if not exists stl";
public static final String create_conditions_table_query = "create table if not exists stl.Conditions (\n" +
" `condition_id` int not null auto_increment,\n" +
" `condition_name` varchar(20) not null,\n" +
" `Date` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n" +
" `init_total_time` double,\n" +
" `better_total_time` double,\n" +
" `distribution_path` varchar(255),\n" +
" `init_awt` double,\n" +
" `better_awt` double,\n" +
" `phase_time` double,\n" +
" PRIMARY KEY (`condition_id`)\n" +
")";
public static final String create_directionsInfo_table_query = "create table if not exists stl.DirectionsInfo (\n" +
" `direction_info_id` int not null auto_increment, \n" +
" `cars_amount` int not null,\n" +
" `average_speed` int not null,\n" +
" `limit_speed` int not null,\n" +
" `type` varchar(20) not null,\n" +
" PRIMARY KEY (`direction_info_id`)\n" +
")";
public static final String create_traffic_lights_table_query = "create table if not exists stl.TrafficLights (\n" +
" `traffic_light_id` int not null auto_increment,\n" +
" `actual_state` int not null,\n" +
" primary key(`traffic_light_id`)\n" +
")";
public static final String create_cars_table_query = "create table if not exists stl.Cars (\n" +
" `car_id` int not null auto_increment,\n" +
" `direction_info_id` int not null,\n" +
" `car_type` varchar(25),\n" +
" `length` int not null,\n" +
" `speed` int not null,\n" +
" primary key(`car_id`),\n" +
" foreign key(`direction_info_id`) references DirectionsInfo(`direction_info_id`)\n" +
")";
public static final String create_crossroadsInfo_table_query = "create table if not exists stl.CrossroadsInfo(\n" +
" `crossroad_info_id` int not null auto_increment,\n" +
" `condition_id` int not null,\n" +
" `north_direction_info_id` int,\n" +
" `east_direction_info_id` int,\n" +
" `south_direction_info_id` int,\n" +
" `west_direction_info_id` int,\n" +
" PRIMARY KEY (`crossroad_info_id`),\n" +
" foreign key(`condition_id`) references Conditions(`condition_id`),\n" +
" foreign key(`north_direction_info_id`) references DirectionsInfo(`direction_info_id`),\n" +
" foreign key(`east_direction_info_id`) references DirectionsInfo(`direction_info_id`),\n" +
" foreign key(`south_direction_info_id`) references DirectionsInfo(`direction_info_id`),\n" +
" foreign key(`west_direction_info_id`) references DirectionsInfo(`direction_info_id`)\n" +
")";
public static final String create_crossroads_table_query = "create table if not exists stl.Crossroads(\n" +
" `crossroad_id` int not null auto_increment,\n" +
" `crossroad_info_id` int not null,\n" +
" `north_traffic_light_id` int,\n" +
" `east_traffic_light_id` int,\n" +
" `south_traffic_light_id` int,\n" +
" `west_traffic_light_id` int,\n" +
" `actual_state` int not null,\n" +
" primary key(`crossroad_id`),\n" +
" foreign key(`crossroad_info_id`) references CrossroadsInfo(`crossroad_info_id`),\n" +
" foreign key(`north_traffic_light_id`) references TrafficLights(`traffic_light_id`),\n" +
" foreign key(`east_traffic_light_id`) references TrafficLights(`traffic_light_id`),\n" +
" foreign key(`south_traffic_light_id`) references TrafficLights(`traffic_light_id`),\n" +
" foreign key(`west_traffic_light_id`) references TrafficLights(`traffic_light_id`)\n" +
")";
//Drops
public static final String drop_database_query = "drop database if exists stl";
//Saves
public static final String insert_conditions_statment = "insert into stl.Conditions(condition_name,init_total_time,better_total_time,distribution_path,init_awt,better_awt,phase_time) values(?,?,?,?,?,?,?)";
public static final String insert_directionsInfo_statment = "insert into "
+ "stl.DirectionsInfo(cars_amount, average_speed, limit_speed, type)"
+ " values(?,?,?,?)";
public static final String insert_crossroadsInfo_statment = "insert into "
+ "stl.CrossroadsInfo(condition_id, north_direction_info_id, east_direction_info_id, south_direction_info_id, west_direction_info_id)"
+ " values(?,?,?,?,?)";
public static final String insert_crossroads_statment = "insert into"
+ " stl.crossroads(crossroad_info_id, north_traffic_light_id, east_traffic_light_id, south_traffic_light_id, west_traffic_light_id, actual_state)"
+ " values(?,?,?,?,?,?)";
public static final String insert_traffic_light = "insert into stl.trafficlights(actual_state) values(?)";
//Selects
public static final String select_0_condition_query = "select * from stl.conditions limit 0";
public static final String select_conditions_dates_query = "select Date from stl.conditions";
public static final String conditions_dates = "Date";
public static final String select_condition_by_date_query = "select * from stl.conditions where date =?";
public static final String select_crossroadsInfo_ids_query = "select crossroad_info_id from stl.crossroadsinfo where condition_id =?";
public static final String select_crossroadsInfo_query = "select north_direction_info_id, east_direction_info_id, south_direction_info_id, west_direction_info_id"
+ " from stl.crossroadsinfo where crossroad_info_id =?";
public static final String select_directionInfo_query = "select cars_amount, average_speed, limit_speed from stl.directionsinfo "
+ "where direction_info_id = ?";
///////////////////////////////////////////////////////////
//log messages
public static final String connection_fail = "ERROR: connection fail!";
public static final String create_database_fail = "ERROR: create local database fail!";
//window labels
public static final String traffic_conditions_window_label = "Choose traffic conditions";
public static final String home_page_window_label = "Welcome to the Smart traffic light!";
public static final String client_type_window_label = "Choose your occupation";
public static final String simulation_window_label = "Simulation";
public static final String about_us_window_label = "About us";
public static final String database_window_label = "Database";
public static final String database_connect_window_label = "Connect to Database";
public static final String random_window_label = "Random";
public static final String go_to_previous_page_window_label = "Go to previous window";
public static final String exit_window_label = "Exit";
public static final String fail_window_label = "Fail";
//buttons labels
public static final String yes_button_label = "Yes";
public static final String no_button_label = "No";
public static final String reset_button_label = "Reset";
public static final String run_button_label = "Run";
public static final String analyst_button_label = "Analyst";
public static final String observer_button_label = "Observer";
public static final String save_button_label = "Save";
public static final String back_button_label = "Back";
public static final String start_button_label = "Start";
public static final String database_button_label = "Database";
public static final String random_button_label = "Random";
public static final String info_button_label = "Info";
public static final String lets_start_button_label = "Let's start";
public static final String about_us_button_label = "About us";
public static final String close_button_label = "Close";
public static final String cancel_button = "Cancel";
public static final String confirm_button_database = "Choose";
public static final String open_csv_button_label = "Open CSV";
//pages labels
public static final String about_us_text = "Smart Traffic Light\nVersion 1.0\n" +
"Created by Netanel Davidov and Maxim Marmer";
public static final String go_to_previous_page_from_conditions_text = "If you go back all options will reset\n" +
"Sure you want to go back?";
public static final String go_to_previous_page_from_simulation_text = "Current simulation will be deleted\n" +
"Sure you want to go back?";
public static final String crossroad_1_label = "Crossroad 1";
public static final String crossroad_2_label = "Crossroad 2";
public static final String other_features_label = "Other features";
public static final String route_label = "Route";
public static final String east_label = "East";
public static final String west_label = "West";
public static final String north_label = "North";
public static final String south_label = "South";
public static final String cars_count_label = "Cars count";
public static final String actual_speed_label = "Actual speed";
public static final String speed_limit_label = "Speed limit";
public static final String window_label = "Smart Traffic Light";
public static final String url_label = "url: ";
public static final String user_label = "user: ";
public static final String password_label = "password: ";
public static final String connect_button = "Connect";
public static final String create_database_button = "Create database";
public static final String choose_file_from_database_label = "Choose conditions file";
public static final String generate_random_data_label = "Generate random data?";
public static final String reset_conditions_label = "Reset all values?";
public static final String exit_text_label = "Sure you want to exit?";
public static final String fail_text_label = "Observer does not have this permissions.";
public static final String csv_fail_text_label = "The opened file has wrong data format.";
public static final double POLICE_MAX_SPEED = 70;
public static final double AMBULANCE_MAX_SPEED = 70;
public static final double TAXI_MAX_SPEED = 70;
public static final double USUAL_MAX_SPEED = 70;
public static final double TRACK_MAX_SPEED = 70;
//sizes
public static final double TRAFFIC_LIGHT_HEIGHT = 40;
public static final double TRAFFIC_LIGHT_WIDTH = 15;
//times
public static final int TRAFFIC_LIGHT_CHANGING_TIME = 2;
public static final int TRAFFIC_LIGHT_MIN_DISTRIBUTION = 5;
public static final double TRAFFIC_LIGHT_PHASE_TIME = 20;
// directions
public static final int NORTH_DIRECTION = 0;
public static final int EAST_DIRECTION = 1;
public static final int SOUTH_DIRECTION = 2;
public static final int WEST_DIRECTION = 3;
//directions names
public static final String DIRECTION_NAME_EAST_WEST = "east-west";
public static final String DIRECTION_NAME_NORTH_SOUTH = "north-south";
public static final String DIRECTION_NAME_EAST = "east";
public static final String DIRECTION_NAME_WEST = "west";
public static final String DIRECTION_NAME_NORTH = "north";
public static final String DIRECTION_NAME_SOUTH = "south";
public static final String CROSSROAD_NAME_FIRST = "first";
public static final String CROSSROAD_NAME_SECOND = "second";
//Units
public static final double METER_TO_PIXEL = 15;
//String delimiters
public static final String PHASE_DELIMITER = "->";
public static final String TIMES_DELIMITER = ":";
//Start values
public static final int CARS_COUNT_SHORT_ROAD_DEFAULT = 3;
public static final int CARS_COUNT_LONG_ROAD_DEFAULT = 10;
public static final int CARS_COUNT_LONG_ROAD_MAX = 100;
public static final int CARS_COUNT_SHORT_ROAD_MAX = 4;
public static final int CARS_COUNT_MIN = 1;
public static final int SPEED_LIMIT_DEFAULT = 50;
public static final int SPEED_LIMIT_MAX = 110;
public static final int SPEED_LIMIT_MIN = 50;
public static final int ACTUAL_LIMIT_DEFAULT = 50;
public static final int ACTUAL_LIMIT_MAX = 110;
public static final int ACTUAL_LIMIT_MIN = 30;
public static final double SAFETY_DISTANCE = 2;
public static final double SAFETY_DISTANCE_TO_START = 3;
public static final double SAFETY_DISTANCE_TO_STOP = 1;
public static final double START_DISTANCE_BETWEEN_CARS = 2;
//info text
public static final String INFO_LABEL = "Main information";
public static final String INFO_DIRECTIONS_LABEL = "Directions information";
public static final String INFO_TRAFFIC_LIGHTS_LABEL = "Traffic lights information";
public static final String INFO_CARS_COUNT_LABEL = "Cars count information";
public static final String INFO_SPEED_LIMIT_LABEL = "Speed limit information";
public static final String INFO_ACTUAL_SPEED_LABEL = "Actual speed information";
public static final String INFO_TEXT = "Before starting the application, you must select the conditions that the algorithm will try to solve." +
"\n\nConditions include cars and speed for two intersections." +
"\n\nThe user can set this data manually, load it from the database by clicking on the 'Database' button, or select it by random clicking 'Random' button." +
"\n\nTo reset all selected settings, press the 'Reset' button.";
public static final String INFO_DIRECTIONS_TEXT = "Each intersection has four roads." +
"\n\nFor a better understanding of the movement of the vehicle, the picture on the left shows the order with the names of the sides and it is in this order that the lanes and directions of movement will be called.";
public static final String INFO_TRAFFIC_LIGHTS_TEXT = "Each lane is regulated by a traffic light. In the figure, the arrow from the traffic light indicates the lane that will depend on the particular traffic light." +
"\n\nEach traffic light has 4 states: green, yellow, red, red-yellow." +
"\n\nGreen - traffic allowed." +
"\nYellow - stop moving." +
"\nRed - cars are waiting for green." +
"\nRed-yellow - mice are ready to go." +
"\n\nIt takes 3 seconds to switch the state of traffic light colors.";
public static final String INFO_CARS_COUNT_TEXT = "The number of cars indicates how many cars must pass the intersection from the selected side.";
public static final String INFO_SPEED_LIMIT_TEXT = "Speed limit indicates the speed limit for the selected road.";
public static final String INFO_ACTUAL_SPEED_TEXT = "The actual speed indicates the speed at which the movement is taking place in real time." +
"\n\nActual speed can be less than speed limit, but can not be more than speed limit on the road.";
}
|
package src.com.prlprg;
public class ParSum {
private ParSumThread[] parSumThreads;
private int numOfThreads;
public ParSum(int threads) {
this.numOfThreads = threads;
this.parSumThreads = new ParSumThread[threads];
}
public long getParSum(int[] arr) {
long result = 0;
int numbOfThreadElements = (int) Math.ceil(arr.length * 1.0 / numOfThreads);
for (int i = 0; i < numOfThreads; i++) {
parSumThreads[i] = new ParSumThread(arr, i * numbOfThreadElements, (i + 1) * numbOfThreadElements);
parSumThreads[i].start();
}
try {
for (ParSumThread thread : parSumThreads) {
thread.join();
}
} catch (InterruptedException e) {
e.getCause();
}
for (ParSumThread thread : parSumThreads) {
result += thread.getPartSum();
}
return result;
}
}
|
package dino.task;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import dino.command.AddTaskCommand;
import dino.exception.*;
import dino.util.Parser;
public class TaskList {
private final List<Task> taskList;
public TaskList(List<Task> taskList) {
this.taskList = taskList;
}
public List<Task> getTaskList() {
return taskList;
}
/**
* Adds a new task to the task list
*
* @param task the task to be added
* @return the output message after execution
*/
public String addTask(Task task) {
assert(task != null); //the task to be added is not empty
taskList.add(task);
int size = taskList.size();
return "Got it. I've added this task: \n"
+ " " + taskList.get(size - 1) + "\n" +
"Now you have " + size +
(size > 1 ? " tasks" : " task") + " in the list.";
}
/**
* Prints out the task list in console, prefixed with index
*
* @return the output message after execution
*/
public String printTaskList() {
try {
if (taskList.isEmpty()) {
throw new EmptyListException();
}
StringBuilder list = new StringBuilder();
for (int i = 0; i < taskList.size(); i++) {
list.append(i + 1).append(". ").append(taskList.get(i)).append("\n");
}
return "Here are the tasks in your list: \n" + list;
} catch (EmptyListException e) {
return e.getMessage();
}
}
/**
* Marks the task indicated by the given index as done
*
* @param index the index of the task as indicated by the task list
* @return the output message after execution
*/
public String markTaskDone(int index) {
try {
if (index < 1 || index > taskList.size()) {
throw new InvalidIndexException();
} else {
Task t = taskList.get(index - 1);
assert(t != null); //the task we fetched is not null
if (t.getStatus()) {
throw new TaskAlreadyDoneException();
}
assert(!t.getStatus()); //the task to be marked as done is not done yet
t.setDone();
return "Nice! I've marked this task as done: \n" + t;
}
} catch (TaskAlreadyDoneException | InvalidIndexException e) {
return e.getMessage();
}
}
/**
* Deletes the task indicated by the index from the task list
*
* @param index the index of the task in the task list
* @return the output message after execution
* @throws InvalidIndexException if the index entered is out of bounds
*/
public String deleteTask(int index) throws InvalidIndexException {
try {
if (index < 1 || index > taskList.size()) {
throw new InvalidIndexException();
} else {
Task t = taskList.remove(index - 1);
assert (t != null); //the task that we removed is not null
int size = taskList.size();
return "Noted. I've removed this task: \n" + t + "\n"
+ "Now you have " + size +
(size > 1 ? " tasks" : " task") + " in the list.";
}
} catch (InvalidIndexException e) {
return e.getMessage();
}
}
/**
* Prints out the task(s) that contains the input keyword(s) in description
*
* @param keywords a list of keywords for searching tasks
* @return the list of task that contains the keyword
*/
public String searchTaskFromKeyword(String ...keywords) {
List<Task> matchingTasksList = new ArrayList<>();
Stream<Task> matchingTasksStream;
for (String keyword : keywords) {
matchingTasksStream = taskList.stream().filter(task -> task.getDescription().contains(keyword));
matchingTasksStream.forEach(task -> matchingTasksList.add(task));
}
try {
if (matchingTasksList.isEmpty()) {
throw new TaskNotFoundException();
} else {
StringBuilder list = new StringBuilder();
for (int i = 0; i < matchingTasksList.size(); i++) {
list.append(i + 1).append(". ").append(matchingTasksList.get(i)).append("\n");
}
return "Here are the matching tasks in your list:\n" + list;
}
} catch (TaskNotFoundException e) {
return e.getMessage();
}
}
/**
* Edits the task at the given index to the new task
*
* @param newTask the new task after edition
* @param index the index of the task to be edited
* @return the output message after edition
*/
public String editTask(String newTask, int index) {
try {
if (index < 1 || index > taskList.size()) {
throw new InvalidIndexException();
}
Task task = taskList.get(index - 1);
Parser.CMDTYPE taskType = Parser.parse(newTask);
String newDescription = AddTaskCommand.getTaskDescription(newTask, taskType);
assert(newDescription != null);
task.editDescription(newDescription);
if (taskType.equals(Parser.CMDTYPE.DEADLINE) || taskType.equals(Parser.CMDTYPE.EVENT)) {
LocalDate newTime = AddTaskCommand.getTaskTime(newTask);
task.editTime(newTime);
}
return "Your task has been successfully changed to:\n" + task;
} catch (DinoException e) {
return e.getMessage();
}
}
}
|
package com.linroid.leetcode.spiralMatrix;
import java.util.ArrayList;
import java.util.List;
/**
* Created by linroid on 4/23/15.
* @link https://leetcode.com/problems/spiral-matrix/
* <p/>
* Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
* <p/>
* For example,
* Given the following matrix:
* <p/>
* <pre>
* [
* [ 1, 2, 3 ],
* [ 4, 5, 6 ],
* [ 7, 8, 9 ]
* ]
* </pre>
* You should return [1,2,3,6,9,8,7,4,5].
* <pre>
* 1 2 3 4
* 5 6 7 8
* 9 10 11 12
* 13 14 15 16
* </pre>
*/
public class Solution {
public static void main(String[] args) {
int[][] matrix = new int[][]{
// { 1, 2, 3, 4 },
// { 5, 6, 7, 8 },
// { 9, 10, 11, 12 },
// { 13, 14, 15, 16 }
{6, 9, 7}
};
Solution solution = new Solution();
System.out.println(solution.spiralOrder(matrix));
}
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix.length == 0) {
return result;
}
int colMin = 0;
int colMax = matrix[0].length - 1;
int rowMin = 0;
int rowMax = matrix.length - 1;
//每次迭代一圈,然后缩小范围
while (colMin <= colMax && rowMin <= rowMax) {
if (colMin == colMax && rowMin == rowMax) {
result.add(matrix[rowMin][rowMax]);
break;
}
//when only one col
if (colMin == colMax) {
for (int i = rowMin; i <= rowMax; i++) {
result.add(matrix[i][colMin]);
}
break;
}
//when only one row
if (rowMin == rowMax) {
for (int i = colMin; i <= colMax; i++) {
result.add(matrix[rowMin][i]);
}
break;
}
//left to right
for (int i = colMin; i <= colMax - 1; i++) {
result.add(matrix[rowMin][i]);
}
//top to bottom
for (int i = rowMin; i <= rowMax - 1; i++) {
result.add(matrix[i][colMax]);
}
//right to left
for (int i = colMax; i > colMin; i--) {
result.add(matrix[rowMax][i]);
}
//bottom to top
for (int i = rowMax; i > colMin; i--) {
result.add(matrix[i][colMin]);
}
colMin++;
colMax--;
rowMin++;
rowMax--;
}
return result;
}
}
|
import java.util.Scanner;
class madglibs {
public static void main(String args[]){
Scanner input = new Scanner (System.in);
String color;
String noun1;
String noun2;
String Adj;
System.out.print("Type in a color.");
color = input.nextLine();
System.out.print("Type in a noun (Plural).");
noun1 = input.nextLine();
System.out.print("Type in a noun.");
noun2 = input.nextLine();
System.out.print("Type in a adjective.");
Adj = input.nextLine();
System.out.println("Roses are " + color+",");
System.out.println(noun1 + " are blue,");
System.out.println(noun2 + " is " + Adj+",");
System.out.println("and so are you.");
}
}
|
package com.bdi.sp.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bdi.sp.dao.DepartInfoDAO;
import com.bdi.sp.service.DepartInfoService;
import com.bdi.sp.vo.DepartInfo;
@Service
public class DepartInfoServiceImpl implements DepartInfoService {
@Autowired
private DepartInfoDAO didao;
@Override
public List<DepartInfo> getDepartInfoList(DepartInfo di) {
return didao.getDepartInfoList(di);
}
@Override
public DepartInfo getDepartInfo(int diNo) {
return didao.getDepartInfo(diNo);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package AAPA.Entity;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
/**
*
* @author youssef
*/
@Entity
public class Forum {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long idForum;
private String titleForum;
private String auterForum;
private Date dateForum;
@OneToMany
private List<commentairesForum> CommForum;
public Long getIdForum() {
return idForum;
}
public void setIdForum(Long idForum) {
this.idForum = idForum;
}
public String getTitleForum() {
return titleForum;
}
public void setTitleForum(String titleForum) {
this.titleForum = titleForum;
}
public String getAuterForum() {
return auterForum;
}
public void setAuterForum(String auterForum) {
this.auterForum = auterForum;
}
public Date getDateForum() {
return dateForum;
}
public void setDateForum(Date dateForum) {
this.dateForum = dateForum;
}
public List<commentairesForum> getCommForum() {
return CommForum;
}
public void setCommForum(List<commentairesForum> CommForum) {
this.CommForum = CommForum;
}
public Forum(String titleForum, String auterForum, Date dateForum) {
this.titleForum = titleForum;
this.auterForum = auterForum;
this.dateForum = dateForum;
}
public Forum() {
}
}
|
package com.bonc.dxbrgrmp.service.serviceimpl;
import com.alibaba.fastjson.JSONObject;
import com.bonc.dxbrgrmp.controller.CloudiipApiController;
import com.bonc.dxbrgrmp.service.IClouddipApiService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.Map;
@Service
public class ClouddipApiServiceImpl implements IClouddipApiService {
private Log loger = LogFactory.getLog(CloudiipApiController.class);
private RestTemplate restTemplate;
@Autowired
public ClouddipApiServiceImpl(RestTemplateBuilder builder){
this.restTemplate = builder.build();
}
@Value("${cloudiip.apiurl.token}")
private String cloudiip_token_apiurl;
@Value("${cloudiip.apiurl.asset_tree}")
private String asset_tree_apiurl;
/**
* 获取token
* @param userId
* @param teantId
* @param pwd
* @return
*/
public String getToken(String userId,String teantId,String pwd) throws Exception {
String u = userId;
String p = pwd;
String t=teantId;
MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<>();
postParameters.add("u", u);
postParameters.add("p", p);
postParameters.add("t", t);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<MultiValueMap<String,String>> entity = new HttpEntity<>(postParameters, headers);
String token = null;
ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(
cloudiip_token_apiurl, HttpMethod.POST, entity,
JSONObject.class);
if(responseEntity != null && responseEntity.getBody() != null){
token = responseEntity.getBody().getString("message");
}
return token;
}
/**
* 获取资产树
* @param token
* @param parametersMap
* @return
* @throws Exception
*/
public Object queryAssetTree(String token, Map parametersMap) throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization",token);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity entity = new HttpEntity(headers);
String url = asset_tree_apiurl+"?"+analyParameter(parametersMap);
ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(
url, HttpMethod.GET, entity,
JSONObject.class);
return responseEntity.getBody();
}
private String analyParameter(Map map){
StringBuilder pa = new StringBuilder();
map.forEach((key1,value)->{
if(value == null){
pa.append(key1).append("=&");
}else{
pa.append(key1).append("=").append(value).append("&");
}
});
return pa.toString();
}
}
|
package foodchain.channels;
import foodchain.transactions.MoneyTransaction;
import foodchain.transactions.Transaction;
import foodchain.parties.Party;
/**
* Channel to pay for products.
*/
public class PaymentChannel implements Channel {
/**
* Party which receives money.
*/
private final Party receiver;
/**
* Constructs channel for sending money.
* @param receiver receiver party to send money to
*/
public PaymentChannel(Party receiver) {
this.receiver = receiver;
}
/**
* Method for making transaction between two parties.
* @param transaction - already created money transaction to transmit
* @return result if transmission was successful, null otherwise
*/
@Override
public MoneyTransaction makeTransmission(Transaction transaction) {
if ((transaction.getSender().getPartyName()).equalsIgnoreCase("farmer")) {
System.out.println("Farmer doesn't send money!");
return null;
}
System.out.println("Money transaction is being made to "+transaction.getReceiver().getPartyName());
MoneyTransaction moneyTransaction = (MoneyTransaction)transaction;
receiver.receiveMoney(moneyTransaction);
return moneyTransaction;
}
}
|
package me.bemind.fingerprintexample;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.widget.TextView;
import me.bemind.fingerprinthelper.AuthenticationCallback;
import me.bemind.fingerprinthelper.FingerPrintHelperBuilder;
import me.bemind.fingerprinthelper.IFingerPrintUiHelper;
public class MainActivity extends Activity implements AuthenticationCallback {
private static final int REQUEST_FINGER_PRINT_PERMISSION = 234;
private TextView descTextView;
private IFingerPrintUiHelper fingerPrintUIHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
descTextView = (TextView) findViewById(R.id.desc);
initFingerPrint();
}
private void initFingerPrint() {
fingerPrintUIHelper = FingerPrintHelperBuilder.getFingerPrintUIHelper(this,this);
// crypto = new FingerprintManagerCompat.CryptoObject(mChifer);
if (!fingerPrintUIHelper.isHardwareDetected()) {
// Device doesn't support fingerprint authentication
descTextView.setText(R.string.no_finger_senso);
} else if (!fingerPrintUIHelper.hasEnrolledFingerprints()) {
// User hasn't enrolled any fingerprints to authenticate with
descTextView.setText(R.string.note);
} else {
// Everything is ready for fingerprint authentication
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.USE_FINGERPRINT) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.USE_FINGERPRINT},
REQUEST_FINGER_PRINT_PERMISSION);
} else {
startListeningFingerPrint();
}
}
}
private void startListeningFingerPrint() {
if(fingerPrintUIHelper.initCipher()){
fingerPrintUIHelper.startListening();
}else {
//show error
descTextView.setText(R.string.errore_generico);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_FINGER_PRINT_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startListeningFingerPrint();
}
}
@Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
descTextView.setText(errString);
}
@Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
descTextView.setText(helpString);
}
@Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
fingerPrintUIHelper.stopListening();
startActivity(new Intent(this,LoggedActivity.class));
}
@Override
public void onAuthenticationFailed() {
descTextView.setText(R.string.auth_failed);
}
}
|
package practice;
public class StringExample {
public static void main(String arg[]) {
String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a==c);
System.out.println(a.equalsIgnoreCase(b));
}
}
|
package com.nãosei.entities;
import java.awt.image.BufferedImage;
public class Rock extends Entity{
public Rock(int x, int y, int width, int heigth, BufferedImage sprite) {
super(x, y, width, heigth, sprite);
}
}
|
package com.cnk.travelogix.service.impl;
import com.google.api.services.oauth2.model.Userinfo;
public abstract class GoogleAuthTemplate
{
public abstract Userinfo getUserInfo(String paramString);
}
|
package com.stem.service;
import com.stem.core.interfaces.BasicService;
import com.stem.entity.ProductActivity;
import com.stem.entity.ProductActivityExample;
public interface EatActivityService extends BasicService<ProductActivityExample, ProductActivity>{
}
|
package org.rocksdb.baseoperator.sst;
import com.google.common.collect.Lists;
import org.rocksdb.IngestExternalFileOptions;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import java.nio.charset.Charset;
import static org.rocksdb.baseoperator.sst.SstWriterFeature.dbPath;
import static org.rocksdb.baseoperator.sst.SstWriterFeature.path;
/**
* @fileName: SstIngestFeature.java
* @description: SstIngestFeature.java类说明
* @author: huangshimin
* @date: 2021/9/29 5:23 下午
*/
public class SstIngestFeature {
public static void main(String[] args) {
RocksDB.loadLibrary();
IngestExternalFileOptions ingestExternalFileOptions = new IngestExternalFileOptions();
// 跳过重复key覆盖
ingestExternalFileOptions.setIngestBehind(true);
try (RocksDB db = RocksDB.open(dbPath)){
db.ingestExternalFile(Lists.newArrayList(path),ingestExternalFileOptions);
System.out.println(new String(db.get("test".getBytes()), Charset.defaultCharset()));
} catch (RocksDBException e) {
e.printStackTrace();
}
}
}
|
package cn.bs.zjzc.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import cn.bs.zjzc.model.response.BaseResponse;
/**
* 省份和城市列表
* Created by mgc on 2016/6/27.
*/
public class ProvinceCityListResponse extends BaseResponse {
/**
* id : 1
* name : 广东省
* city_list : [{"id":"2","name":"广州市"},{"id":"3","name":"深圳市"}]
*/
public List<DataBean> data;
@Override
public String toString() {
return "ProvinceCityListResponse{" +
"data=" + data +
'}';
}
public static class DataBean implements Serializable{
public String id;
public String name;
/**
* 多级菜单城市列表依赖toString方法,勿更改
* @return
*/
// @Override
// public String toString() {
// return name;
// }
@Override
public String toString() {
/*return "{" +
"city_list:" + city_list +
", id:\"" + id + '\"' +
", name:\"" + name + '\"' +
'}';*/
return name;
}
/**
* id : 2
* name : 广州市
*/
public ArrayList<CityListBean> city_list;
public static class CityListBean implements Serializable{
public String id;
public String name;
/**
* 多级菜单城市列表依赖toString方法,勿更改
* @return
*/
@Override
public String toString() {
return name;
}
}
}
}
|
package com.wuyan.masteryi.admin.entity;
/*
*project:master-yi
*file:OrderCount
*@author:wsn
*date:2021/7/11 20:48
*/
import lombok.Data;
import java.util.Date;
@Data
public class OrderCount {
private Date date;
private int count;
private float totalMoney;
private String f_date;
}
|
package pl.ark.chr.buginator.commons.util;
import java.util.Objects;
public class Pair<X, Y> {
public final X _1;
public final Y _2;
public Pair(X x, Y y) {
this._1 = x;
this._2 = y;
}
@Override
public String toString() {
return "(" + _1 + "," + _2 + ")";
}
@Override
@SuppressWarnings("unchecked")
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Pair)) {
return false;
}
Pair<X, Y> that = (Pair<X, Y>) o;
return Objects.equals(this._1, that._1) && Objects.equals(this._2, that._2);
}
@Override
public int hashCode() {
return Objects.hash(_1, _2);
}
}
|
package com.voiceman.cg.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.voiceman.cg.entities.typeProjet;
public interface TypeProjetRepository extends JpaRepository<typeProjet , Long> {
}
|
package org.browsexml.timesheetjob.service.impl;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.browsexml.timesheetjob.dao.HoursWorkedDao;
import org.browsexml.timesheetjob.dao.PayPeriodDao;
import org.browsexml.timesheetjob.model.Constants;
import org.browsexml.timesheetjob.model.HoursWorkedExport;
import org.browsexml.timesheetjob.model.HoursWorkedHistory;
import org.browsexml.timesheetjob.model.HoursWorkedReport;
import org.browsexml.timesheetjob.model.JobRateType;
import org.browsexml.timesheetjob.model.PayPer;
import org.browsexml.timesheetjob.model.ReportLineItem;
import org.browsexml.timesheetjob.service.HoursReportsManager;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
public class HoursReportsManagerImpl implements HoursReportsManager, MessageSourceAware {
private static Log log = LogFactory.getLog(HoursReportsManagerImpl.class);
private PayPeriodDao pay;
private HoursWorkedDao hours;
private MessageSource messageSource = null;
@Override
public void setMessageSource(MessageSource messageSource) {
log.debug("MESSAGE SOURCE SET");
this.messageSource = messageSource;
}
/* (non-Javadoc)
* @see org.browsexml.timesheetjob.service.impl.HoursReportsManager#setPayPeriodDao(org.browsexml.timesheetjob.dao.PayPeriodDao)
*/
public void setPayPeriodDao(PayPeriodDao pay) {
this.pay = pay;
}
@Override
public PayPer getLastPeriodEnd(Boolean fulltime) {
log.debug("fulltime = " + fulltime);
Date date = pay.getLastPeriodEnd(fulltime, false);
log.debug("date = " + date);
if (date == null)
return null;
return pay.getPeriodFromEndDate(new java.sql.Date(date.getTime()),
fulltime);
}
/* (non-Javadoc)
* @see org.browsexml.timesheetjob.service.impl.HoursReportsManager#setHoursWorkedDao(org.browsexml.timesheetjob.dao.HoursWorkedDao)
*/
public void setHoursWorkedDao(HoursWorkedDao hours) {
this.hours = hours;
}
/* (non-Javadoc)
* @see org.browsexml.timesheetjob.service.impl.HoursReportsManager#getPayPeriods(java.lang.String)
*/
public List<PayPer> getPayPeriods(String year) {
return pay.getPeriods(year);
}
/**
* Get a list of payperiods limited to full or part time
*/
@Override
public List<PayPer> getPayPeriods(String year, boolean fulltime) {
return pay.getPeriods(year, fulltime);
}
public PayPer getPayPeriod(String id) {
PayPer ret = null;
if (id == null) {
return new PayPer();
}
try {
ret = pay.getPeriod(Integer.parseInt(id));
} catch (NumberFormatException e) {
e.printStackTrace();
}
return ret;
}
public List<Integer> getYears() {
return pay.getYears();
}
/* (non-Javadoc)
* @see org.browsexml.timesheetjob.service.impl.HoursReportsManager#getAllHoursWorked(java.lang.String, java.lang.String)
*/
public List<HoursWorkedReport> getAllStudentHoursWorked(Date start, Date end, String supervisorId) {
return this.hours.getAllStudentHoursWorked(start, end, supervisorId, null, null);
}
@Override
public List<HoursWorkedReport> getAllFulltimeHoursWorked(Date start, Date end, String supervisorId) {
return this.hours.getAllFulltimeHoursWorked(start, end, supervisorId, null, null);
}
public List<JobRateType> getAllJobInfo(Date start, Date end) {
return this.hours.getJobRateType(start, end);
}
/**
* Get a list of all hours worked in a pay period. Weekly overtime should
* be calculated with the beginning of the week as Monday (even if it
* is not in the pay period).
*/
@Override
public List<ReportLineItem> getHoursReportLines(PayPer period, String supervisorId, String peopleId, String departmentId) {
Date start = period.getBeginDate();
Date end = period.getEndDate();
Boolean fulltime = period.getFulltime();
List<HoursWorkedReport> x = null;
List<ReportLineItem> lines = new ArrayList<ReportLineItem>();
if (fulltime) {
x = this.hours.getAllFulltimeHoursWorked(start, end, supervisorId, peopleId, departmentId);
} else {
x = this.hours.getAllStudentHoursWorked(start, end, supervisorId, peopleId, departmentId);
}
int totalHours = 0;
int periodGrandTotalHours = 0;
int totalHoursTowardOvertime = 0;
String lastJob = "";
int lastId = 0;
int lastDow = -1;
for(int i = 0; i < x.size(); i++) {
HoursWorkedReport day = (HoursWorkedReport) x.get(i);
Calendar dowCal = new GregorianCalendar();
dowCal.setTime(day.getPunched());
int dow = ((dowCal.get(Calendar.DAY_OF_WEEK)-Calendar.SUNDAY) + 0)%7;//Monday = 1;Sunday = 0
int id = Integer.parseInt(day.getPeopleId());
String jobCode = day.getJobDepartment();
if (!fulltime) // Don't break by weeks if student
lastDow = dow;
if (i == 0) {
lastDow = dow;
lastJob = jobCode;
}
else if (dow < lastDow || !lastJob.equals(jobCode)
|| id != lastId) {
// Footer --break up by job, day of week and person
lastJob = jobCode;
lines.add(new ReportLineItem(totalHours));
periodGrandTotalHours += totalHours;
totalHours = 0;
totalHoursTowardOvertime = 0;
if (id != lastId) {
lines.add(new ReportLineItem(periodGrandTotalHours, true));
periodGrandTotalHours = 0;
}
}
lastDow = dow;
Boolean newId = (id != lastId);
Integer hours = new Double(day.getHours() * 100).intValue();
Integer hours2 = 0;
// Make sure date is within pay period; need to get from Monday to
// calculate overtime
if (day.getPunched().getTime() >= start.getTime())
totalHours += hours;
if (day.countsTowardOvertime()) {
if ((totalHoursTowardOvertime < Constants.MAX_HOURS_PER_WEEK_IN_HUNDREDS) &&
(totalHoursTowardOvertime + hours) > Constants.MAX_HOURS_PER_WEEK_IN_HUNDREDS) {
Integer newHours = Constants.MAX_HOURS_PER_WEEK_IN_HUNDREDS - totalHoursTowardOvertime;
hours2 = hours - newHours;
hours = newHours;
}
totalHoursTowardOvertime += hours + hours2;
}
Boolean overtime = totalHoursTowardOvertime > Constants.MAX_HOURS_PER_WEEK_IN_HUNDREDS;
if (hours2 != 0) {
lines.add(new ReportLineItem(day, newId, false, hours, false));
ReportLineItem over = new ReportLineItem(day, newId, true, hours2, true);
lines.add(over);
}
else {
ReportLineItem item = new ReportLineItem(day, newId, overtime, hours, false);
lines.add(item);
}
if (newId) {
lastId = id;
}
}
lines.add(new ReportLineItem(totalHours));
lines.add(new ReportLineItem(periodGrandTotalHours+totalHours, true));
return lines;
}
/**
* Use the list of all hours worked for a pay period (getHoursReportLines)
* to sum up the hours for each person by department and workcode.
*/
@Override
public List<HoursWorkedExport> getHoursExportLines(PayPer period, String supervisorId, String peopleId, String departmentId) {
List<HoursWorkedExport> exportList = new ArrayList<HoursWorkedExport>();
List<ReportLineItem> list = getHoursReportLines(period, supervisorId, peopleId, departmentId);
if (list == null || list.size() == 0)
return exportList;
ReportLineItem firstItem = list.get(0);
log.debug(Constants.toReflexString(firstItem));
HoursWorkedReport firstDay = firstItem.getDay();
String lastPeopleId = null;
String lastDepartment = null;
boolean first = true;
HoursWorkedReport lastDay = firstDay;
TreeMap<String, Summation> allHours = new TreeMap<String, Summation>();
for (ReportLineItem item: list) {
if (item.getFooter())
continue;
HoursWorkedReport day = item.getDay();
String personId = day.getPeopleId();
String department = day.getJobDepartment();
if (!first) {
if (!personId.equals(lastPeopleId) || !department.equals(lastDepartment)) {
iterateMap(allHours, lastDay, exportList);
allHours = new TreeMap<String, Summation>();
}
}
first = false;
String key = day.getWorkcode(item.getOvertime(),
messageSource.getMessage(Constants.OVERTIME_CODE, null, Locale.getDefault()));
Summation sum = allHours.get(key);
if (sum == null)
sum = new Summation();
sum.hours = sum.hours + item.getHours();
// Try to weed out zero rates should they occur; they shouldn't
Integer dayRate = day.getRate(item.getOvertime());
if (dayRate == null)
dayRate = 0;
sum.rate = Math.max(sum.getRate(), dayRate);
allHours.put(key, sum);
lastDay = day;
lastPeopleId = day.getPeopleId();
lastDepartment = day.getJobDepartment();
}
iterateMap(allHours, lastDay, exportList);
return exportList;
}
/**
* Iterate a tree map to return a list of the elements
* @param allHours
* @param day
* @param exportList
*/
private void iterateMap(TreeMap<String, Summation> allHours,
HoursWorkedReport day, List<HoursWorkedExport> exportList) {
for (Map.Entry<String,Summation> entry : allHours.entrySet()) {
exportList.add(
new HoursWorkedExport(day.getJobDepartment(),
day.getName(), day.getPeopleId(),
entry.getValue().getHours(), entry.getValue().getRate(),
day.getAwardCode(), entry.getKey()));
}
}
/**
* Get a list of all workers and there historical hours so that which current
* award to use can be calculated.
* @param pay
* @return
* @throws Exception
*/
@Override
public HashMap getAwardPlacement() throws Exception {
log.debug("getAwardPlacement");
List<PayPer> payPeriods =
pay.getContainingPeriods(new java.sql.Date(pay.getLastPeriodEnd(false, false).getTime()),
false);
if (payPeriods.size() != 1) {
throw new Exception ("There must be one and only one current student payperiod; there are " +
payPeriods.size() + " current periods ");
}
PayPer payPeriod = payPeriods.get(0);
List<HoursWorkedExport> export = getHoursExportLines(payPeriod, null, null, null);
log.debug("pay period = " + payPeriod.getStrBeginDate());
List<HoursWorkedHistory> x = hours.getHistoricalStudentHoursWorked(payPeriod);
HashMap m = new HashMap();
m.put("report", export);
for (HoursWorkedHistory hist: x) {
m.put(hist, hist);
}
for (HoursWorkedExport e: export) {
e.setHist((HoursWorkedHistory)m.get(new HoursWorkedHistory(e.getPeopleId(), e.getDepartment())));
}
return m;
}
}
class Summation {
Integer hours = 0;
Integer rate = 0;
String workcode;
public Summation() {
}
public Summation(Integer hours, Integer rate, String workcode) {
this.hours = hours;
this.rate = rate;
this.workcode = workcode;
}
public Integer getHours() {
return hours;
}
public void setHours(Integer hours) {
this.hours = hours;
}
public Integer getRate() {
return rate;
}
public void setRate(Integer rate) {
this.rate = rate;
}
public String getWorkcode() {
return workcode;
}
public void setWorkcode(String workcode) {
this.workcode = workcode;
}
}
|
package com.lin.paper.service;
import java.util.List;
import com.github.pagehelper.PageInfo;
import com.lin.paper.bean.ColumnPerm;
import com.lin.paper.pojo.PRole;
/**
* 角色信息的业务逻辑接口
* @
* @date 2018年1月28日下午8:38:26
* @version 1.0
*/
public interface RoleService {
/**
* 分页加载所有有用的角色集合
* @param page
* @return
*/
PageInfo<PRole> getRoleList(Integer page);
/**
* 根据角色名查找数据
* @param rolename
* @return
*/
PRole getRoleByName(String rolename);
/**
* 保存角色数据
* @param role
*/
void saveRole(PRole role);
/**
* 更新用户信息
* @param role
*/
void updateRole(PRole role);
/**
* 根据ID删除用户信息
* @param roleid
*/
void deleteRoleById(String roleid);
/**
* 根据ID查找角色信息
* @param roleid
* @return
*/
PRole getRoleById(String roleid);
/**
* 获得所有的用户角色集合
* @return
*/
List<PRole> getUserRoles();
/**
* 根据ID查询所有角色名称
* @param roles
* @return
*/
String getNamesByIds(String roles);
/**
* 获得所有用户的权限列表
* @param roles
* @return
*/
List<ColumnPerm> getColumnPermByRole(String roles);
}
|
package com.training.pom;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.training.generics.ScreenShot;
public class LoginPOM {
private WebDriver driver;
private ScreenShot screenShot;
public LoginPOM(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
@FindBy ( id="btn_signin") private WebElement Signin_Button ;
@FindBy(id="login") private WebElement userName;
@FindBy(id="password") private WebElement password;
@FindBy(id="form-login_submitAuth") private WebElement loginBtn;
@FindBy ( xpath="//li[@class='dropdown avatar-user']") private WebElement UserIcon_Dropdown ;
@FindBy ( xpath="//a[@id='logout_button']") private WebElement LogoutButton ;
public void sendUserName(String userName) {
this.userName.clear();
this.userName.sendKeys(userName);
}
public void sendPassword(String password) {
this.password.clear();
this.password.sendKeys(password);
}
public void clickLoginBtn() {
this.loginBtn.click();
}
}
|
/**
* @author Adham Elarabawy
*/
package org.team3128.redobot.subsystems;
import org.team3128.common.hardware.motor.LazyCANSparkMax;
import org.team3128.common.generics.Threaded;
import org.team3128.common.control.RateLimiter;
import org.team3128.common.control.AsynchronousPid;
import org.team3128.common.control.motion.RamseteController;
import org.team3128.common.control.trajectory.Trajectory;
import org.team3128.common.control.trajectory.Trajectory.State;
import org.team3128.common.drive.AutoDriveSignal;
import org.team3128.common.drive.DriveSignal;
import org.team3128.common.utility.math.Rotation2D;
import org.team3128.common.utility.NarwhalUtility;
import com.ctre.phoenix.motorcontrol.ControlMode;
import com.ctre.phoenix.motorcontrol.FeedbackDevice;
import com.ctre.phoenix.motorcontrol.NeutralMode;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.SPI;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Timer;
import org.team3128.common.hardware.motor.LazyTalonFX;
import org.team3128.common.utility.RobotMath;
import edu.wpi.first.wpilibj.Timer;
import com.kauailabs.navx.frc.AHRS;
import org.team3128.common.utility.Log;
import org.team3128.common.drive.Drive;
public class FalconDrive extends Drive {
public enum DriveState {
TELEOP, RAMSETECONTROL, TURN, DONE
}
private static final FalconDrive instance = new FalconDrive();
public static FalconDrive getInstance() {
return instance;
}
// private ADXRS450_Gyro gyroSensor;
public AHRS ahrs;
// private LazyTalonSRX leftTalon, rightTalon, leftSlaveTalon, leftSlave2Talon,
// rightSlaveTalon, rightSlave2Talon;
private RamseteController autonomousDriver;
private Trajectory trajectory = null;
private AsynchronousPid turnPID;
private DriveState driveState;
private RateLimiter moveProfiler, turnProfiler;
private Rotation2D wantedHeading;
private volatile double driveMultiplier;
private double currentTime;
private double startTime;
private double totalTime;
double prevPositionL = 0;
double prevPositionR = 0;
double startTimeControl;
double endTime = 0;
public LazyTalonFX leftTalon, rightTalon, leftTalonSlave, rightTalonSlave, leftTalonSlave2, rightTalonSlave2;
public double left_setpoint, right_setpoint;
private FalconDrive() {
// gyroSensor = new ADXRS450_Gyro(SPI.Port.kOnboardCS0);
ahrs = new AHRS(SPI.Port.kMXP);
//left and right are flipped because the driver wanted to flip the direction of driving.
rightTalon = new LazyTalonFX(Constants.DriveConstants.LEFT_DRIVE_FRONT_ID);
rightTalonSlave = new LazyTalonFX(Constants.DriveConstants.LEFT_DRIVE_MIDDLE_ID);
// leftTalonSlave2 = new LazyTalonFX(Constants.LEFT_DRIVE_BACK_ID);
leftTalon = new LazyTalonFX(Constants.DriveConstants.RIGHT_DRIVE_FRONT_ID);
leftTalonSlave = new LazyTalonFX(Constants.DriveConstants.RIGHT_DRIVE_MIDDLE_ID);
// rightTalonSlave2 = new LazyTalonFX(Constants.RIGHT_DRIVE_BACK_ID);
leftTalon.setInverted(true);
rightTalon.setInverted(false);
leftTalonSlave.setInverted(true);
rightTalonSlave.setInverted(false);
// leftTalonSlave2.setInverted(false);
// rightTalonSlave2.setInverted(false);
configMotors();
driveState = DriveState.TELEOP;
turnPID = new AsynchronousPid(1.0, 0, 1.2, 0); // P=1.0 OR 0.8
turnPID.setOutputRange(Constants.DriveConstants.DRIVE_HIGH_SPEED, -Constants.DriveConstants.DRIVE_HIGH_SPEED);
turnPID.setSetpoint(0);
moveProfiler = new RateLimiter(Constants.DriveConstants.DRIVE_ACCEL_LIMIT);
turnProfiler = new RateLimiter(100);
// configHigh();
configAuto();
}
@Override
public void debug() {
System.out.println("L enc: " + getLeftDistance() + " velo " + getLeftSpeed());
System.out.println("R enc: " + getRightDistance() + " velo " + getRightSpeed());
System.out.println("Gyro: " + getAngle()/* getGyroAngle().getDegrees() */);
}
@Override
public void debugSpeed() {
System.out.println("L speed " + " actual " + getLeftSpeed());
System.out.println("R speed " + " actual " + getRightSpeed());
}
@Override
public void setRight() {
setWheelVelocity(new DriveSignal(40, 0));
}
@Override
public void configAuto() {
rightTalon.config_kP(0, Constants.DriveConstants.K_AUTO_RIGHT_P);
rightTalon.config_kD(0, Constants.DriveConstants.K_AUTO_RIGHT_D);
rightTalon.config_kF(0, Constants.DriveConstants.K_AUTO_RIGHT_F);
leftTalon.config_kP(0, Constants.DriveConstants.K_AUTO_LEFT_P);
leftTalon.config_kD(0, Constants.DriveConstants.K_AUTO_LEFT_D);
leftTalon.config_kF(0, Constants.DriveConstants.K_AUTO_LEFT_F);
}
@Override
public void configHigh() {
driveMultiplier = Constants.DriveConstants.DRIVE_HIGH_SPEED;
}
boolean teleopstart = true;
@Override
synchronized public void setTeleop() {
driveState = DriveState.TELEOP;
}
@Override
public void calibrateGyro() {
// gyroSensor.calibrate();
}
@Override
public void printCurrent() {
System.out.println(leftTalon);
}
@Override
public void configMotors() {
leftTalonSlave.follow(leftTalon);
// leftTalonSlave2.follow(leftTalon);
rightTalonSlave.follow(rightTalon);
// rightTalonSlave2.follow(rightTalon);
leftTalon.setNeutralMode(Constants.DriveConstants.DRIVE_IDLE_MODE);
rightTalon.setNeutralMode(Constants.DriveConstants.DRIVE_IDLE_MODE);
leftTalonSlave.setNeutralMode(Constants.DriveConstants.DRIVE_IDLE_MODE);
rightTalonSlave.setNeutralMode(Constants.DriveConstants.DRIVE_IDLE_MODE);
// leftTalonSlave2.setIdleMode(IdleMode.kCoast);
// rightTalonSlave2.setIdleMode(IdleMode.kCoast);
configAuto();
}
@Override
public void resetMotionProfile() {
moveProfiler.reset();
}
@Override
public double getAngle() {
return ahrs.getAngle();
}
@Override
public double getDistance() {
return (getLeftDistance() + getRightDistance()) / 2;
}
@Override
public Rotation2D getGyroAngle() {
// -180 through 180
return Rotation2D.fromDegrees(getAngle());
}
@Override
public double getLeftDistance() {
return leftTalon.getSelectedSensorPosition(0) * Constants.DriveConstants.kDriveNuToInches;
}
@Override
public double getRightDistance() {
return rightTalon.getSelectedSensorPosition(0) * Constants.DriveConstants.kDriveNuToInches;
}
@Override
public double getSpeed() {
return (getLeftSpeed() + getRightSpeed()) / 2;
}
@Override
public double getLeftSpeed() {
return leftTalon.getSelectedSensorVelocity(0) * Constants.DriveConstants.kDriveInchesPerSecPerNUp100ms;
}
@Override
public double getRightSpeed() {
return rightTalon.getSelectedSensorVelocity(0) * Constants.DriveConstants.kDriveInchesPerSecPerNUp100ms;
}
@Override
public synchronized void setAutoTrajectory(Trajectory autoTraj, boolean isReversed) {
this.trajectory = autoTraj;
totalTime = trajectory.getTotalTimeSeconds();
autonomousDriver = new RamseteController(1.8, 0.7, isReversed, Constants.AutonomousDriveConstants.TRACK_RADIUS); // 2,0.7
}
@Override
public synchronized void startTrajectory() {
if (trajectory == null) {
Log.info("FalconDrive", "FATAL // FAILED TRAJECTORY - NULL TRAJECTORY INPUTTED");
Log.info("FalconDrive", "Returned to teleop control");
driveState = DriveState.TELEOP;
} else {
//configAuto();
updateRamseteController(true);
driveState = DriveState.RAMSETECONTROL;
}
}
@Override
public void setBrakeState(NeutralMode mode) {
}
@Override
public double getVoltage() {
return 0;
}
@Override
public void setWheelPower(DriveSignal signal) {
leftTalon.set(ControlMode.PercentOutput, signal.leftVelocity);
rightTalon.set(ControlMode.PercentOutput, signal.rightVelocity);
}
@Override
public void setWheelVelocity(DriveSignal setVelocity) {
if (Math.abs(setVelocity.rightVelocity) > (Constants.DriveConstants.DRIVE_HIGH_SPEED)
|| Math.abs(setVelocity.leftVelocity) > (Constants.DriveConstants.DRIVE_HIGH_SPEED)) {
DriverStation.getInstance();
DriverStation.reportError("Velocity set over " + Constants.DriveConstants.DRIVE_HIGH_SPEED + " !", false);
return;
}
left_setpoint = setVelocity.leftVelocity;
right_setpoint = setVelocity.rightVelocity;
}
/**
* Update the motor outputs with the given control values.
*
* @param joyX horizontal control input
* @param joyY vertical control input
* @param throttle throttle control input scaled between 1 and -1 (-.8 is 10 %,
* 0 is 50%, 1.0 is 100%)
*/
@Override
public void arcadeDrive(double joyX, double joyY, double throttle, boolean fullSpeed) {
synchronized (this) {
driveState = DriveState.TELEOP;
}
double spdL, spdR, pwrL, pwrR;
if (!fullSpeed) {
joyY *= .65;
} else {
joyY *= 1;
}
// scale from 1 to -1 to 1 to 0
throttle = (throttle + 1) / 2;
if (throttle < .3) {
throttle = .3;
} else if (throttle > .8) {
throttle = 1;
}
joyY *= throttle;
joyX *= throttle;
pwrL = Constants.DriveConstants.LEFT_SPEEDSCALAR * RobotMath.clampPosNeg1(joyY - joyX);
pwrR = Constants.DriveConstants.RIGHT_SPEEDSCALAR * RobotMath.clampPosNeg1(joyY + joyX);
spdL = Constants.DriveConstants.DRIVE_HIGH_SPEED * pwrL;
spdR = Constants.DriveConstants.DRIVE_HIGH_SPEED * pwrR;
// String tempStr = "pwrL=" + String.valueOf(pwrL) + ", pwrR=" + String.valueOf(pwrR) + ", spdL="
// + String.valueOf(spdL) + ", spdR=" + String.valueOf(spdR);
// Log.info("FalconDrive", tempStr);
setWheelPower(new DriveSignal(pwrL, pwrR));
// setWheelVelocity(new DriveSignal(spdL, spdR));
}
@Override
public void update() {
// velocityController();
DriveState snapDriveState;
synchronized (this) {
snapDriveState = driveState;
}
switch (snapDriveState) {
case TELEOP:
break;
case RAMSETECONTROL:
updateRamseteController(false);
break;
case TURN:
updateTurn();
break;
}
}
private void velocityController() {
double ks_sign = 1;
if (left_setpoint < 0) {
ks_sign = -1;
}
if (left_setpoint == 0) {
ks_sign = 0;
}
double error = left_setpoint - getLeftSpeed();
double feedforward_left = (Constants.DriveConstants.kS * ks_sign) + (left_setpoint * Constants.DriveConstants.kV); //TODO: add acceleration to this
double voltage_applied_left = feedforward_left + (Constants.DriveConstants.kP*error);
ks_sign = 1;
//the next few conditional statements ensure that the y intercept is pushed to the right direction (in case out path includes going backwards)
if (right_setpoint < 0) {
ks_sign = -1;
}
if (right_setpoint == 0) {
ks_sign = 0;
}
// applied_voltage = kS + (desired velocity * kV) [we currently ignore acceleration and emit PID which might be a bad assumption]
error = right_setpoint - getRightSpeed();
double feedforward_right = (Constants.DriveConstants.kS * ks_sign) + (right_setpoint * Constants.DriveConstants.kV); //TODO: add acceleration to this
double voltage_applied_right = feedforward_right + (Constants.DriveConstants.kP*error);
double leftAvaliableVoltage = leftTalon.getBusVoltage();
double rightAvaliableVoltage = rightTalon.getBusVoltage();
//Log.info("FalconDrive", "left_voltage = " + String.valueOf(voltage_applied_left) + ", right_voltage = " + String.valueOf(voltage_applied_right));
double leftPower = voltage_applied_left / leftAvaliableVoltage;
double rightPower = voltage_applied_right / rightAvaliableVoltage;
if ((Math.abs(leftPower) > 1) || (Math.abs(rightPower) > 1)) {
Log.info("Drive", "Tried to set a voltage greater than the avaliable voltage");
leftPower = RobotMath.clampPosNeg1(leftPower);
rightPower = RobotMath.clampPosNeg1(rightPower);
}
leftTalon.set(ControlMode.PercentOutput, leftPower);
rightTalon.set(ControlMode.PercentOutput, rightPower);
endTime = Timer.getFPGATimestamp();
}
@Override
public void setRotation(Rotation2D angle) {
synchronized (this) {
wantedHeading = angle;
driveState = DriveState.TURN;
}
configHigh();
}
/**
* Set Velocity PID for both sides of the drivetrain (to the same constants)
*/
@Override
public void setDualVelocityPID(double kP, double kD, double kF) {
leftTalon.config_kP(0, kP);
leftTalon.config_kD(0, kD);
leftTalon.config_kF(0, kF);
rightTalon.config_kP(0, kP);
rightTalon.config_kD(0, kD);
rightTalon.config_kF(0, kF);
Log.info("[ArcadeDrive]", "Updated Velocity PID values for both sides of the drivetrain to: kP = " + kP
+ ", kD = " + kD + ", kF = " + kF);
}
@Override
public void updateTurn() {
double error = wantedHeading.rotateBy(RobotTracker.getInstance().getOdometry().rotationMat.inverse())
.getDegrees();
double deltaSpeed;
// System.out.println(RobotTracker.getInstance().getOdometry().rotationMat.getDegrees());
// System.out.println("error: " + error);
deltaSpeed = turnPID.update(error);
deltaSpeed = Math.copySign(NarwhalUtility.coercedNormalize(Math.abs(deltaSpeed), 0, 180, 0,
Constants.DriveConstants.DRIVE_HIGH_SPEED), deltaSpeed);
if (Math.abs(error) < Constants.AutonomousDriveConstants.MAX_TURN_ERROR
&& deltaSpeed < Constants.AutonomousDriveConstants.MAX_PID_STOP_SPEED) {
setWheelVelocity(new DriveSignal(0, 0));
synchronized (this) {
driveState = DriveState.DONE;
}
} else {
setWheelVelocity(new DriveSignal(-deltaSpeed, deltaSpeed));
}
}
@Override
public void setShiftState(boolean state) {
configHigh();
}
@Override
public void updateRamseteController(boolean isStart) {
currentTime = Timer.getFPGATimestamp();
if (isStart) {
startTime = currentTime;
}
State currentTrajectoryState = trajectory.sample(currentTime - startTime);
AutoDriveSignal signal = autonomousDriver.calculate(RobotTracker.getInstance().getOdometry(),
currentTrajectoryState);
if ((currentTime - startTime) == totalTime) {
synchronized (this) {
Log.info("FalconDrive", "Finished Trajectory Pursuit with RamseteController successfully.");
driveState = DriveState.TELEOP;
}
configHigh();
}
// System.out.println("signal l:" + signal.command.leftVelocity + " signal R " +
// signal.command.rightVelocity);
setWheelVelocity(signal.command);
}
@Override
public void resetGyro() {
ahrs.reset();
}
@Override
public boolean checkSubsystem() {
configMotors();
return true;
}
@Override
synchronized public void stopMovement() {
leftTalon.set(ControlMode.PercentOutput, 0);
rightTalon.set(ControlMode.PercentOutput, 0);
setWheelVelocity(new DriveSignal(0, 0));
driveState = DriveState.TELEOP;
resetMotionProfile();
}
@Override
synchronized public boolean isFinished() {
return driveState == DriveState.DONE || driveState == DriveState.TELEOP;
}
@Override
public void clearStickyFaults() {
}
}
|
package cs5387;
import java.io.*;
/**********************************************
*TableSorter sorts the integer values of an NxN
*matrix in ascending order by using MergeSort.
*First, it sorts the values in the rows, then
*it transposes the matrix to sort the values
*in the columns.
*
*@<<author name redacted >>
***********************************************/
public class TableSorter
{
public static int counter = 0;
public boolean isSorted(Table t)
{
if(t==null)
return false;
if(!check(t))
return false;
else
{
columnsToRows(t);
if(!check(t))
return false;
}
return true;
}
private boolean check(Table t)
{
for(int i=0; i<t.getSize(); i++)
for(int j=i+1; j<t.getSize(); j++)
if(t.getTableValue(i, j-1) > t.getTableValue(i, j))
return false;
return true;
}
public static void sortable(Table t)
{
counter++;
if(t != null)
{
sortRows(t);
counter++;
columnsToRows(t);
counter++;
sortRows(t);
counter++;
}
}
private static void sortRows(Table t)
{
int size = t.getSize();
counter++;
counter++;
int[] row = new int[size];
counter++;
int value = 0;
counter++;
counter++;
for(int i=0; i<size; i++)
{
counter++;
counter++;
for(int j=0; j<size; j++)
{
counter++;
value = t.getTableValue(i, j);
counter++;
counter++;
row[j] = value;
counter++;
}
sort(row, 0, row.length-1);
counter++;
counter++;
for (int n=0; n<row.length; n++) {
counter++;
t.setTableValue(i, n, row[n]);
counter++;
}
}
System.out.println();
}
/*Since the Table must be sorted individually by row and individually by column,
* the assumption is made that the order per row and/or the order per column of the original table
* does not have to be maintained. Therefore, transposing the table seems like an efficient
* way to sort the values and/or to check if they are sorted.
*/
private static void columnsToRows(Table t)
{
counter++;
for (int i=0; i<t.getSize(); i++) {
counter++;
counter++;
for (int j=i+1; j<t.getSize(); j++)
{
counter++;
int temp = t.getTableValue(i, j);
counter++;
counter++;
t.setTableValue(i,j, t.getTableValue(j, i));
counter++;
counter++;
t.setTableValue(j, i, temp);
counter++;
}
}
}
/*MergeSort is used because of its O(nlogn) time complexity;
*Unlike QuickSort or BubbleSort which have O(n^2)*/
private static int[] sort(int [] array, int left, int right)
{
counter++;
if(left < right)
{
int mid = (left+right)/2;
counter++;
sort(array, left, mid);
counter++;
sort(array, mid+1, right);
counter++;
merge(array, left, mid, right);
counter++;
}
return array;
}
private static int[] merge(int [] array, int left, int mid, int right)
{
int subArraySize1 = mid-left+1;
counter++;
int subArraySize2 = right-mid;
counter++;
int [] leftTempArray = new int [subArraySize1];
counter++;
int [] rightTempArray = new int [subArraySize2];
counter++;
counter++;
for(int i=0; i<subArraySize1; ++i) {
counter++;
leftTempArray[i] = array[left+i];
counter++;
}
counter++;
for(int i=0; i<subArraySize2; ++i) {
counter++;
rightTempArray[i] = array[mid+1+i];
counter++;
}
int i=0;
counter++;
int j=0;
counter++;
int k=left;
counter++;
while(i<subArraySize1 && j < subArraySize2)
{
counter++;
if(leftTempArray[i] <= rightTempArray[j])
{
counter++;
array[k] = leftTempArray[i];
i++;
counter++;
counter++;
}
else
{
array[k] = rightTempArray[j];
j++;
counter++;
counter++;
}
k++;
counter++;
}
while(i<subArraySize1)
{
counter++;
array[k] = leftTempArray[i];
i++;
k++;
counter++;
counter++;
counter++;
}
while(j<subArraySize2)
{
counter++;
array[k] = rightTempArray[j];
j++;
k++;
counter++;
counter++;
counter++;
}
return array;
}
public void run(Table t)
{
//if(isSorted(t))
System.out.print("\nThe table is sorted in");
}
public static void main(String[] args)throws FileNotFoundException, IOException, Exception
{
int [] array = new int [] {3,5,7,1,8,6,6,0,7};
Table t = new Table(array.length, array);
sortable(t);
TableSorter ts = new TableSorter();
ts.run(t);
System.out.print(" "+ counter + " operations.");
}
}
|
public interface MenuItem {
/** @return the name of the menu item */
String getName();
/** @return the price of the menu item */
double getPrice();
}
|
package com.aalexandrakis.fruit_e_shop;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
//import android.widget.TextView;
public class OrderedItems extends Login {
private ItemAdapter adapt;
public ProgressDialog pgd;
GetOrderedItemsAsyncTask getOrderedItemsAsyncTaskObject;
private String orderId;
protected void onPause() {
if (getOrderedItemsAsyncTaskObject != null &&
getOrderedItemsAsyncTaskObject.getStatus() != AsyncTask.Status.FINISHED){
getOrderedItemsAsyncTaskObject.cancel(true);
}
super.onPause();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
this.orderId = b.getString("orderId");
pgd = new ProgressDialog(this);
pgd.setTitle("Loading...");
pgd.setMessage("Please wait to load data");
setContentView(R.layout.select_item);
TextView txtUserHeader = (TextView) findViewById(R.id.txtUserHeader);
txtUserHeader.setText("Order items");
if (checkConnectivity()) {
GetOrderedItemsAsyncTask getOrderedItemsAsyncTaskObject = new GetOrderedItemsAsyncTask(this);
getOrderedItemsAsyncTaskObject.execute(Commons.URL + "/getOrderItems/" + this.orderId);
} else {
showAlertDialog("Error", "No internet connection");
}
}
@Override
public void onBackPressed(){
if (getOrderedItemsAsyncTaskObject != null &&
getOrderedItemsAsyncTaskObject.getStatus() != AsyncTask.Status.FINISHED){
getOrderedItemsAsyncTaskObject.cancel(true);
}
this.finish();
}
public void fillListWithProducts(ArrayList<Item> ItemsArray){
ListView lstView = (ListView) findViewById(R.id.CartList);
adapt = new ItemAdapter (this, R.layout.list_item_item, ItemsArray);
lstView.setAdapter(adapt);
}
}
/////////////////////////////////////////////////////////////////////////
class GetOrderedItemsAsyncTask extends AsyncTask<String, ArrayList<Item>, ArrayList<Item>> {
private InputStream intStrm;
private ArrayList<Item> items = new ArrayList<Item>();
public OrderedItems thisActivity;
public GetOrderedItemsAsyncTask(OrderedItems a){
thisActivity = a;
}
@Override
protected ArrayList<Item> doInBackground(String... params) {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 30000);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 30000);
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse response = httpClient.execute(httpGet);
intStrm = response.getEntity().getContent();
XmlPullParser xmlItems = null;
xmlItems = XmlPullParserFactory.newInstance().newPullParser();
xmlItems.setInput(intStrm, null);
items = this.fillStringArray(xmlItems);
return items;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();;
//Log.i("doInBackground-cpe", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();;
//Log.i("doInBackground-ioe", e.getMessage());
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();;
//Log.i("doInBackground-xppe", e.getMessage());
thisActivity.showAlertDialog("Error", "Data not found. Please try later");
this.cancel(true);
}
return null;
}
public ArrayList<Item> fillStringArray(XmlPullParser xmlItems) {
Integer eventtype = -1;
ArrayList<Item> items = new ArrayList<Item>();
try {
eventtype = xmlItems.getEventType();
Item item = null;
while (eventtype != XmlPullParser.END_DOCUMENT) {
if (eventtype == XmlPullParser.START_TAG && xmlItems.getName().equals("ordereditem")) {
item = new Item();
} else if (eventtype == XmlPullParser.START_TAG && xmlItems.getName().equals("descr")) {
item.setItemDescr(xmlItems.nextText());
} else if (eventtype == XmlPullParser.START_TAG && xmlItems.getName().equals("mm")) {
item.setItemMm(xmlItems.nextText());
} else if (eventtype == XmlPullParser.START_TAG && xmlItems.getName().equals("itemid")) {
item.setItemCode(Integer.valueOf(xmlItems.nextText()));
} else if (eventtype == XmlPullParser.START_TAG && xmlItems.getName().equals("quantity")) {
item.setItemQuantity(Float.valueOf(xmlItems.nextText()));
} else if (eventtype == XmlPullParser.START_TAG && xmlItems.getName().equals("price")) {
item.setItemPrice(Float.valueOf(xmlItems.nextText()));
} else if (eventtype == XmlPullParser.START_TAG && xmlItems.getName().equals("amount")) {
item.setItemSummary(Float.valueOf(xmlItems.nextText()));
} else if (eventtype == XmlPullParser.END_TAG && xmlItems.getName().equals("ordereditem")) {
items.add(item);
}else if (eventtype == XmlPullParser.END_TAG && xmlItems.getName().equals("ordereditems")) {
break;
}
eventtype = xmlItems.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return items;
}
@Override
protected void onPostExecute(ArrayList<Item> Items) {
thisActivity.fillListWithProducts(Items);
thisActivity.pgd.dismiss();
}
@Override
protected void onPreExecute(){
thisActivity.pgd.show();
}
}
|
package com.cognizant.designpattern.abstractfactory;
public class HDFCHomeLoan extends Loan{
@Override
double getInterestRate() {
// TODO Auto-generated method stub
return 3.8d;
}
}
|
package base;
import java.io.*;
import java.util.*;
public class Post implements Comparable<Post>,Serializable{
private Date _date;
private String _content;
public Post(Date date, String content){
_date = date;
_content = content;
}
public String getContent(){
return _content;
}
public void setContent(String content){
_content = content;
}
public Date getDate(){
return _date;
}
public void setDate(Date date){
_date = date;
}
public String toString(){
return (_date.toString() + "\n" + _content + "\n");
}
public boolean equals(Object o){
o.getClass();
Post post = (Post) o;
return(this.getDate() == post.getDate() && this.getContent() == post.getContent());
}
public int hashCode(){
return (_date.hashCode() + _content.hashCode());
}
public boolean contains(String keyword){
String[] temp = _content.split(" ");
for (int i=0; i<temp.length; i++){
if (temp[i].equals(keyword)){
return true;
}
}
return false;
}
public int compareTo(Post p){
return(_date.compareTo(p._date));
}
}
|
package pack1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.mysql.cj.jdbc.Driver;
public class close_connection_using_finallyTest {
public static void main(String[] args) throws Throwable {
//creating variable connection
Connection connection=null;
//creating try catch block for proper execution of close()
try {
//register the driver
Driver driver=new Driver();
DriverManager.registerDriver(driver);
//step:2-establish the connection
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");
//issue the statement
Statement statement = connection.createStatement();
//update the querry.
int result = statement.executeUpdate("insert into student_info values('6','rajesh','k','kn')");
if(result==1){
System.out.println("Data is added to the database");
}else
System.out.println("Data is not added to the database");
}
//catch block for catching the exception type object
catch (Exception e) {
}
//finally block for surity of execution of close()
finally {
connection.close();
}
}
}
|
package com.trs.om.service;
/**
* 用户级别的系统使用偏好服务
* @author changguanghua
* */
public interface UserPreferenceService {
/**
* 设置用户默认显示的专题追踪的时间范围
* @param userId 用户id
* @param timeType 时间范围类型
* */
void setDefaultThemeSpan(Long userId,Integer timeType);
/**
* 获得默认显示的专题追踪的时间范围
* @param timeType 时间范围类型
* */
Integer getDefaultThemeSpan(Long userId);
/**
* 设置用户首页刷新时间
* @param userId 用户id
* @param indexPageAutoRefreshTimeSpan 时间范围类型
* */
void setIndexPageAutoRefreshTimeSpan(Long userId,Integer indexPageAutoRefreshTimeSpan);
/**
* 获得用户首页刷新时间
* @param indexPageAutoRefreshTimeSpan 时间范围类型
* */
Integer getIndexPageAutoRefreshTimeSpan(Long userId);
/**
* 设置默认每页显示数量
* @param userId
* @param defaultPageLimit
*/
void setDefaultPageLimit(Long userId,Integer defaultPageLimit);
/**
* 获取用户每页显示数量
* @param userId
* @return
*/
Integer getDefaultPageLimit(Long userId);
/**
* 设置是否启用自动热搜词维护
* @param userId
* @param autoSearchWord
*/
void setAutoSearchWord(Long userId,Integer autoSearchWord);
/**
* 获取用户设置的热搜词维护方式
* @param userId
* @return
*/
Integer getAutoSearchWord(Long userId);
}
|
package com.beiyelin.projectportal.entity;
import com.beiyelin.commonsql.jpa.BaseDomainEntity;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* @Description:
* 2018.10.06
* 结算资源范围合并到可借款资源范围中。
* 这张表可以不用了。
* @Author: newmann
* @Date: Created in 22:00 2018-02-22
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper=true)
@Entity
@Table(name = SettleResourse.TABLE_NAME)
@Deprecated
public class SettleResourse extends BaseDomainEntity {
public static final String TABLE_NAME="s_settlement_resourse";
private static final long serialVersionUID = -295260581004725234L;
private EmbeddableSettleResourse settleResourse;
}
|
import java.awt.BorderLayout;
import java.awt.Dimension;
//import java.awt.TextField;
// import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//import java.util.ArrayList;
//import java.util.NoSuchElementException;
//import java.util.Scanner;
//import java.util.StringTokenizer;
//import java.util.Vector;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
//import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
@SuppressWarnings("serial")
public class SongLibrary extends JFrame {
private final String[] HEADERS = { "Song", "Artist", "Album", "Year" };
private Object[][] DATA = {};
private BufferedReader reader;
private DefaultTableModel tablemodel;
private Object [] newRow = new Object [4];
public SongLibrary() {
setTitle("SongLibrary");
// create the application
setLayout(new BorderLayout());
// creates the menu bar
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
add(BorderLayout.NORTH, menubar);
// adds buttons to menu bar
Box panel = Box.createVerticalBox();
JButton added = new JButton("Add");
JButton delete = new JButton("Delete");
panel.add(added);
panel.add(delete);
panel.add(Box.createVerticalBox());
//adds a border to the right side
add(BorderLayout.EAST,panel);
JMenu Library = new JMenu("SongLibrary");
menubar.add(Library);
JMenuItem about = Library.add("About...");
Library.addSeparator();
JMenuItem exit = Library.add("Exit");
JMenu tables = new JMenu("Table");
menubar.add(tables);
JMenuItem New = tables.add("New");
tables.addSeparator();
JMenuItem open = tables.add("Open...");
tables.addSeparator();
JMenuItem saveAs = tables.add("Save As...");
JFileChooser chooser = new JFileChooser();
JTable table = new JTable(DATA, HEADERS);
table.setPreferredScrollableViewportSize(new Dimension(500, 100));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(BorderLayout.CENTER, scrollPane);
tablemodel = new DefaultTableModel(0,4);
tablemodel.setColumnIdentifiers(HEADERS);
table.setModel(tablemodel);
if(table.getRowCount() == 0){
delete.setEnabled(false);
}
about.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(SongLibrary.this,
new JLabel(
"<html><b>SongLibrary</b> <br/> <p>by: Tyre King and Sam Allison</p><html>"),
"About", JOptionPane.INFORMATION_MESSAGE);
}
});
New.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(SongLibrary.this, "Clear all table data?");
if(result == JOptionPane.YES_OPTION){
tablemodel.setRowCount(0);
}
setTitle("SongLibrary");
delete.setEnabled(false);
}
});
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
askForClosing();
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
askForClosing();
}
});
added.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tablemodel.addRow(newRow);
delete.setEnabled(true);
}
});
JFileChooser chooser1 = new JFileChooser();
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(table.getSelectedRow()!= -1){
tablemodel.removeRow(table.getSelectedRow());
}
else if(table.getSelectedRow()== -1 ){
JOptionPane.showMessageDialog(SongLibrary.this, "No row selected", "Message", JOptionPane.OK_OPTION);
}
if(table.getRowCount() == 0){
delete.setEnabled(false);
}
}
});
// the saveAs button has a action listener
saveAs.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent d){
if(d.getSource() == saveAs){
int result = chooser1.showSaveDialog(SongLibrary.this);
if(result== JFileChooser.APPROVE_OPTION){
File file = chooser1.getSelectedFile();
String line;
int rowcount = tablemodel.getRowCount();
try {
BufferedWriter wrote = new BufferedWriter(new FileWriter(file.getAbsolutePath()));
for(int row = 0; row < rowcount; row++){
for(int col = 0; col < tablemodel.getColumnCount() ;col++){
line = (String) tablemodel.getValueAt(row, col);
if(col!= 3){
line += ",";
}else{
line+="\n";
}
wrote.write(line);
//System.out.println(line);
}
}
wrote.close();
setTitle("SongLibrary"+file.getAbsolutePath());
}
catch (IOException e) {
JOptionPane.showMessageDialog(null, "Buffered writer issue");
e.printStackTrace();
}
}
}
}
});
// the open button has a action listener
open.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == open) {
int result = chooser.showOpenDialog(SongLibrary.this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String line;
tablemodel.setRowCount(0);
setTitle("SongLibrary ["+ file.getAbsolutePath()+"]");
try {
reader = new BufferedReader(new FileReader(file));
while((line = reader.readLine())!=null){
tablemodel.addRow(line.split(","));
}
reader.close();
}
catch (Exception e1) {
}
if(table.getRowCount() == 0){
delete.setEnabled(false);
}
else
delete.setEnabled(true);
}
}
}
});
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
}
protected void askForClosing() {
int result = JOptionPane.showConfirmDialog(this,
"Do you want to exit?");
if (result == JOptionPane.YES_OPTION) {
dispose();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new SongLibrary();
f.setVisible(true);
}
});
}
}
|
package com.library.bexam.service;
import com.library.bexam.common.pojo.model.Result;
import com.library.bexam.entity.PaperContentEntity;
import com.library.bexam.entity.PaperEntity;
import java.util.List;
import java.util.Map;
/**
* @author JayChen
*/
public interface PaperService {
/**
* 添加试卷
*
* @return boolean
* @author JayChen
*/
Result add(List<PaperEntity> paperEntityList);
/**
* 获取试卷列表
*
* @return List
* @author JayChen
*/
List list(Map<String, Object> params);
/**
* 根据ID获取试卷信息
*
* @return PaperEntity
* @author JayChen
*/
PaperEntity get(String paperId);
/**
* 修改试卷信息
*
* @return boolean
* @author JayChen
*/
boolean update(PaperEntity paperEntity);
/**
* 更新试卷试题信息
*
* @return boolean
* @author JayChen
*/
boolean updateContent(PaperEntity paperEntity);
/**
* 批量删除试卷
*
* @return boolean
* @author JayChen
*/
boolean delete(String[] paperIdArray);
}
|
package br.com.gdgtresrios.Utils;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
/**
* Created by Wanderlei on 03/07/2015.
*/
public class TransacaoFragmentTask extends AsyncTask<Void, Void, Boolean> {
private static final String TAG = "livroandroid";
private final Context context;
private final Fragment fragment;
private final Transacao transacao;
private Exception exceptionErro;
private int progressID;
public TransacaoFragmentTask(Fragment fragment, Transacao transacao, int progressID) {
this.context = fragment.getActivity();
this.fragment = fragment;
this.transacao = transacao;
this.progressID = progressID;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
try{
showProgress();
} catch (Exception e){
Log.e(TAG, e.getMessage(), e);
}
}
@Override
protected Boolean doInBackground(Void... params) {
try{
transacao.executar();
}catch (Exception e){
Log.e(TAG, e.getMessage(), e);
this.exceptionErro = e;
return false;
} finally {
try{
fragment.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
hideProgress();
}
});
} catch (Exception e){
Log.e(TAG, e.getMessage(), e);
}
}
return true;
}
@Override
protected void onPostExecute(Boolean b) {
if (b){
transacao.atualizarView();
} else {
Log.i(TAG, exceptionErro.getMessage());
}
}
private void showProgress(){
View view = fragment.getView();
if (view != null) {
ProgressBar progressBar = (ProgressBar) view.findViewById(progressID);
if (progressBar != null){
progressBar.setVisibility(View.VISIBLE);
}
}
}
private void hideProgress(){
View view = fragment.getView();
if (view != null){
ProgressBar progressBar = (ProgressBar) view.findViewById(progressID);
if (progressBar != null){
progressBar.setVisibility(View.INVISIBLE);
}
}
}
}
|
package fr.lteconsulting.training.appengine.marvels;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Scope;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan( basePackageClasses = ApplicationController.class )
public class ApplicationController
{
public static void main( String[] args ) throws Exception
{
SpringApplication.run( ApplicationController.class, args );
}
@Bean
@Scope( "singleton" )
public CharactersRepository getMemosRepository()
{
CharactersRepository charactersRepository = new CharactersRepository();
charactersRepository.load();
return charactersRepository;
}
}
|
package org.lovecorp.timetable.domain;
public enum Period {
FIRST, SECOND, THIRD, FOURTH, FIFTH, SIXTH, SEVENTH
}
|
package java8.functionalinterfaces;
import java.util.function.BinaryOperator;
public class BinaryOperatorFunctionalInterfaceExample {
/**
* BinaryOperator is a functional interface which extends BiFunction interface, Introduced in java8
* Accepts 2 inputs and return the same type of value as output
* We can use this interface instead of BiFunction, where we know that both inputs and output are going to be of same type
*/
public static void main(String[] args) {
//creating a simple BinaryOperator which accepts two integers as input, and returns an integer\
BinaryOperator<Integer> integerBinaryOperator = (num1, num2) -> num1 * num2;
System.out.println("Result of integerBinaryOperator: " + integerBinaryOperator.apply(3,4));
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.presales.core.service;
import com.cnk.travelogix.presales.model.ChecklistModel;
/**
* interface for attribute implementationChecklistId
*/
public interface ChecklistService
{
/**
* @param checklistModel
*/
public void generateImplementationChecklistId(final ChecklistModel checklistModel);
}
|
package com.tencent.mm.plugin.appbrand.jsapi.d;
import com.tencent.mm.plugin.appbrand.jsapi.a;
import com.tencent.mm.plugin.appbrand.jsapi.c;
import com.tencent.mm.plugin.appbrand.l;
import com.tencent.mm.plugin.appbrand.page.p;
import com.tencent.mm.plugin.appbrand.widget.input.m;
class b$1 implements Runnable {
final /* synthetic */ int doP;
final /* synthetic */ c fQE;
final /* synthetic */ Integer fQF;
final /* synthetic */ b fQG;
b$1(b bVar, c cVar, Integer num, int i) {
this.fQG = bVar;
this.fQE = cVar;
this.fQF = num;
this.doP = i;
}
public final void run() {
if (this.fQE.isRunning()) {
c cVar = this.fQE;
this.fQE.E(this.doP, this.fQG.f(m.a(cVar instanceof p ? (p) cVar : a.d((l) cVar), this.fQF) ? "ok" : "fail:input not exists", null));
}
}
}
|
package com.nave.game;
import java.util.Iterator;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Nave implements Screen {
final Drop game;
private Texture imagenMisil1;
private Texture imagenMisil2;
private Texture imagenNave1;
private Texture imagenNave2;
private Texture imagenExplosion;
private Sound sonidoExplosion;
private Sound sonidoDisparoLaser;
private Music musicaJuego;
private SpriteBatch batch;
private OrthographicCamera camara;
private Rectangle nave;
private Rectangle nave2;
private Array<Rectangle> misiles;
private Array<Rectangle> misiles2;
private long tiempoCaidaUltimoMisil;
private long ultimoDisparoMisil;
private int puntos;
private int vidas;
private int vidasNave2;
private int velocidad = 100;
public Nave(final Drop game) {
this.game = game;
this.puntos = 0;
this.vidas = 3;
this.vidasNave2 = 5;
// carga las imágenes de las gotas de lluvia y del nave, cada una de 64x64 píxeles
imagenMisil1 = new Texture(Gdx.files.internal("spaceMissiles_001.png"));
imagenMisil2 = new Texture(Gdx.files.internal("spaceMissiles_002.png"));
imagenNave1 = new Texture(Gdx.files.internal("spaceShips_008.png"));
imagenNave2 = new Texture(Gdx.files.internal("spaceShips_001.png"));
imagenExplosion = new Texture(Gdx.files.internal("tank_explosion4.png"));
// carga de sonido para la caída de la gota y la música de fondo
sonidoExplosion = Gdx.audio.newSound(Gdx.files.internal("explosion.mp3"));
sonidoDisparoLaser = Gdx.audio.newSound(Gdx.files.internal("disparoLaser.mp3"));
musicaJuego = Gdx.audio.newMusic(Gdx.files.internal("gta-san-andreas-f.mp3"));
// se aplica que la música se repita en bucle, comienza la reproducción de la música de fondo
musicaJuego.setLooping(true);
musicaJuego.play();
// crea la cámara ortográfica y el lote de sprites
camara = new OrthographicCamera();
camara.setToOrtho(false, 800, 480);
batch = new SpriteBatch();
// crea un rectángulo (clase Rectangle) para representar lógicamente la nave 1
nave = new Rectangle();
nave.x = 800 / 2 - 64 / 2; // centra el nave horizontal
nave.y = 20; // esquina inferior izquierda del nave estará a 20 píxeles del límite inferior
nave.width = 64;
nave.height = 64;
// crea un rectangulo (clase Rectangle) para representar logicamente la nave 2
nave2 = new Rectangle();
nave2.x = 800 / 2 - 64 / 2; // centra el nave horizontal
nave2.y = 400;
nave2.width = 64;
nave2.height = 64;
// crea el vector de misiles
misiles = new Array<Rectangle>();
misiles2 = new Array<Rectangle>();
}
private void creaMisil() {
Rectangle misil = new Rectangle();
misil.x = nave.x + 38;
misil.y = nave.y;
misil.width = 20;
misil.height = 64;
misiles.add(misil);
ultimoDisparoMisil = TimeUtils.nanoTime();
}
private void creaMisil2() {
Rectangle misil2 = new Rectangle();
misil2.x = nave2.x + 38;
misil2.y = nave2.y;
misil2.width = 20;
misil2.height = 64;
misiles2.add(misil2);
tiempoCaidaUltimoMisil = TimeUtils.nanoTime();
}
public void automaticMove() {
nave2.x += velocidad * Gdx.graphics.getDeltaTime();
if (nave2.x > 800 - 95 || nave2.x < 0) {
velocidad = -velocidad;
}
}
public void crearNave2() {
// crea un rectangulo (clase Rectangle) para representar logicamente la nave 2
nave2 = new Rectangle();
nave2.x = 800 / 2 - 64 / 2; // centra el nave horizontal
nave2.y = 400;
nave2.width = 64;
nave2.height = 64;
}
@Override
public void render(float delta) {
// limpia la pantalla con un color azul oscuro. Los argumentos RGB de la función glClearcColor están en el rango entre 0 y 1
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// ordenada a la cámara actualizar sus matrices
camara.update();
// indica al lote de sprites que se represente en las coordenadas específicas de la cámara
game.batch.setProjectionMatrix(camara.combined);
// comienza un nuevo proceso y dibuja el nave y los misiles
game.batch.begin();
game.batch.draw(imagenNave1, nave.x, nave.y);
game.batch.draw(imagenNave2, nave2.x, nave2.y);
game.font.draw(game.batch, "Vidas: " + vidas, 100, 100);
game.font.draw(game.batch, "Puntos: " + puntos, 100, 130);
for(Rectangle misil: misiles) {
game.batch.draw(imagenMisil1, misil.x, misil.y);
}
for(Rectangle misil2: misiles2) {
game.batch.draw(imagenMisil2, misil2.x, misil2.y);
}
game.batch.end();
// lectura de entrada
if(Gdx.input.isTouched()) {
Vector3 posicionTocada = new Vector3();
posicionTocada.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camara.unproject(posicionTocada);
nave.x = posicionTocada.x - 64 / 2;
}
if(Gdx.input.isKeyPressed(Keys.LEFT)) nave.x -= 600 * Gdx.graphics.getDeltaTime();
if(Gdx.input.isKeyPressed(Keys.RIGHT)) nave.x += 600 * Gdx.graphics.getDeltaTime();
//Controla el intervalo entre disparo y disparo de misiles
if (TimeUtils.nanoTime() - ultimoDisparoMisil > 1000000000) {
if(Gdx.input.isKeyPressed(Keys.UP)) {
creaMisil();
sonidoDisparoLaser.play();
}
}
// comprueba si ha pasado un segundo desde el último misil2, para crear uno nuevo
if(TimeUtils.nanoTime() - tiempoCaidaUltimoMisil > 2000000000) creaMisil2();
//Movimiento automatico nave 2
automaticMove();
// nos aseguramos de que las naves permanezca entre los límites de la pantalla
if(nave.x < 0) nave.x = 0;
if(nave.x > 800 - 96) nave.x = 800 - 96;
if(nave2.x < 0) nave2.x = 0;
if(nave2.x > 800 - 96) nave2.x = 800 - 96;
// recorre los misiles y borra aquellos que hayan llegado al suelo (límite superior de la pantalla) o toquen el nave, en ese caso se reproduce sonido.
Iterator<Rectangle> iter = misiles.iterator();
while(iter.hasNext()) {
Rectangle misil = iter.next();
misil.y += 200 * Gdx.graphics.getDeltaTime();
if (misil.y + 64 > 800) iter.remove();
if (misil.overlaps(nave2)) {
iter.remove();
puntos++;
vidasNave2--;
}
}
Iterator<Rectangle> iter2 = misiles2.iterator();
while(iter2.hasNext()) {
Rectangle misil2 = iter2.next();
misil2.y -= 150 * Gdx.graphics.getDeltaTime();
if (misil2.y + 64 < 0) iter2.remove();
if (misil2.overlaps(nave)) {
iter2.remove();
vidas--;
}
}
//Si alcanza cero vidas llama a la pantalla LoseScreen
if (vidas == 0) {
game.batch.begin();
sonidoExplosion.play();
game.batch.draw(imagenExplosion, nave.x, nave.y);
game.batch.end();
if (TimeUtils.nanoTime() - ultimoDisparoMisil > 2000000000) {
game.setScreen(new LoseScreen(game, puntos));
dispose();
}
}
//Si eliminas la nave enemiga
if (vidasNave2 == 0) {
game.batch.begin();
sonidoExplosion.play();
game.batch.draw(imagenExplosion, nave2.x, nave2.y);
if (TimeUtils.nanoTime() - ultimoDisparoMisil > 2000000000) {
velocidad = velocidad + 100;
vidasNave2 = 5;
nave2.x = 64;
}
game.batch.end();
}
}
@Override
public void dispose() {
// liberamos todos los recursos
imagenMisil1.dispose();
imagenNave1.dispose();
//sonicoCaidaGota.dispose();
//musicaLluvia.dispose();
batch.dispose();
}
@Override
public void show() {
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
}
|
package leetcode;
/*
You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
*/
import java.util.Arrays;
public class AddTwoNumber_2 {
static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) {
return null;
}
ListNode root = new ListNode(0);
ListNode head = root;
int carry = 0;
while (l1 != null && l2 != null) {
int sum = l1.val + l2.val + carry;
carry = sum/10;
head.next = new ListNode(sum % 10);
head = head.next;
l1 = l1.next;
l2 = l2.next;
}
ListNode temp = null;
if (l1 != null) {
temp = l1;
} else {
temp = l2;
}
while (temp != null) {
int sum = temp.val + carry;
carry = sum/10;
head.next = new ListNode(sum % 10);
head = head.next;
temp = temp.next;
if (temp == null && carry > 0) {
temp = new ListNode(0);
}
}
if (carry > 0) {
head.next = new ListNode(carry);
}
return root.next;
}
public void solve() {
ListNode val1 = new ListNode(5);
// val1.next = new ListNode(4);
// val1.next.next = new ListNode(3);
ListNode val2 = new ListNode(5);
// val2.next = new ListNode(6);
// val2.next.next = new ListNode(4);
ListNode answer = addTwoNumbers(val1, val2);
while (answer != null) {
System.out.println("digit:" + (answer.val));
answer = answer.next;
}
}
}
|
package tiny1.comp_semantica_estatica;
import tiny1.asint.ProcesamientoPorDefecto;
import tiny1.asint.TinyASint.*;
public class SimplificacionTipo extends ProcesamientoPorDefecto{
private boolean verbose;
public SimplificacionTipo(boolean verbose){
this.verbose = verbose;
}
private void log(String msg) {
if(verbose) {
System.out.println("SimplificacionTipo: " + msg);
}
}
@Override
public void procesa(DVar exp) {
exp.tipo().procesa(this);
exp.setType(exp.tipo().type());
log(exp.id().fila() + " " + exp.id().col()+ " " +exp.id().toString() + ": " + exp.tipo().toString() + " --> " + exp.tipo().tipoSimpl().toString() + ": " + exp.type().toString());
exp.setTipo(exp.tipo().tipoSimpl());
}
@Override
public void procesa(DTipo exp) {
exp.tipo().procesa(this);
exp.setType(exp.tipo().type());
log(exp.id().fila() + " " + exp.id().col()+ " " +exp.id().toString() + ": " + exp.tipo().toString() + " --> " + exp.tipo().tipoSimpl().toString() + ": " + exp.type().toString());
exp.setTipo(exp.tipo().tipoSimpl());
}
@Override
public void procesa(ParRef par) {
par.tipo().procesa(this);
par.setType(par.tipo().type());
log(par.id().fila() + " " + par.id().col()+ " " +par.id().toString() + ": " + par.tipo().toString() + " --> " + par.tipo().tipoSimpl().toString() + ": " + par.type().toString());
par.setTipo(par.tipo().tipoSimpl());
}
@Override
public void procesa(ParSinRef par) {
par.tipo().procesa(this);
par.setType(par.tipo().type());
log(par.id().fila() + " " + par.id().col()+ " " +par.id().toString() + ": " + par.tipo().toString() + " --> " + par.tipo().tipoSimpl().toString() + ": " + par.type().toString());
par.setTipo(par.tipo().tipoSimpl());
}
@Override
public void procesa(Campo c) {
c.tipo().procesa(this);
c.setType(c.tipo().type());
log(c.id().fila() + " " + c.id().col()+ " " +c.id().toString() + ": " + c.tipo().toString() + " --> " + c.tipo().tipoSimpl().toString() + ": " + c.type().toString());
c.setTipo(c.tipo().tipoSimpl());
}
@Override
public void procesa(ARRAY t) {
t.tipo().procesa(this);
log(t.tipo().toString());
t.setTipo(t.tipo().tipoSimpl());
log(t.tipo().toString());
}
@Override
public void procesa(POINTER t) {
t.tipo().procesa(this);
log(t.tipo().toString());
t.setTipo(t.tipo().tipoSimpl());
log(t.tipo().toString());
}
}
|
package me.mani.clhub;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import me.mani.clhub.DataManager.DataLoadException;
import me.mani.clhub.listener.*;
import me.mani.clhub.portal.Portal;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Hub extends JavaPlugin {
private static Hub instance;
private MongoClient mongoClient;
private DataManager dataManager;
private List<Portal> portals = new ArrayList<>();
@Override
public void onEnable() {
instance = this;
mongoClient = new MongoClient(new ServerAddress("craplezz.de", 27017), Arrays.asList(MongoCredential.createCredential("Overload", "admin", "1999mani123".toCharArray())));
dataManager = new DataManager(mongoClient, "todo", "general");
try {
portals = dataManager.loadPortals();
} catch (DataLoadException e) {
e.printStackTrace();
}
Bukkit.getPluginManager().registerEvents(new BlockBreakListener(), this);
Bukkit.getPluginManager().registerEvents(new PlayerMoveListener(), this);
Bukkit.getPluginManager().registerEvents(new PlayerJoinListener(), this);
Bukkit.getPluginManager().registerEvents(new PlayerQuitListener(), this);
Bukkit.getPluginManager().registerEvents(new EntityDamageListener(), this);
}
public MongoClient getMongoClient() {
return mongoClient;
}
public DataManager getDataManager() {
return dataManager;
}
public List<Portal> getPortals() {
return portals;
}
public static Hub getInstance() {
return instance;
}
}
|
package org.github.phani.apple.app;
public class Apple {
}
|
package com.kaysanshi.springsecurityoauth2.configure;
import com.kaysanshi.springsecurityoauth2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
/**
* Description:
* author2配置
* AuthorizationServerConfigurerAdapter 包括:
* ClientDetailsServiceConfigurer:用来配置客户端详情服务(ClientDetailsService),客户端详情信息在这里进行初始化,你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息。
* AuthorizationServerSecurityConfigurer:用来配置令牌端点(Token Endpoint)的安全约束.
* AuthorizationServerEndpointsConfigurer:用来配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services)。
*
* @date:2020/10/29 9:30
* @author: kaysanshi
**/
@Configuration
@EnableAuthorizationServer // 开启认证授权服务器
public class AuthorizationServerConfigure extends AuthorizationServerConfigurerAdapter {
// 密码授权的操作就是通过这个对象把密码传入授权服务器的
@Autowired
private AuthenticationManager authenticationManager;
// 将令牌信息存储到内存中
@Autowired(required = false)
private TokenStore inMemoryTokenStore; // 也可以使用redis进行存储
// 该对象将为刷新token提供支持
@Autowired
private UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
/**
* ClientDetailsServiceConfigurer
* 主要是注入ClientDetailsService实例对象(唯一配置注入)。其它地方可以通过ClientDetailsServiceConfigurer调用开发配置的ClientDetailsService。
* 系统提供的二个ClientDetailsService实现类:JdbcClientDetailsService、InMemoryClientDetailsService。
*
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {
// 配置一个基于password认证的。
clients.inMemory()
// 配置clientId
.withClient("admin")
// 配置client-secret
.secret(passwordEncoder.encode("112233"))
// 配置token过期时间
.accessTokenValiditySeconds(2630)
// 配置 redirectUri,用于授权成功后跳转
.redirectUris("http://www.baidu.com")
// 配置申请的权限范围
.scopes("all")
// 配置grant_type 表示授权类型。 使用密码模式
.authorizedGrantTypes("password");
}
/**
* 使用密码模式所需配置
* AuthorizationServerEndpointsConfigurer 访问端点配置 是一个装载类
* 装载Endpoints所有相关的类配置(AuthorizationServer、TokenServices、TokenStore、ClientDetailsService、UserDetailsService)。
* @param endpoints
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(inMemoryTokenStore) //配置令牌的存储(这里存放在内存中)
.authenticationManager(authenticationManager)
.userDetailsService(userService);
}
}
|
package com.yrz.comm;
import java.util.Objects;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class DataSourceSwitchAspect {
@Pointcut("execution(* com.yrz.service.db1.*.*(..))")
private void db1Aspect() {
}
@Pointcut("execution(* com.yrz.service.db2.*.*(..))")
private void db2Aspect() {
}
/**
* 执行service方法之前先切换数据源到db1
* @Title: db1
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param joinPoint 设定文件
* @author:yrz
* @data: 2019年5月21日 下午4:48:06
* @return void 返回类型
* @throws
*/
@Before( "db1Aspect()" )
public void db1(JoinPoint joinPoint) {
System.out.println("切换到db1 数据源...");
setDataSource(joinPoint,DBTypeEnum.db1);
}
/**
* 执行service方法之前先切换数据源到db2
* @Title: db1
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param joinPoint 设定文件
* @author:yrz
* @data: 2019年5月21日 下午4:48:06
* @return void 返回类型
* @throws
*/
@Before("db2Aspect()" )
public void db2 (JoinPoint joinPoint) {
System.out.println("切换到db2 数据源...");
setDataSource(joinPoint,DBTypeEnum.db2);
}
/**
* 添加注解方式,如果有注解优先注解,没有则按传过来的数据源配置
* @param joinPoint
* @param dbTypeEnum
*/
private void setDataSource(JoinPoint joinPoint, DBTypeEnum dbTypeEnum) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
DataSourceSwitch dataSourceSwitch = methodSignature.getMethod().getAnnotation(DataSourceSwitch.class);
if (Objects.isNull(dataSourceSwitch) || Objects.isNull(dataSourceSwitch.value())) {
DbContextHolder.setDbType(dbTypeEnum);
}else{
System.out.println("根据注解来切换数据源,注解值为:"+dataSourceSwitch.value());
switch (dataSourceSwitch.value().getValue()) {
case "db1":
DbContextHolder.setDbType(DBTypeEnum.db1);
break;
case "db2":
DbContextHolder.setDbType(DBTypeEnum.db2);
break;
default:
DbContextHolder.setDbType(dbTypeEnum);
}
}
}
}
|
package com.cube.storm.language.data;
import androidx.annotation.NonNull;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
/**
* Basic language model with a map of key/value pairs for the language.
* <p/>
* This model contains a map of all the key/value localsations stored in a localisation file.
* The entire localisation language is loaded into one of these models. Be careful not to have a language
* pack that is too large else you may experience memory problems.
*
* @author Callum Taylor
* @project LightningLanguage
*/
public class Language implements Serializable
{
/**
* Source Uri of the language object
*/
@Getter @Setter protected String sourceUri;
/**
* Values of the language file
*/
@Getter @Setter protected Map<String, String> values = new HashMap<String, String>(0);
/**
* Gets the language value from a String key
*
* @param id The ID of the string
*
* @return The language translation or an empty string
*/
@NonNull
public String getValue(@NonNull String id)
{
return values.get(id) == null ? "" : values.get(id);
}
/**
* Checks for ID in the translation list
*
* @param id The ID of the string to check
*
* @return true if found, false if not
*/
public boolean hasValue(@NonNull String id)
{
return values.containsKey(id);
}
}
|
package gr.athena.innovation.fagi.core.function.date;
import gr.athena.innovation.fagi.core.function.IFunction;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.jena.rdf.model.Literal;
import gr.athena.innovation.fagi.core.function.IFunctionTwoLiteralStringParameters;
/**
* Class for evaluating valid date strings against a date format.
*
* @author nkarag
*/
public class IsValidDate implements IFunction, IFunctionTwoLiteralStringParameters{
/**
* Validates the date range of the given date string using the lenient property of date.
*
* @param date the date literal.
* @param format the SimpleDateFormat of the date string
* @return true if the date is valid and false if the date is invalid or it does not agree with the given format.
*/
@Override
public boolean evaluate(Literal date, String format) {
if(date == null){
return false;
}
//TODO - consider using https://github.com/joestelmach/natty for parsing unknown formats
boolean isValid;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
simpleDateFormat.setLenient(false);
try {
simpleDateFormat.parse(date.getString());
isValid = true;
} catch (ParseException ex) {
//LOG.error("Error parsing date: " + date + " with format: " + format);
//LOG.error(ex);
isValid = false;
}
return isValid;
}
@Override
public String getName() {
String className = this.getClass().getSimpleName().toLowerCase();
return className;
}
}
|
package 集合;
/**
* @Author: Mr.M
* @Date: 2019-02-26 11:01
* @Description:
**/
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode() {
}
public TreeNode(int x) {
val = x;
}
}
|
public interface SpaceBalls{
boolean spaceBalls();
}
|
package gr.athena.innovation.fagi.evaluation;
import gr.athena.innovation.fagi.core.normalizer.AdvancedGenericNormalizer;
import gr.athena.innovation.fagi.core.normalizer.BasicGenericNormalizer;
import gr.athena.innovation.fagi.core.similarity.Cosine;
import gr.athena.innovation.fagi.core.similarity.Jaccard;
import gr.athena.innovation.fagi.core.similarity.Jaro;
import gr.athena.innovation.fagi.core.similarity.JaroWinkler;
import gr.athena.innovation.fagi.core.similarity.Levenshtein;
import gr.athena.innovation.fagi.core.similarity.LongestCommonSubsequenceMetric;
import gr.athena.innovation.fagi.core.similarity.NGram;
import gr.athena.innovation.fagi.core.similarity.SortedJaroWinkler;
import gr.athena.innovation.fagi.core.similarity.WeightedSimilarity;
import gr.athena.innovation.fagi.exception.ApplicationException;
import gr.athena.innovation.fagi.model.NormalizedLiteral;
import gr.athena.innovation.fagi.model.WeightedPairLiteral;
import gr.athena.innovation.fagi.specification.Configuration;
import gr.athena.innovation.fagi.specification.SpecificationConstants;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Class for calculation of accuracy, precision, recall and harmonic mean for linked pairs and acceptance label.
*
* @author nkarag
*/
public class MetricProcessor {
private static final Logger LOG = LogManager.getLogger(MetricProcessor.class);
private static final String SEP = ",";
private final Configuration configuration;
private static final String ACCEPT = "ACCEPT";
private static final String REJECT = "REJECT";
private int totalRows = 0;
Accuracy optimalAccuracy = new Accuracy();
private Map<String, List<Double>> aLevenPrecisionMap = new HashMap<>();
private Map<String, List<Double>> bLevenPrecisionMap = new HashMap<>();
private Map<String, List<Double>> cLevenPrecisionMap = new HashMap<>();
private Map<String, List<Double>> dLevenPrecisionMap = new HashMap<>();
private Map<String, List<Double>> aNGramPrecisionMap = new HashMap<>();
private Map<String, List<Double>> bNGramPrecisionMap = new HashMap<>();
private Map<String, List<Double>> cNGramPrecisionMap = new HashMap<>();
private Map<String, List<Double>> dNGramPrecisionMap = new HashMap<>();
private Map<String, List<Double>> aCosinePrecisionMap = new HashMap<>();
private Map<String, List<Double>> bCosinePrecisionMap = new HashMap<>();
private Map<String, List<Double>> cCosinePrecisionMap = new HashMap<>();
private Map<String, List<Double>> dCosinePrecisionMap = new HashMap<>();
private Map<String, List<Double>> aLqsPrecisionMap = new HashMap<>();
private Map<String, List<Double>> bLqsPrecisionMap = new HashMap<>();
private Map<String, List<Double>> cLqsPrecisionMap = new HashMap<>();
private Map<String, List<Double>> dLqsPrecisionMap = new HashMap<>();
private Map<String, List<Double>> aJaccardPrecisionMap = new HashMap<>();
private Map<String, List<Double>> bJaccardPrecisionMap = new HashMap<>();
private Map<String, List<Double>> cJaccardPrecisionMap = new HashMap<>();
private Map<String, List<Double>> dJaccardPrecisionMap = new HashMap<>();
private Map<String, List<Double>> aJaroPrecisionMap = new HashMap<>();
private Map<String, List<Double>> bJaroPrecisionMap = new HashMap<>();
private Map<String, List<Double>> cJaroPrecisionMap = new HashMap<>();
private Map<String, List<Double>> dJaroPrecisionMap = new HashMap<>();
private Map<String, List<Double>> aJaroWinklerPrecisionMap = new HashMap<>();
private Map<String, List<Double>> bJaroWinklerPrecisionMap = new HashMap<>();
private Map<String, List<Double>> cJaroWinklerPrecisionMap = new HashMap<>();
private Map<String, List<Double>> dJaroWinklerPrecisionMap = new HashMap<>();
private Map<String, List<Double>> aSortedJaroWinklerPrecisionMap = new HashMap<>();
private Map<String, List<Double>> bSortedJaroWinklerPrecisionMap = new HashMap<>();
private Map<String, List<Double>> cSortedJaroWinklerPrecisionMap = new HashMap<>();
private Map<String, List<Double>> dSortedJaroWinklerPrecisionMap = new HashMap<>();
private Threshold optimalThreshold = new Threshold();
/**
* Constructor of a metric processor object.
* Initializes the hashmaps with accept/reject keys and arraylist values.
*
* @param configuration
*/
public MetricProcessor(Configuration configuration) {
this.configuration = configuration;
aLevenPrecisionMap.put(ACCEPT, new ArrayList<>());
aLevenPrecisionMap.put(REJECT, new ArrayList<>());
bLevenPrecisionMap.put(ACCEPT, new ArrayList<>());
bLevenPrecisionMap.put(REJECT, new ArrayList<>());
cLevenPrecisionMap.put(ACCEPT, new ArrayList<>());
cLevenPrecisionMap.put(REJECT, new ArrayList<>());
dLevenPrecisionMap.put(ACCEPT, new ArrayList<>());
dLevenPrecisionMap.put(REJECT, new ArrayList<>());
aNGramPrecisionMap.put(ACCEPT, new ArrayList<>());
aNGramPrecisionMap.put(REJECT, new ArrayList<>());
bNGramPrecisionMap.put(ACCEPT, new ArrayList<>());
bNGramPrecisionMap.put(REJECT, new ArrayList<>());
cNGramPrecisionMap.put(ACCEPT, new ArrayList<>());
cNGramPrecisionMap.put(REJECT, new ArrayList<>());
dNGramPrecisionMap.put(ACCEPT, new ArrayList<>());
dNGramPrecisionMap.put(REJECT, new ArrayList<>());
aCosinePrecisionMap.put(ACCEPT, new ArrayList<>());
aCosinePrecisionMap.put(REJECT, new ArrayList<>());
bCosinePrecisionMap.put(ACCEPT, new ArrayList<>());
bCosinePrecisionMap.put(REJECT, new ArrayList<>());
cCosinePrecisionMap.put(ACCEPT, new ArrayList<>());
cCosinePrecisionMap.put(REJECT, new ArrayList<>());
dCosinePrecisionMap.put(ACCEPT, new ArrayList<>());
dCosinePrecisionMap.put(REJECT, new ArrayList<>());
aLqsPrecisionMap.put(ACCEPT, new ArrayList<>());
aLqsPrecisionMap.put(REJECT, new ArrayList<>());
bLqsPrecisionMap.put(ACCEPT, new ArrayList<>());
bLqsPrecisionMap.put(REJECT, new ArrayList<>());
cLqsPrecisionMap.put(ACCEPT, new ArrayList<>());
cLqsPrecisionMap.put(REJECT, new ArrayList<>());
dLqsPrecisionMap.put(ACCEPT, new ArrayList<>());
dLqsPrecisionMap.put(REJECT, new ArrayList<>());
aJaccardPrecisionMap.put(ACCEPT, new ArrayList<>());
aJaccardPrecisionMap.put(REJECT, new ArrayList<>());
bJaccardPrecisionMap.put(ACCEPT, new ArrayList<>());
bJaccardPrecisionMap.put(REJECT, new ArrayList<>());
cJaccardPrecisionMap.put(ACCEPT, new ArrayList<>());
cJaccardPrecisionMap.put(REJECT, new ArrayList<>());
dJaccardPrecisionMap.put(ACCEPT, new ArrayList<>());
dJaccardPrecisionMap.put(REJECT, new ArrayList<>());
aJaroPrecisionMap.put(ACCEPT, new ArrayList<>());
aJaroPrecisionMap.put(REJECT, new ArrayList<>());
bJaroPrecisionMap.put(ACCEPT, new ArrayList<>());
bJaroPrecisionMap.put(REJECT, new ArrayList<>());
cJaroPrecisionMap.put(ACCEPT, new ArrayList<>());
cJaroPrecisionMap.put(REJECT, new ArrayList<>());
dJaroPrecisionMap.put(ACCEPT, new ArrayList<>());
dJaroPrecisionMap.put(REJECT, new ArrayList<>());
aJaroWinklerPrecisionMap.put(ACCEPT, new ArrayList<>());
aJaroWinklerPrecisionMap.put(REJECT, new ArrayList<>());
bJaroWinklerPrecisionMap.put(ACCEPT, new ArrayList<>());
bJaroWinklerPrecisionMap.put(REJECT, new ArrayList<>());
cJaroWinklerPrecisionMap.put(ACCEPT, new ArrayList<>());
cJaroWinklerPrecisionMap.put(REJECT, new ArrayList<>());
dJaroWinklerPrecisionMap.put(ACCEPT, new ArrayList<>());
dJaroWinklerPrecisionMap.put(REJECT, new ArrayList<>());
aSortedJaroWinklerPrecisionMap.put(ACCEPT, new ArrayList<>());
aSortedJaroWinklerPrecisionMap.put(REJECT, new ArrayList<>());
bSortedJaroWinklerPrecisionMap.put(ACCEPT, new ArrayList<>());
bSortedJaroWinklerPrecisionMap.put(REJECT, new ArrayList<>());
cSortedJaroWinklerPrecisionMap.put(ACCEPT, new ArrayList<>());
cSortedJaroWinklerPrecisionMap.put(REJECT, new ArrayList<>());
dSortedJaroWinklerPrecisionMap.put(ACCEPT, new ArrayList<>());
dSortedJaroWinklerPrecisionMap.put(REJECT, new ArrayList<>());
}
/**
* Executes the evaluation.
*
* @param csvPath the csv path containing the training samples.
* @param resultsPath the output path of the results as a string.
* @param propertyName the property name as a string.
* @param thresholdsFilename the name of the optimal-threshold file.
* @param notes the information of the current evaluation as a string.
* @throws FileNotFoundException indicates FileNotFoundException.
* @throws IOException indicates I/O exception.
*/
public void executeEvaluation(String csvPath, String resultsPath, String propertyName, String thresholdsFilename,
String notes) throws FileNotFoundException, IOException {
String propertyPath = resultsPath + propertyName;
File metricsFile = new File(propertyPath);
if (metricsFile.exists()) {
//clear contents
PrintWriter pw = new PrintWriter(propertyPath);
pw.close();
} else {
metricsFile.getParentFile().mkdirs();
metricsFile.createNewFile();
}
LOG.info("Evaluation output at " + metricsFile.getAbsolutePath());
try (BufferedWriter metricsWriter = new BufferedWriter(new FileWriter(metricsFile, true))) {
double[] thresholds =
{0.05, 0.1, 0.15, 0.2, 0.30, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95};
for (int i = 0; i < thresholds.length; i++) {
clearPrecisionMapLists(aLevenPrecisionMap);
clearPrecisionMapLists(bLevenPrecisionMap);
clearPrecisionMapLists(cLevenPrecisionMap);
clearPrecisionMapLists(dLevenPrecisionMap);
clearPrecisionMapLists(aNGramPrecisionMap);
clearPrecisionMapLists(bNGramPrecisionMap);
clearPrecisionMapLists(cNGramPrecisionMap);
clearPrecisionMapLists(dNGramPrecisionMap);
clearPrecisionMapLists(aCosinePrecisionMap);
clearPrecisionMapLists(bCosinePrecisionMap);
clearPrecisionMapLists(cCosinePrecisionMap);
clearPrecisionMapLists(dCosinePrecisionMap);
clearPrecisionMapLists(aLqsPrecisionMap);
clearPrecisionMapLists(bLqsPrecisionMap);
clearPrecisionMapLists(cLqsPrecisionMap);
clearPrecisionMapLists(dLqsPrecisionMap);
clearPrecisionMapLists(aJaccardPrecisionMap);
clearPrecisionMapLists(bJaccardPrecisionMap);
clearPrecisionMapLists(cJaccardPrecisionMap);
clearPrecisionMapLists(dJaccardPrecisionMap);
clearPrecisionMapLists(aJaroPrecisionMap);
clearPrecisionMapLists(bJaroPrecisionMap);
clearPrecisionMapLists(cJaroPrecisionMap);
clearPrecisionMapLists(dJaroPrecisionMap);
clearPrecisionMapLists(aJaroWinklerPrecisionMap);
clearPrecisionMapLists(bJaroWinklerPrecisionMap);
clearPrecisionMapLists(cJaroWinklerPrecisionMap);
clearPrecisionMapLists(dJaroWinklerPrecisionMap);
clearPrecisionMapLists(aSortedJaroWinklerPrecisionMap);
clearPrecisionMapLists(bSortedJaroWinklerPrecisionMap);
clearPrecisionMapLists(cSortedJaroWinklerPrecisionMap);
clearPrecisionMapLists(dSortedJaroWinklerPrecisionMap);
double thres = thresholds[i];
Accuracy aAccuracy = new Accuracy();
Accuracy bAccuracy = new Accuracy();
Accuracy cAccuracy = new Accuracy();
Accuracy dAccuracy = new Accuracy();
executeThreshold(metricsWriter, csvPath, thres, aAccuracy, bAccuracy, cAccuracy, dAccuracy);
}
String thresholdsPath = resultsPath + thresholdsFilename;
File thresholdsFile = new File(thresholdsPath);
if (thresholdsFile.exists()) {
//clear contents
PrintWriter pw = new PrintWriter(thresholdsPath);
pw.close();
} else {
thresholdsFile.getParentFile().mkdirs();
thresholdsFile.createNewFile();
}
try (BufferedWriter thresholdWriter = new BufferedWriter(new FileWriter(thresholdsFile, true))) {
thresholdWriter.append(optimalThreshold.toString());
thresholdWriter.newLine();
}
String notesPath = resultsPath + "notes.txt";
File notesFile = new File(notesPath);
if (notesFile.exists()) {
//clear contents
PrintWriter pw = new PrintWriter(notesPath);
pw.close();
} else {
notesFile.getParentFile().mkdirs();
notesFile.createNewFile();
}
try (BufferedWriter notesWriter = new BufferedWriter(new FileWriter(notesFile, true))) {
notesWriter.append(notes);
notesWriter.newLine();
}
}
}
private void executeThreshold(BufferedWriter writer, String csvPath, double threshold,
Accuracy aAccuracy, Accuracy bAccuracy, Accuracy cAccuracy, Accuracy dAccuracy)
throws FileNotFoundException, IOException{
LOG.trace("Calculating for threshold " + threshold);
totalRows = 0;
String line;
String cvsSplitBy = "\\^";
Locale locale = configuration.getLocale();
int l = 0;
BufferedReader br = new BufferedReader(new FileReader(csvPath));
try {
//toggle configuration
//executeOriginalSet(l, br, cvsSplitBy, locale, threshold, aAccuracy, bAccuracy, cAccuracy, dAccuracy);
executeBalancedSet(l, br, cvsSplitBy, locale, threshold, aAccuracy, bAccuracy, cAccuracy, dAccuracy);
int aLevenPrecisionAcceptCounter = count(aLevenPrecisionMap.get(ACCEPT), threshold);
int aLevenPrecisionRejectCounter = count(aLevenPrecisionMap.get(REJECT), threshold);
int bLevenPrecisionAcceptCounter = count(bLevenPrecisionMap.get(ACCEPT), threshold);
int bLevenPrecisionRejectCounter = count(bLevenPrecisionMap.get(REJECT), threshold);
int cLevenPrecisionAcceptCounter = count(cLevenPrecisionMap.get(ACCEPT), threshold);
int cLevenPrecisionRejectCounter = count(cLevenPrecisionMap.get(REJECT), threshold);
int dLevenPrecisionAcceptCounter = count(dLevenPrecisionMap.get(ACCEPT), threshold);
int dLevenPrecisionRejectCounter = count(dLevenPrecisionMap.get(REJECT), threshold);
int aNGramPrecisionAcceptCounter = count(aNGramPrecisionMap.get(ACCEPT), threshold);
int aNGramPrecisionRejectCounter = count(aNGramPrecisionMap.get(REJECT), threshold);
int bNGramPrecisionAcceptCounter = count(bNGramPrecisionMap.get(ACCEPT), threshold);
int bNGramPrecisionRejectCounter = count(bNGramPrecisionMap.get(REJECT), threshold);
int cNGramPrecisionAcceptCounter = count(cNGramPrecisionMap.get(ACCEPT), threshold);
int cNGramPrecisionRejectCounter = count(cNGramPrecisionMap.get(REJECT), threshold);
int dNGramPrecisionAcceptCounter = count(dNGramPrecisionMap.get(ACCEPT), threshold);
int dNGramPrecisionRejectCounter = count(dNGramPrecisionMap.get(REJECT), threshold);
int aCosinePrecisionAcceptCounter = count(aCosinePrecisionMap.get(ACCEPT), threshold);
int aCosinePrecisionRejectCounter = count(aCosinePrecisionMap.get(REJECT), threshold);
int bCosinePrecisionAcceptCounter = count(bCosinePrecisionMap.get(ACCEPT), threshold);
int bCosinePrecisionRejectCounter = count(bCosinePrecisionMap.get(REJECT), threshold);
int cCosinePrecisionAcceptCounter = count(cCosinePrecisionMap.get(ACCEPT), threshold);
int cCosinePrecisionRejectCounter = count(cCosinePrecisionMap.get(REJECT), threshold);
int dCosinePrecisionAcceptCounter = count(dCosinePrecisionMap.get(ACCEPT), threshold);
int dCosinePrecisionRejectCounter = count(dCosinePrecisionMap.get(REJECT), threshold);
int aLqsPrecisionAcceptCounter = count(aLqsPrecisionMap.get(ACCEPT), threshold);
int aLqsPrecisionRejectCounter = count(aLqsPrecisionMap.get(REJECT), threshold);
int bLqsPrecisionAcceptCounter = count(bLqsPrecisionMap.get(ACCEPT), threshold);
int bLqsPrecisionRejectCounter = count(bLqsPrecisionMap.get(REJECT), threshold);
int cLqsPrecisionAcceptCounter = count(cLqsPrecisionMap.get(ACCEPT), threshold);
int cLqsPrecisionRejectCounter = count(cLqsPrecisionMap.get(REJECT), threshold);
int dLqsPrecisionAcceptCounter = count(dLqsPrecisionMap.get(ACCEPT), threshold);
int dLqsPrecisionRejectCounter = count(dLqsPrecisionMap.get(REJECT), threshold);
int aJaccardPrecisionAcceptCounter = count(aJaccardPrecisionMap.get(ACCEPT), threshold);
int aJaccardPrecisionRejectCounter = count(aJaccardPrecisionMap.get(REJECT), threshold);
int bJaccardPrecisionAcceptCounter = count(bJaccardPrecisionMap.get(ACCEPT), threshold);
int bJaccardPrecisionRejectCounter = count(bJaccardPrecisionMap.get(REJECT), threshold);
int cJaccardPrecisionAcceptCounter = count(cJaccardPrecisionMap.get(ACCEPT), threshold);
int cJaccardPrecisionRejectCounter = count(cJaccardPrecisionMap.get(REJECT), threshold);
int dJaccardPrecisionAcceptCounter = count(dJaccardPrecisionMap.get(ACCEPT), threshold);
int dJaccardPrecisionRejectCounter = count(dJaccardPrecisionMap.get(REJECT), threshold);
int aJaroPrecisionAcceptCounter = count(aJaroPrecisionMap.get(ACCEPT), threshold);
int aJaroPrecisionRejectCounter = count(aJaroPrecisionMap.get(REJECT), threshold);
int bJaroPrecisionAcceptCounter = count(bJaroPrecisionMap.get(ACCEPT), threshold);
int bJaroPrecisionRejectCounter = count(bJaroPrecisionMap.get(REJECT), threshold);
int cJaroPrecisionAcceptCounter = count(cJaroPrecisionMap.get(ACCEPT), threshold);
int cJaroPrecisionRejectCounter = count(cJaroPrecisionMap.get(REJECT), threshold);
int dJaroPrecisionAcceptCounter = count(dJaroPrecisionMap.get(ACCEPT), threshold);
int dJaroPrecisionRejectCounter = count(dJaroPrecisionMap.get(REJECT), threshold);
int aJaroWinklerPrecisionAcceptCounter = count(aJaroWinklerPrecisionMap.get(ACCEPT), threshold);
int aJaroWinklerPrecisionRejectCounter = count(aJaroWinklerPrecisionMap.get(REJECT), threshold);
int bJaroWinklerPrecisionAcceptCounter = count(bJaroWinklerPrecisionMap.get(ACCEPT), threshold);
int bJaroWinklerPrecisionRejectCounter = count(bJaroWinklerPrecisionMap.get(REJECT), threshold);
int cJaroWinklerPrecisionAcceptCounter = count(cJaroWinklerPrecisionMap.get(ACCEPT), threshold);
int cJaroWinklerPrecisionRejectCounter = count(cJaroWinklerPrecisionMap.get(REJECT), threshold);
int dJaroWinklerPrecisionAcceptCounter = count(dJaroWinklerPrecisionMap.get(ACCEPT), threshold);
int dJaroWinklerPrecisionRejectCounter = count(dJaroWinklerPrecisionMap.get(REJECT), threshold);
int aSortedJaroWinklerPrecisionAcceptCounter = count(aSortedJaroWinklerPrecisionMap.get(ACCEPT), threshold);
int aSortedJaroWinklerPrecisionRejectCounter = count(aSortedJaroWinklerPrecisionMap.get(REJECT), threshold);
int bSortedJaroWinklerPrecisionAcceptCounter = count(bSortedJaroWinklerPrecisionMap.get(ACCEPT), threshold);
int bSortedJaroWinklerPrecisionRejectCounter = count(bSortedJaroWinklerPrecisionMap.get(REJECT), threshold);
int cSortedJaroWinklerPrecisionAcceptCounter = count(cSortedJaroWinklerPrecisionMap.get(ACCEPT), threshold);
int cSortedJaroWinklerPrecisionRejectCounter = count(cSortedJaroWinklerPrecisionMap.get(REJECT), threshold);
int dSortedJaroWinklerPrecisionAcceptCounter = count(dSortedJaroWinklerPrecisionMap.get(ACCEPT), threshold);
int dSortedJaroWinklerPrecisionRejectCounter = count(dSortedJaroWinklerPrecisionMap.get(REJECT), threshold);
double aLevenAccuracy = calculateAccuracy(aAccuracy.getLevenshteinCount(), totalRows);
double aLevenPrecision = calculatePrecision(aLevenPrecisionAcceptCounter, aLevenPrecisionRejectCounter);
double aLevenRecall= calculateRecall(aLevenPrecisionAcceptCounter, aLevenPrecisionMap);
double aLevenHarmonicMean = calculateHarmonicMean(aLevenPrecision, aLevenRecall);
double bLevenAccuracy = calculateAccuracy(bAccuracy.getLevenshteinCount(), totalRows);
double bLevenPrecision = calculatePrecision(bLevenPrecisionAcceptCounter, bLevenPrecisionRejectCounter);
double bLevenRecall= calculateRecall(bLevenPrecisionAcceptCounter, bLevenPrecisionMap);
double bLevenHarmonicMean = calculateHarmonicMean(bLevenPrecision, bLevenRecall);
double cLevenAccuracy = calculateAccuracy(cAccuracy.getLevenshteinCount(), totalRows);
double cLevenPrecision = calculatePrecision(cLevenPrecisionAcceptCounter, cLevenPrecisionRejectCounter);
double cLevenRecall= calculateRecall(cLevenPrecisionAcceptCounter, cLevenPrecisionMap);
double cLevenHarmonicMean = calculateHarmonicMean(cLevenPrecision, cLevenRecall);
double dLevenAccuracy = calculateAccuracy(dAccuracy.getLevenshteinCount(), totalRows);
double dLevenPrecision = calculatePrecision(dLevenPrecisionAcceptCounter, dLevenPrecisionRejectCounter);
double dLevenRecall= calculateRecall(dLevenPrecisionAcceptCounter, dLevenPrecisionMap);
double dLevenHarmonicMean = calculateHarmonicMean(dLevenPrecision, dLevenRecall);
double aNGramAccuracy = calculateAccuracy(aAccuracy.getNgram2Count(), totalRows);
double aNGramPrecision = calculatePrecision(aNGramPrecisionAcceptCounter, aNGramPrecisionRejectCounter);
double aNGramRecall= calculateRecall(aNGramPrecisionAcceptCounter, aNGramPrecisionMap);
double aNGramHarmonicMean = calculateHarmonicMean(aNGramPrecision, aNGramRecall);
double bNGramAccuracy = calculateAccuracy(bAccuracy.getNgram2Count(), totalRows);
double bNGramPrecision = calculatePrecision(bNGramPrecisionAcceptCounter, bNGramPrecisionRejectCounter);
double bNGramRecall= calculateRecall(bNGramPrecisionAcceptCounter, bNGramPrecisionMap);
double bNGramHarmonicMean = calculateHarmonicMean(bNGramPrecision, bNGramRecall);
double cNGramAccuracy = calculateAccuracy(cAccuracy.getNgram2Count(), totalRows);
double cNGramPrecision = calculatePrecision(cNGramPrecisionAcceptCounter, cNGramPrecisionRejectCounter);
double cNGramRecall= calculateRecall(cNGramPrecisionAcceptCounter, cNGramPrecisionMap);
double cNGramHarmonicMean = calculateHarmonicMean(cNGramPrecision, cNGramRecall);
double dNGramAccuracy = calculateAccuracy(dAccuracy.getNgram2Count(), totalRows);
double dNGramPrecision = calculatePrecision(dNGramPrecisionAcceptCounter, dNGramPrecisionRejectCounter);
double dNGramRecall= calculateRecall(dNGramPrecisionAcceptCounter, dNGramPrecisionMap);
double dNGramHarmonicMean = calculateHarmonicMean(dNGramPrecision, dNGramRecall);
double aCosineAccuracy = calculateAccuracy(aAccuracy.getCosineCount(), totalRows);
double aCosinePrecision = calculatePrecision(aCosinePrecisionAcceptCounter, aCosinePrecisionRejectCounter);
double aCosineRecall= calculateRecall(aCosinePrecisionAcceptCounter, aCosinePrecisionMap);
double aCosineHarmonicMean = calculateHarmonicMean(aCosinePrecision, aCosineRecall);
double bCosineAccuracy = calculateAccuracy(bAccuracy.getCosineCount(), totalRows);
double bCosinePrecision = calculatePrecision(bCosinePrecisionAcceptCounter, bCosinePrecisionRejectCounter);
double bCosineRecall= calculateRecall(bCosinePrecisionAcceptCounter, bCosinePrecisionMap);
double bCosineHarmonicMean = calculateHarmonicMean(bCosinePrecision, bCosineRecall);
double cCosineAccuracy = calculateAccuracy(cAccuracy.getCosineCount(), totalRows);
double cCosinePrecision = calculatePrecision(cCosinePrecisionAcceptCounter, cCosinePrecisionRejectCounter);
double cCosineRecall= calculateRecall(cCosinePrecisionAcceptCounter, cCosinePrecisionMap);
double cCosineHarmonicMean = calculateHarmonicMean(cCosinePrecision, cCosineRecall);
double dCosineAccuracy = calculateAccuracy(dAccuracy.getCosineCount(), totalRows);
double dCosinePrecision = calculatePrecision(dCosinePrecisionAcceptCounter, dCosinePrecisionRejectCounter);
double dCosineRecall= calculateRecall(dCosinePrecisionAcceptCounter, dCosinePrecisionMap);
double dCosineHarmonicMean = calculateHarmonicMean(dCosinePrecision, dCosineRecall);
double aLqsAccuracy = calculateAccuracy(aAccuracy.getLqsCount(), totalRows);
double aLqsPrecision = calculatePrecision(aLqsPrecisionAcceptCounter, aLqsPrecisionRejectCounter);
double aLqsRecall= calculateRecall(aLqsPrecisionAcceptCounter, aLqsPrecisionMap);
double aLqsHarmonicMean = calculateHarmonicMean(aLqsPrecision, aLqsRecall);
double bLqsAccuracy = calculateAccuracy(bAccuracy.getLqsCount(), totalRows);
double bLqsPrecision = calculatePrecision(bLqsPrecisionAcceptCounter, bLqsPrecisionRejectCounter);
double bLqsRecall= calculateRecall(bLqsPrecisionAcceptCounter, bLqsPrecisionMap);
double bLqsHarmonicMean = calculateHarmonicMean(bLqsPrecision, bLqsRecall);
double cLqsAccuracy = calculateAccuracy(cAccuracy.getLqsCount(), totalRows);
double cLqsPrecision = calculatePrecision(cLqsPrecisionAcceptCounter, cLqsPrecisionRejectCounter);
double cLqsRecall= calculateRecall(cLqsPrecisionAcceptCounter, cLqsPrecisionMap);
double cLqsHarmonicMean = calculateHarmonicMean(cLqsPrecision, cLqsRecall);
double dLqsAccuracy = calculateAccuracy(dAccuracy.getLqsCount(), totalRows);
double dLqsPrecision = calculatePrecision(dLqsPrecisionAcceptCounter, dLqsPrecisionRejectCounter);
double dLqsRecall= calculateRecall(dLqsPrecisionAcceptCounter, dLqsPrecisionMap);
double dLqsHarmonicMean = calculateHarmonicMean(dLqsPrecision, dLqsRecall);
double aJaccardAccuracy = calculateAccuracy(aAccuracy.getJaccardCount(), totalRows);
double aJaccardPrecision = calculatePrecision(aJaccardPrecisionAcceptCounter, aJaccardPrecisionRejectCounter);
double aJaccardRecall= calculateRecall(aJaccardPrecisionAcceptCounter, aJaccardPrecisionMap);
double aJaccardHarmonicMean = calculateHarmonicMean(aJaccardPrecision, aJaccardRecall);
double bJaccardAccuracy = calculateAccuracy(bAccuracy.getJaccardCount(), totalRows);
double bJaccardPrecision = calculatePrecision(bJaccardPrecisionAcceptCounter, bJaccardPrecisionRejectCounter);
double bJaccardRecall= calculateRecall(bJaccardPrecisionAcceptCounter, bJaccardPrecisionMap);
double bJaccardHarmonicMean = calculateHarmonicMean(bJaccardPrecision, bJaccardRecall);
double cJaccardAccuracy = calculateAccuracy(cAccuracy.getJaccardCount(), totalRows);
double cJaccardPrecision = calculatePrecision(cJaccardPrecisionAcceptCounter, cJaccardPrecisionRejectCounter);
double cJaccardRecall= calculateRecall(cJaccardPrecisionAcceptCounter, cJaccardPrecisionMap);
double cJaccardHarmonicMean = calculateHarmonicMean(cJaccardPrecision, cJaccardRecall);
double dJaccardAccuracy = calculateAccuracy(dAccuracy.getJaccardCount(), totalRows);
double dJaccardPrecision = calculatePrecision(dJaccardPrecisionAcceptCounter, dJaccardPrecisionRejectCounter);
double dJaccardRecall= calculateRecall(dJaccardPrecisionAcceptCounter, dJaccardPrecisionMap);
double dJaccardHarmonicMean = calculateHarmonicMean(dJaccardPrecision, dJaccardRecall);
double aJaroAccuracy = calculateAccuracy(aAccuracy.getJaroCount(), totalRows);
double aJaroPrecision = calculatePrecision(aJaroPrecisionAcceptCounter, aJaroPrecisionRejectCounter);
double aJaroRecall= calculateRecall(aJaroPrecisionAcceptCounter, aJaroPrecisionMap);
double aJaroHarmonicMean = calculateHarmonicMean(aJaroPrecision, aJaroRecall);
double bJaroAccuracy = calculateAccuracy(bAccuracy.getJaroCount(), totalRows);
double bJaroPrecision = calculatePrecision(bJaroPrecisionAcceptCounter, bJaroPrecisionRejectCounter);
double bJaroRecall= calculateRecall(bJaroPrecisionAcceptCounter, bJaroPrecisionMap);
double bJaroHarmonicMean = calculateHarmonicMean(bJaroPrecision, bJaroRecall);
double cJaroAccuracy = calculateAccuracy(cAccuracy.getJaroCount(), totalRows);
double cJaroPrecision = calculatePrecision(cJaroPrecisionAcceptCounter, cJaroPrecisionRejectCounter);
double cJaroRecall= calculateRecall(cJaroPrecisionAcceptCounter, cJaroPrecisionMap);
double cJaroHarmonicMean = calculateHarmonicMean(cJaroPrecision, cJaroRecall);
double dJaroAccuracy = calculateAccuracy(dAccuracy.getJaroCount(), totalRows);
double dJaroPrecision = calculatePrecision(dJaroPrecisionAcceptCounter, dJaroPrecisionRejectCounter);
double dJaroRecall= calculateRecall(dJaroPrecisionAcceptCounter, dJaroPrecisionMap);
double dJaroHarmonicMean = calculateHarmonicMean(dJaroPrecision, dJaroRecall);
double aJaroWinklerAccuracy = calculateAccuracy(aAccuracy.getJaroWinklerCount(), totalRows);
double aJaroWinklerPrecision = calculatePrecision(aJaroWinklerPrecisionAcceptCounter, aJaroWinklerPrecisionRejectCounter);
double aJaroWinklerRecall= calculateRecall(aJaroWinklerPrecisionAcceptCounter, aJaroWinklerPrecisionMap);
double aJaroWinklerHarmonicMean = calculateHarmonicMean(aJaroWinklerPrecision, aJaroWinklerRecall);
double bJaroWinklerAccuracy = calculateAccuracy(bAccuracy.getJaroWinklerCount(), totalRows);
double bJaroWinklerPrecision = calculatePrecision(bJaroWinklerPrecisionAcceptCounter, bJaroWinklerPrecisionRejectCounter);
double bJaroWinklerRecall= calculateRecall(bJaroWinklerPrecisionAcceptCounter, bJaroWinklerPrecisionMap);
double bJaroWinklerHarmonicMean = calculateHarmonicMean(bJaroWinklerPrecision, bJaroWinklerRecall);
double cJaroWinklerAccuracy = calculateAccuracy(cAccuracy.getJaroWinklerCount(), totalRows);
double cJaroWinklerPrecision = calculatePrecision(cJaroWinklerPrecisionAcceptCounter, cJaroWinklerPrecisionRejectCounter);
double cJaroWinklerRecall= calculateRecall(cJaroWinklerPrecisionAcceptCounter, cJaroWinklerPrecisionMap);
double cJaroWinklerHarmonicMean = calculateHarmonicMean(cJaroWinklerPrecision, cJaroWinklerRecall);
double dJaroWinklerAccuracy = calculateAccuracy(dAccuracy.getJaroWinklerCount(), totalRows);
double dJaroWinklerPrecision = calculatePrecision(dJaroWinklerPrecisionAcceptCounter, dJaroWinklerPrecisionRejectCounter);
double dJaroWinklerRecall= calculateRecall(dJaroWinklerPrecisionAcceptCounter, dJaroWinklerPrecisionMap);
double dJaroWinklerHarmonicMean = calculateHarmonicMean(dJaroWinklerPrecision, dJaroWinklerRecall);
double aSortedJaroWinklerAccuracy = calculateAccuracy(aAccuracy.getJaroWinklerSortedCount(), totalRows);
double aSortedJaroWinklerPrecision = calculatePrecision(aSortedJaroWinklerPrecisionAcceptCounter, aSortedJaroWinklerPrecisionRejectCounter);
double aSortedJaroWinklerRecall= calculateRecall(aSortedJaroWinklerPrecisionAcceptCounter, aSortedJaroWinklerPrecisionMap);
double aSortedJaroWinklerHarmonicMean = calculateHarmonicMean(aSortedJaroWinklerPrecision, aSortedJaroWinklerRecall);
double bSortedJaroWinklerAccuracy = calculateAccuracy(bAccuracy.getJaroWinklerSortedCount(), totalRows);
double bSortedJaroWinklerPrecision = calculatePrecision(bSortedJaroWinklerPrecisionAcceptCounter, bSortedJaroWinklerPrecisionRejectCounter);
double bSortedJaroWinklerRecall= calculateRecall(bSortedJaroWinklerPrecisionAcceptCounter, bSortedJaroWinklerPrecisionMap);
double bSortedJaroWinklerHarmonicMean = calculateHarmonicMean(bSortedJaroWinklerPrecision, bSortedJaroWinklerRecall);
double cSortedJaroWinklerAccuracy = calculateAccuracy(cAccuracy.getJaroWinklerSortedCount(), totalRows);
double cSortedJaroWinklerPrecision = calculatePrecision(cSortedJaroWinklerPrecisionAcceptCounter, cSortedJaroWinklerPrecisionRejectCounter);
double cSortedJaroWinklerRecall= calculateRecall(cSortedJaroWinklerPrecisionAcceptCounter, cSortedJaroWinklerPrecisionMap);
double cSortedJaroWinklerHarmonicMean = calculateHarmonicMean(cSortedJaroWinklerPrecision, cSortedJaroWinklerRecall);
double dSortedJaroWinklerAccuracy = calculateAccuracy(dAccuracy.getJaroWinklerSortedCount(), totalRows);
double dSortedJaroWinklerPrecision = calculatePrecision(dSortedJaroWinklerPrecisionAcceptCounter, dSortedJaroWinklerPrecisionRejectCounter);
double dSortedJaroWinklerRecall= calculateRecall(dSortedJaroWinklerPrecisionAcceptCounter, dSortedJaroWinklerPrecisionMap);
double dSortedJaroWinklerHarmonicMean = calculateHarmonicMean(dSortedJaroWinklerPrecision, dSortedJaroWinklerRecall);
String aScores = scores("a", threshold, aLevenAccuracy, aLevenPrecision, aLevenRecall, aLevenHarmonicMean,
aNGramAccuracy, aNGramPrecision, aNGramRecall, aNGramHarmonicMean,
aCosineAccuracy, aCosinePrecision, aCosineRecall, aCosineHarmonicMean,
aLqsAccuracy, aLqsPrecision, aLqsRecall, aLqsHarmonicMean, aJaccardAccuracy,
aJaccardPrecision, aJaccardRecall, aJaccardHarmonicMean, aJaroAccuracy,
aJaroPrecision, aJaroRecall, aJaroHarmonicMean, aJaroWinklerAccuracy,
aJaroWinklerPrecision, aJaroWinklerRecall, aJaroWinklerHarmonicMean,
aSortedJaroWinklerAccuracy, aSortedJaroWinklerPrecision,
aSortedJaroWinklerRecall, aSortedJaroWinklerHarmonicMean);
writer.append(aScores);
writer.newLine();
String bScores = scores("b", threshold, bLevenAccuracy, bLevenPrecision, bLevenRecall,
bLevenHarmonicMean, bNGramAccuracy, bNGramPrecision, bNGramRecall,
bNGramHarmonicMean, bCosineAccuracy, bCosinePrecision, bCosineRecall,
bCosineHarmonicMean, bLqsAccuracy, bLqsPrecision, bLqsRecall, bLqsHarmonicMean,
bJaccardAccuracy, bJaccardPrecision, bJaccardRecall, bJaccardHarmonicMean,
bJaroAccuracy, bJaroPrecision, bJaroRecall, bJaroHarmonicMean, bJaroWinklerAccuracy,
bJaroWinklerPrecision, bJaroWinklerRecall, bJaroWinklerHarmonicMean,
bSortedJaroWinklerAccuracy, bSortedJaroWinklerPrecision, bSortedJaroWinklerRecall,
bSortedJaroWinklerHarmonicMean);
writer.append(bScores);
writer.newLine();
//exclude c scores
// String cScores = scores("c", threshold, cLevenAccuracy, cLevenPrecision, cLevenRecall, cLevenHarmonicMean,
// cNGramAccuracy, cNGramPrecision, cNGramRecall, cNGramHarmonicMean, cCosineAccuracy,
// cCosinePrecision, cCosineRecall, cCosineHarmonicMean, cLqsAccuracy, cLqsPrecision,
// cLqsRecall, cLqsHarmonicMean, cJaccardAccuracy, cJaccardPrecision, cJaccardRecall,
// cJaccardHarmonicMean, cJaroAccuracy, cJaroPrecision, cJaroRecall, cJaroHarmonicMean,
// cJaroWinklerAccuracy, cJaroWinklerPrecision, cJaroWinklerRecall, cJaroWinklerHarmonicMean,
// cSortedJaroWinklerAccuracy, cSortedJaroWinklerPrecision, cSortedJaroWinklerRecall,
// cSortedJaroWinklerHarmonicMean);
//
//
//
// writer.append(cScores);
// writer.newLine();
String dScores = scores("d", threshold, dLevenAccuracy, dLevenPrecision, dLevenRecall, dLevenHarmonicMean,
dNGramAccuracy, dNGramPrecision, dNGramRecall, dNGramHarmonicMean, dCosineAccuracy,
dCosinePrecision, dCosineRecall, dCosineHarmonicMean, dLqsAccuracy, dLqsPrecision,
dLqsRecall, dLqsHarmonicMean, dJaccardAccuracy, dJaccardPrecision, dJaccardRecall,
dJaccardHarmonicMean, dJaroAccuracy, dJaroPrecision, dJaroRecall, dJaroHarmonicMean,
dJaroWinklerAccuracy, dJaroWinklerPrecision, dJaroWinklerRecall, dJaroWinklerHarmonicMean,
dSortedJaroWinklerAccuracy, dSortedJaroWinklerPrecision, dSortedJaroWinklerRecall,
dSortedJaroWinklerHarmonicMean);
writer.append(dScores);
writer.newLine();
writer.newLine();
writer.newLine();
writer.newLine();
} catch(IOException | RuntimeException ex){
writer.close();
throw new ApplicationException(ex.getMessage());
}
}
private void executeOriginalSet(int l, BufferedReader br, String cvsSplitBy, Locale locale, double threshold,
Accuracy aAccuracy, Accuracy bAccuracy, Accuracy cAccuracy, Accuracy dAccuracy) throws IOException {
String line;
l = 0;
while ((line = br.readLine()) != null) {
//skip first line of csv
if (l < 1) {
l++;
continue;
}
// use comma as separator
String[] spl = line.split(cvsSplitBy);
//StringBuffer sb = new StringBuffer("");
if (spl.length < 22) {
continue;
}
String idA = spl[0];
String idB = spl[1];
//String distanceMeters = spl[2];
String nameA = spl[3];
String nameB = spl[4];
//String nameFusionAction = spl[5];
// String streetA = spl[6];
// String streetB = spl[7];
// //String streetFusionAction = spl[8];
//
// String streetNumberA = spl[9];
// String streetNumberB = spl[10];
//
// String phoneA = spl[11];
// String phoneB = spl[12];
// //String phoneFusionAction = spl[13];
//
// String emailA = spl[14];
// String emailB = spl[15];
// //String emailFusionAction = spl[16];
//
// String websiteA = spl[17];
// String websiteB = spl[18];
//String websiteFusionAction = spl[19];
//String score = spl[20];
//String names1 = spl[21];
String acceptance = spl[22];
computePairOutputResult(nameA, nameB, locale, acceptance, threshold,
aAccuracy, bAccuracy, cAccuracy, dAccuracy);
l++;
}
}
private void executeBalancedSet(int l, BufferedReader br, String cvsSplitBy, Locale locale, double threshold,
Accuracy aAccuracy, Accuracy bAccuracy, Accuracy cAccuracy, Accuracy dAccuracy) throws IOException {
List<Record> records = new ArrayList<>();
String line;
l = 0;
while ((line = br.readLine()) != null) {
//skip first line of csv
if (l < 1) {
l++;
continue;
}
// use comma as separator
String[] spl = line.split(cvsSplitBy);
//StringBuffer sb = new StringBuffer("");
if (spl.length < 22) {
continue;
}
String nameA = spl[3];
String nameB = spl[4];
String acceptance = spl[22];
Record record = new Record();
record.setKey(l);
record.setNameA(nameA);
record.setNameB(nameB);
record.setAcceptance(acceptance);
records.add(record);
l++;
}
//balance the record list
int acceptCount = getAcceptCount(records);
int rejectCount = getRejectCount(records);
List<Record> balanced = new ArrayList<>();
List<Record> accepts = new ArrayList<>();
List<Record> rejects = new ArrayList<>();
long seed = 123456;
if(acceptCount > rejectCount){
int diff = acceptCount - rejectCount;
for(Record record : records){
if(record.getAcceptance().equals(ACCEPT)){
accepts.add(record);
} else if(record.getAcceptance().equals(REJECT)){
rejects.add(record);
} else {
throw new ApplicationException("Wrong acceptance value: " + record.getAcceptance());
}
}
Collections.shuffle(accepts, new Random(seed));
accepts = accepts.subList(diff, accepts.size());
balanced.addAll(accepts);
balanced.addAll(rejects);
} else if(acceptCount < rejectCount){
int diff = rejectCount - acceptCount;
for(Record record : records){
if(record.getAcceptance().equals(ACCEPT)){
accepts.add(record);
} else if(record.getAcceptance().equals(REJECT)){
rejects.add(record);
} else {
throw new ApplicationException("Wrong acceptance value: " + record.getAcceptance());
}
}
Collections.shuffle(rejects, new Random(seed));
rejects = rejects.subList(diff, rejects.size());
balanced.addAll(accepts);
balanced.addAll(rejects);
}
//compute using balanced
for (Record record : balanced) {
computePairOutputResult(record.getNameA(), record.getNameB(), locale, record.getAcceptance(), threshold,
aAccuracy, bAccuracy, cAccuracy, dAccuracy);
l++;
}
}
private int getAcceptCount(List<Record> records){
int count = 0;
for(Record record : records){
if(record.getAcceptance().equals(ACCEPT)){
count++;
}
}
return count;
}
private int getRejectCount(List<Record> records){
int count = 0;
for(Record record : records){
if(record.getAcceptance().equals(REJECT)){
count++;
}
}
return count;
}
private String scores(String ind, double threshold, double aLevenAccuracy, double aLevenPrecision, double aLevenRecall,
double aLevenHarmonicMean, double aNGramAccuracy, double aNGramPrecision, double aNGramRecall,
double aNGramHarmonicMean, double aCosineAccuracy, double aCosinePrecision, double aCosineRecall,
double aCosineHarmonicMean, double aLqsAccuracy, double aLqsPrecision, double aLqsRecall,
double aLqsHarmonicMean, double aJaccardAccuracy, double aJaccardPrecision, double aJaccardRecall,
double aJaccardHarmonicMean, double aJaroAccuracy, double aJaroPrecision, double aJaroRecall,
double aJaroHarmonicMean, double aJaroWinklerAccuracy, double aJaroWinklerPrecision,
double aJaroWinklerRecall, double aJaroWinklerHarmonicMean, double aSortedJaroWinklerAccuracy,
double aSortedJaroWinklerPrecision, double aSortedJaroWinklerRecall, double aSortedJaroWinklerHarmonicMean) {
String scores = "Total: " + totalRows
+ "\nMetric_Threshold " + threshold + SEP + "Accuracy" + SEP +"Precision"+ SEP + "Recall" + SEP + "harmonicMean"
+ " \nLevenstein_" + ind + threshold + SEP + aLevenAccuracy + SEP + aLevenPrecision + SEP + aLevenRecall + SEP + aLevenHarmonicMean
+ " \n2Gram_" + ind + threshold + SEP + aNGramAccuracy + SEP + aNGramPrecision + SEP + aNGramRecall + SEP + aNGramHarmonicMean
//+ " \nCosine_" + ind + threshold + SEP + aCosineAccuracy + SEP + aCosinePrecision + SEP + aCosineRecall + SEP + aCosineHarmonicMean
+ " \nLongestCommonSubseq_" + ind + threshold + SEP + aLqsAccuracy + SEP + aLqsPrecision + SEP + aLqsRecall + SEP + aLqsHarmonicMean
//+ " \nJaccard_" + ind + threshold + SEP + aJaccardAccuracy + SEP + aJaccardPrecision + SEP + aJaccardRecall + SEP + aJaccardHarmonicMean
+ " \nJaro_" + ind + threshold + SEP + aJaroAccuracy + SEP + aJaroPrecision + SEP + aJaroRecall + SEP + aJaroHarmonicMean
+ " \nJaroWinkler_" + ind + threshold + SEP + aJaroWinklerAccuracy + SEP + aJaroWinklerPrecision + SEP + aJaroWinklerRecall + SEP + aJaroWinklerHarmonicMean;
//+ " \nSortedJaroWinkler_" + ind + threshold + SEP + aSortedJaroWinklerAccuracy + SEP + aSortedJaroWinklerPrecision + SEP + aSortedJaroWinklerRecall + SEP + aSortedJaroWinklerHarmonicMean;
return scores;
}
private void computePairOutputResult(String valueA, String valueB,
Locale locale, String acceptance, double threshold, Accuracy aAccuracy,
Accuracy bAccuracy, Accuracy cAccuracy, Accuracy dAccuracy) {
totalRows++;
NormalizedLiteral basicA = getBasicNormalization(valueA, valueB, locale);
NormalizedLiteral basicB = getBasicNormalization(valueB, valueA, locale);
WeightedPairLiteral normalizedPair = getAdvancedNormalization(basicA, basicB, locale);
String basicNormA = basicA.getNormalized();
String basicNormB = basicB.getNormalized();
double aLeven = Levenshtein.computeSimilarity(valueA, valueB, null);
double aNGram = NGram.computeSimilarity(valueA, valueB, 2);
double aCosine = Cosine.computeSimilarity(valueA, valueB);
double aLqs = LongestCommonSubsequenceMetric.computeSimilarity(valueA, valueB);
double aJaccard = Jaccard.computeSimilarity(valueA, valueB);
double aJaro = Jaro.computeSimilarity(valueA, valueB);
double aJaroWinkler = JaroWinkler.computeSimilarity(valueA, valueB);
double aSortedJaroWinkler = SortedJaroWinkler.computeSimilarity(valueA, valueB);
constructPrecisionMap(aLevenPrecisionMap, acceptance, aLeven);
constructPrecisionMap(aNGramPrecisionMap, acceptance, aNGram);
constructPrecisionMap(aCosinePrecisionMap, acceptance, aCosine);
constructPrecisionMap(aLqsPrecisionMap, acceptance, aLqs);
constructPrecisionMap(aJaccardPrecisionMap, acceptance, aJaccard);
constructPrecisionMap(aJaroPrecisionMap, acceptance, aJaro);
constructPrecisionMap(aJaroWinklerPrecisionMap, acceptance, aJaroWinkler);
constructPrecisionMap(aSortedJaroWinklerPrecisionMap, acceptance, aSortedJaroWinkler);
double bLeven = Levenshtein.computeSimilarity(basicNormA, basicNormB, null);
double bNGram = NGram.computeSimilarity(basicNormA, basicNormB, 2);
double bCosine = Cosine.computeSimilarity(basicNormA, basicNormB);
double bLqs = LongestCommonSubsequenceMetric.computeSimilarity(basicNormA, basicNormB);
double bJaccard = Jaccard.computeSimilarity(basicNormA, basicNormB);
double bJaro = Jaro.computeSimilarity(basicNormA, basicNormB);
double bJaroWinkler = JaroWinkler.computeSimilarity(basicNormA, basicNormB);
double bSortedJaroWinkler = SortedJaroWinkler.computeSimilarity(basicNormA, basicNormB);
constructPrecisionMap(bLevenPrecisionMap, acceptance, bLeven);
constructPrecisionMap(bNGramPrecisionMap, acceptance, bNGram);
constructPrecisionMap(bCosinePrecisionMap, acceptance, bCosine);
constructPrecisionMap(bLqsPrecisionMap, acceptance, bLqs);
constructPrecisionMap(bJaccardPrecisionMap, acceptance, bJaccard);
constructPrecisionMap(bJaroPrecisionMap, acceptance, bJaro);
constructPrecisionMap(bJaroWinklerPrecisionMap, acceptance, bJaroWinkler);
constructPrecisionMap(bSortedJaroWinklerPrecisionMap, acceptance, bSortedJaroWinkler);
double cLeven = WeightedSimilarity.computeCSimilarity(normalizedPair, SpecificationConstants.Similarity.LEVENSHTEIN);
double cNGram = WeightedSimilarity.computeCSimilarity(normalizedPair, SpecificationConstants.Similarity.GRAM_2);
double cCosine = WeightedSimilarity.computeCSimilarity(normalizedPair, SpecificationConstants.Similarity.COSINE);
double cLqs = WeightedSimilarity.computeCSimilarity(normalizedPair, SpecificationConstants.Similarity.LCS);
double cJaccard = WeightedSimilarity.computeCSimilarity(normalizedPair, SpecificationConstants.Similarity.JACCARD);
double cJaro = WeightedSimilarity.computeCSimilarity(normalizedPair, SpecificationConstants.Similarity.JARO);
double cJaroWinkler = WeightedSimilarity.computeCSimilarity(normalizedPair, SpecificationConstants.Similarity.JARO_WINKLER);
double cSortedJaroWinkler = WeightedSimilarity.computeCSimilarity(normalizedPair, SpecificationConstants.Similarity.SORTED_JARO_WINKLER);
constructPrecisionMap(cLevenPrecisionMap, acceptance, cLeven);
constructPrecisionMap(cNGramPrecisionMap, acceptance, cNGram);
constructPrecisionMap(cCosinePrecisionMap, acceptance, cCosine);
constructPrecisionMap(cLqsPrecisionMap, acceptance, cLqs);
constructPrecisionMap(cJaccardPrecisionMap, acceptance, cJaccard);
constructPrecisionMap(cJaroPrecisionMap, acceptance, cJaro);
constructPrecisionMap(cJaroWinklerPrecisionMap, acceptance, cJaroWinkler);
constructPrecisionMap(cSortedJaroWinklerPrecisionMap, acceptance, cSortedJaroWinkler);
double dLeven = WeightedSimilarity.computeDSimilarity(normalizedPair, SpecificationConstants.Similarity.LEVENSHTEIN);
double dNGram = WeightedSimilarity.computeDSimilarity(normalizedPair, SpecificationConstants.Similarity.GRAM_2);
double dCosine = WeightedSimilarity.computeDSimilarity(normalizedPair, SpecificationConstants.Similarity.COSINE);
double dLqs = WeightedSimilarity.computeDSimilarity(normalizedPair, SpecificationConstants.Similarity.LCS);
double dJaccard = WeightedSimilarity.computeDSimilarity(normalizedPair, SpecificationConstants.Similarity.JACCARD);
double dJaro = WeightedSimilarity.computeDSimilarity(normalizedPair, SpecificationConstants.Similarity.JARO);
double dJaroWinkler = WeightedSimilarity.computeDSimilarity(normalizedPair, SpecificationConstants.Similarity.JARO_WINKLER);
double dSortedJaroWinkler = WeightedSimilarity.computeDSimilarity(normalizedPair, SpecificationConstants.Similarity.SORTED_JARO_WINKLER);
constructPrecisionMap(dLevenPrecisionMap, acceptance, dLeven);
constructPrecisionMap(dNGramPrecisionMap, acceptance, dNGram);
constructPrecisionMap(dCosinePrecisionMap, acceptance, dCosine);
constructPrecisionMap(dLqsPrecisionMap, acceptance, dLqs);
constructPrecisionMap(dJaccardPrecisionMap, acceptance, dJaccard);
constructPrecisionMap(dJaroPrecisionMap, acceptance, dJaro);
constructPrecisionMap(dJaroWinklerPrecisionMap, acceptance, dJaroWinkler);
constructPrecisionMap(dSortedJaroWinklerPrecisionMap, acceptance, dSortedJaroWinkler);
//a
if((aLeven >= threshold && acceptance.equals(ACCEPT)) || aLeven < threshold && acceptance.equals(REJECT)){
aAccuracy.setLevenshteinCount(aAccuracy.getLevenshteinCount() + 1);
}
if((aNGram >= threshold && acceptance.equals(ACCEPT)) || aNGram < threshold && acceptance.equals(REJECT)){
aAccuracy.setNgram2Count(aAccuracy.getNgram2Count() + 1);
}
if((aCosine >= threshold && acceptance.equals(ACCEPT)) || aCosine < threshold && acceptance.equals(REJECT)){
aAccuracy.setCosineCount(aAccuracy.getCosineCount() + 1);
}
if((aLqs >= threshold && acceptance.equals(ACCEPT)) || aLqs < threshold && acceptance.equals(REJECT)){
aAccuracy.setLqsCount(aAccuracy.getLqsCount() + 1);
}
if((aJaccard >= threshold && acceptance.equals(ACCEPT)) || aJaccard < threshold && acceptance.equals(REJECT)){
aAccuracy.setJaccardCount(aAccuracy.getJaccardCount() + 1);
}
if((aJaro >= threshold && acceptance.equals(ACCEPT)) || aJaro < threshold && acceptance.equals(REJECT)){
aAccuracy.setJaroCount(aAccuracy.getJaroCount() + 1);
}
if((aJaroWinkler >= threshold && acceptance.equals(ACCEPT)) || aJaroWinkler < threshold && acceptance.equals(REJECT)){
aAccuracy.setJaroWinklerCount(aAccuracy.getJaroWinklerCount() + 1);
}
if((aSortedJaroWinkler >= threshold && acceptance.equals(ACCEPT)) || aSortedJaroWinkler < threshold && acceptance.equals(REJECT)){
aAccuracy.setJaroWinklerSortedCount(aAccuracy.getJaroWinklerSortedCount() + 1);
}
//b norm
if((bLeven >= threshold && acceptance.equals(ACCEPT)) || bLeven < threshold && acceptance.equals(REJECT)){
bAccuracy.setLevenshteinCount(bAccuracy.getLevenshteinCount() + 1);
}
if((bNGram >= threshold && acceptance.equals(ACCEPT)) || bNGram < threshold && acceptance.equals(REJECT)){
bAccuracy.setNgram2Count(bAccuracy.getNgram2Count() + 1);
}
if((bCosine >= threshold && acceptance.equals(ACCEPT)) || bCosine < threshold && acceptance.equals(REJECT)){
bAccuracy.setCosineCount(bAccuracy.getCosineCount() + 1);
}
if((bLqs >= threshold && acceptance.equals(ACCEPT)) || bLqs < threshold && acceptance.equals(REJECT)){
bAccuracy.setLqsCount(bAccuracy.getLqsCount() + 1);
}
if((bJaccard >= threshold && acceptance.equals(ACCEPT)) || bJaccard < threshold && acceptance.equals(REJECT)){
bAccuracy.setJaccardCount(bAccuracy.getJaccardCount() + 1);
}
if((bJaro >= threshold && acceptance.equals(ACCEPT)) || bJaro < threshold && acceptance.equals(REJECT)){
bAccuracy.setJaroCount(bAccuracy.getJaroCount() + 1);
}
if((bJaroWinkler >= threshold && acceptance.equals(ACCEPT)) || bJaroWinkler < threshold && acceptance.equals(REJECT)){
bAccuracy.setJaroWinklerCount(bAccuracy.getJaroWinklerCount() + 1);
}
if((bSortedJaroWinkler >= threshold && acceptance.equals(ACCEPT)) || bSortedJaroWinkler < threshold && acceptance.equals(REJECT)){
bAccuracy.setJaroWinklerSortedCount(bAccuracy.getJaroWinklerSortedCount() + 1);
}
//c norm
if((cLeven >= threshold && acceptance.equals(ACCEPT)) || cLeven < threshold && acceptance.equals(REJECT)){
cAccuracy.setLevenshteinCount(cAccuracy.getLevenshteinCount() + 1);
}
if((cNGram >= threshold && acceptance.equals(ACCEPT)) || cNGram < threshold && acceptance.equals(REJECT)){
cAccuracy.setNgram2Count(cAccuracy.getNgram2Count() + 1);
}
if((cCosine >= threshold && acceptance.equals(ACCEPT)) || cCosine < threshold && acceptance.equals(REJECT)){
cAccuracy.setCosineCount(cAccuracy.getCosineCount() + 1);
}
if((cLqs >= threshold && acceptance.equals(ACCEPT)) || cLqs < threshold && acceptance.equals(REJECT)){
cAccuracy.setLqsCount(cAccuracy.getLqsCount() + 1);
}
if((cJaccard >= threshold && acceptance.equals(ACCEPT)) || cJaccard < threshold && acceptance.equals(REJECT)){
cAccuracy.setJaccardCount(cAccuracy.getJaccardCount() + 1);
}
if((cJaro >= threshold && acceptance.equals(ACCEPT)) || cJaro < threshold && acceptance.equals(REJECT)){
cAccuracy.setJaroCount(cAccuracy.getJaroCount() + 1);
}
if((cJaroWinkler >= threshold && acceptance.equals(ACCEPT)) || cJaroWinkler < threshold && acceptance.equals(REJECT)){
cAccuracy.setJaroWinklerCount(cAccuracy.getJaroWinklerCount() + 1);
}
if((cSortedJaroWinkler >= threshold && acceptance.equals(ACCEPT)) || cSortedJaroWinkler < threshold && acceptance.equals(REJECT)){
cAccuracy.setJaroWinklerSortedCount(cAccuracy.getJaroWinklerSortedCount() + 1);
}
//d norm
if((dLeven >= threshold && acceptance.equals(ACCEPT)) || dLeven < threshold && acceptance.equals(REJECT)){
dAccuracy.setLevenshteinCount(dAccuracy.getLevenshteinCount() + 1);
}
if((dNGram >= threshold && acceptance.equals(ACCEPT)) || dNGram < threshold && acceptance.equals(REJECT)){
dAccuracy.setNgram2Count(dAccuracy.getNgram2Count() + 1);
}
if((dCosine >= threshold && acceptance.equals(ACCEPT)) || dCosine < threshold && acceptance.equals(REJECT)){
dAccuracy.setCosineCount(dAccuracy.getCosineCount() + 1);
}
if((dLqs >= threshold && acceptance.equals(ACCEPT)) || dLqs < threshold && acceptance.equals(REJECT)){
dAccuracy.setLqsCount(dAccuracy.getLqsCount() + 1);
}
if((dJaccard >= threshold && acceptance.equals(ACCEPT)) || dJaccard < threshold && acceptance.equals(REJECT)){
dAccuracy.setJaccardCount(dAccuracy.getJaccardCount() + 1);
}
if((dJaro >= threshold && acceptance.equals(ACCEPT)) || dJaro < threshold && acceptance.equals(REJECT)){
dAccuracy.setJaroCount(dAccuracy.getJaroCount() + 1);
}
if((dJaroWinkler >= threshold && acceptance.equals(ACCEPT)) || dJaroWinkler < threshold && acceptance.equals(REJECT)){
dAccuracy.setJaroWinklerCount(dAccuracy.getJaroWinklerCount() + 1);
}
if((dSortedJaroWinkler >= threshold && acceptance.equals(ACCEPT)) || dSortedJaroWinkler < threshold && acceptance.equals(REJECT)){
dAccuracy.setJaroWinklerSortedCount(dAccuracy.getJaroWinklerSortedCount() + 1);
}
//find best accuracy in order to set optimal threshold
int maxAccuracyLeven = getMaxAccuracy(aAccuracy.getLevenshteinCount(),
bAccuracy.getLevenshteinCount(), cAccuracy.getLevenshteinCount(), dAccuracy.getLevenshteinCount());
int maxAccuracyNGram = getMaxAccuracy(aAccuracy.getNgram2Count(),
bAccuracy.getNgram2Count(), cAccuracy.getNgram2Count(), dAccuracy.getNgram2Count());
int maxAccuracyCosine = getMaxAccuracy(aAccuracy.getCosineCount(),
bAccuracy.getCosineCount(), cAccuracy.getCosineCount(), dAccuracy.getCosineCount());
int maxAccuracyLqs = getMaxAccuracy(aAccuracy.getLqsCount(),
bAccuracy.getLqsCount(), cAccuracy.getLqsCount(), dAccuracy.getLqsCount());
int maxAccuracyJaccard = getMaxAccuracy(aAccuracy.getJaccardCount(),
bAccuracy.getJaccardCount(), cAccuracy.getJaccardCount(), dAccuracy.getJaccardCount());
int maxAccuracyJaro = getMaxAccuracy(aAccuracy.getJaroCount(),
bAccuracy.getJaroCount(), cAccuracy.getJaroCount(), dAccuracy.getJaroCount());
int maxAccuracyJaroWinkler = getMaxAccuracy(aAccuracy.getJaroWinklerCount(),
bAccuracy.getJaroWinklerCount(), cAccuracy.getJaroWinklerCount(), dAccuracy.getJaroWinklerCount());
int maxAccuracySortedJaroWinkler = getMaxAccuracy(aAccuracy.getJaroWinklerSortedCount(),
bAccuracy.getJaroWinklerSortedCount(), cAccuracy.getJaroWinklerSortedCount(), dAccuracy.getJaroWinklerSortedCount());
if(maxAccuracyLeven > optimalAccuracy.getLevenshteinCount()){
optimalAccuracy.setLevenshteinCount(maxAccuracyLeven);
optimalThreshold.setLevenshtein(threshold);
}
if(maxAccuracyNGram > optimalAccuracy.getNgram2Count()){
optimalAccuracy.setNgram2Count(maxAccuracyNGram);
optimalThreshold.setNgram2(threshold);
}
if(maxAccuracyCosine > optimalAccuracy.getCosineCount()){
optimalAccuracy.setCosineCount(maxAccuracyCosine);
optimalThreshold.setCosine(threshold);
}
if(maxAccuracyLqs > optimalAccuracy.getLqsCount()){
optimalAccuracy.setLqsCount(maxAccuracyLqs);
optimalThreshold.setLqs(threshold);
}
if(maxAccuracyJaccard > optimalAccuracy.getJaccardCount()){
optimalAccuracy.setJaccardCount(maxAccuracyJaccard);
optimalThreshold.setJaccard(threshold);
}
if(maxAccuracyJaro > optimalAccuracy.getJaroCount()){
optimalAccuracy.setJaroCount(maxAccuracyJaro);
optimalThreshold.setJaro(threshold);
}
if(maxAccuracyJaroWinkler > optimalAccuracy.getJaroWinklerCount()){
optimalAccuracy.setJaroWinklerCount(maxAccuracyJaroWinkler);
optimalThreshold.setJaroWinkler(threshold);
}
if(maxAccuracySortedJaroWinkler > optimalAccuracy.getJaroWinklerSortedCount()){
optimalAccuracy.setJaroWinklerSortedCount(maxAccuracySortedJaroWinkler);
optimalThreshold.setSortedJaroWinkler(threshold);
}
}
private NormalizedLiteral getBasicNormalization(String literalA, String literalB, Locale locale) {
BasicGenericNormalizer bgn = new BasicGenericNormalizer();
NormalizedLiteral normalizedLiteral = bgn.getNormalizedLiteral(literalA, literalB, locale);
return normalizedLiteral;
}
private WeightedPairLiteral getAdvancedNormalization(NormalizedLiteral normA, NormalizedLiteral normB, Locale locale) {
AdvancedGenericNormalizer agn = new AdvancedGenericNormalizer();
WeightedPairLiteral weightedPairLiteral = agn.getWeightedPair(normA, normB, locale);
return weightedPairLiteral;
}
private void constructPrecisionMap(Map<String, List<Double>> precisionMap, String acceptance, double similarity) {
if(acceptance.equals(ACCEPT)){
precisionMap.get(ACCEPT).add(similarity);
} else if(acceptance.equals(REJECT)){
precisionMap.get(REJECT).add(similarity);
} else {
throw new ApplicationException("Wrong acceptance value: " + acceptance);
}
}
private void clearPrecisionMapLists(Map<String, List<Double>> precisionMap){
precisionMap.get(ACCEPT).clear();
precisionMap.get(REJECT).clear();
}
private double calculateAccuracy(int count, int rows) {
if(rows == 0){
LOG.warn("Could not calculate accuracy. No rows found.");
return 0;
} else {
return roundHalfUp(count / (double)rows);
}
}
private double calculatePrecision(int acceptCounter, int rejectCounter) {
double result;
if(acceptCounter == 0 && rejectCounter == 0){
result = 0;
} else {
result = roundHalfUp(acceptCounter / (double)(acceptCounter + rejectCounter));
}
return result;
}
private double calculateRecall(int acceptCounter, Map<String, List<Double>> precisionMap) {
double result;
if(acceptCounter == 0){
result = 0;
} else {
result = roundHalfUp(acceptCounter / (double) precisionMap.get(ACCEPT).size());
}
return result;
}
private double calculateHarmonicMean(double precision, double recall) {
double result;
if(precision == 0 || recall == 0){
result = 0;
} else {
result = roundHalfUp(2 * precision * recall / (double)(precision + recall));
}
return result;
}
private double roundHalfUp(double d){
return new BigDecimal(d).setScale(SpecificationConstants.Similarity.ROUND_DECIMALS_3, RoundingMode.HALF_UP).doubleValue();
}
private int count(List<Double> accepted, double threshold) {
int counter = 0;
for(Double elem : accepted){
if(elem >= threshold){
counter++;
}
}
return counter;
}
private int getMaxAccuracy(int aAccuracy, int bAccuracy, int cAccuracy, int dAccuracy) {
return Math.max(Math.max(Math.max(aAccuracy,bAccuracy),cAccuracy), dAccuracy);
}
}
|
package com.twirling.audio.player;
/*
** OpenMXPlayer - Freeware audio player library for Android
** Copyright (C) 2009 - 2014 Radu Motisan, radu.motisan@gmail.com
**
** This file is a part of "OpenMXPlayer" open source library.
**
** OpenMXPlayer 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; either version 3 of the License,
** or (at your option) any later version.
**
** 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 Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
public class PlayerStates {
/**
* Playing state which can either be stopped, playing, or reading the header before playing
*/
public static final int READY_TO_PLAY = 2;
public static final int PLAYING = 3;
public static final int STOPPED = 4;
public int playerState = STOPPED;
public int get() {
return playerState;
}
public void set(int state) {
playerState = state;
}
/**
* Checks whether the player is ready to play, this is the state used also for Pause (phase 2)
*
* @return <code>true</code> if ready, <code>false</code> otherwise
*/
public synchronized boolean isReadyToPlay() {
return playerState == com.twirling.audio.player.PlayerStates.READY_TO_PLAY;
}
/**
* Checks whether the player is currently playing (phase 3)
*
* @return <code>true</code> if playing, <code>false</code> otherwise
*/
public synchronized boolean isPlaying() {
return playerState == com.twirling.audio.player.PlayerStates.PLAYING;
}
/**
* Checks whether the player is currently stopped (not playing)
*
* @return <code>true</code> if playing, <code>false</code> otherwise
*/
public synchronized boolean isStopped() {
return playerState == com.twirling.audio.player.PlayerStates.STOPPED;
}
}
|
package pers.pbyang.entity;
public class Trade {
private int id;
private String country;
private String daoYear;
private String daoMonth;
private String daoDay;
private String number;
private String chuanXing;
private String danWei;
private String huoNum;
private String liPort;
private String zhPort;
private String daoPort;
private String afterPort;
private String liNum;
private String daoNum;
private String liYear;
private String liMonth;
private String liDay;
private String junNum;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getDaoYear() {
return daoYear;
}
public void setDaoYear(String daoYear) {
this.daoYear = daoYear;
}
public String getDaoMonth() {
return daoMonth;
}
public void setDaoMonth(String daoMonth) {
this.daoMonth = daoMonth;
}
public String getDaoDay() {
return daoDay;
}
public void setDaoDay(String daoDay) {
this.daoDay = daoDay;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getChuanXing() {
return chuanXing;
}
public void setChuanXing(String chuanXing) {
this.chuanXing = chuanXing;
}
public String getDanWei() {
return danWei;
}
public void setDanWei(String danWei) {
this.danWei = danWei;
}
public String getHuoNum() {
return huoNum;
}
public void setHuoNum(String huoNum) {
this.huoNum = huoNum;
}
public String getLiPort() {
return liPort;
}
public void setLiPort(String liPort) {
this.liPort = liPort;
}
public String getZhPort() {
return zhPort;
}
public void setZhPort(String zhPort) {
this.zhPort = zhPort;
}
public String getDaoPort() {
return daoPort;
}
public void setDaoPort(String daoPort) {
this.daoPort = daoPort;
}
public String getAfterPort() {
return afterPort;
}
public void setAfterPort(String afterPort) {
this.afterPort = afterPort;
}
public String getDaoNum() {
return daoNum;
}
public void setDaoNum(String daoNum) {
this.daoNum = daoNum;
}
public String getLiYear() {
return liYear;
}
public void setLiYear(String liYear) {
this.liYear = liYear;
}
public String getLiMonth() {
return liMonth;
}
public void setLiMonth(String liMonth) {
this.liMonth = liMonth;
}
public String getLiDay() {
return liDay;
}
public void setLiDay(String liDay) {
this.liDay = liDay;
}
public String getJunNum() {
return junNum;
}
public void setJunNum(String junNum) {
this.junNum = junNum;
}
public String getLiNum() {
return liNum;
}
public void setLiNum(String liNum) {
this.liNum = liNum;
}
}
|
package com.seemoreinteractive.seemoreinteractive.multitouch;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import com.seemoreinteractive.seemoreinteractive.multitouch.MultiTouchController.MultiTouchObjectCanvas;
import com.seemoreinteractive.seemoreinteractive.multitouch.MultiTouchController.PointInfo;
import com.seemoreinteractive.seemoreinteractive.multitouch.MultiTouchController.PositionAndScale;
public class PhotoSortrView extends View implements
MultiTouchObjectCanvas<MultiTouchEntity> {
private ArrayList<MultiTouchEntity> mImages = new ArrayList<MultiTouchEntity>();
private MultiTouchController<MultiTouchEntity> multiTouchController = new MultiTouchController<MultiTouchEntity>(
this);
private PointInfo currTouchPoint = new PointInfo();
private static final int UI_MODE_ROTATE = 1, UI_MODE_ANISOTROPIC_SCALE = 2;
private int mUIMode = UI_MODE_ROTATE;
private static final float SCREEN_MARGIN = 100;
private int displayWidth, displayHeight;
public PhotoSortrView(Context context) {
this(context, null);
}
public PhotoSortrView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PhotoSortrView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
Resources res = context.getResources();
setBackgroundColor(Color.TRANSPARENT);
DisplayMetrics metrics = res.getDisplayMetrics();
this.displayWidth = res.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? Math
.max(metrics.widthPixels, metrics.heightPixels) : Math.min(
metrics.widthPixels, metrics.heightPixels);
this.displayHeight = res.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? Math
.min(metrics.widthPixels, metrics.heightPixels) : Math.max(
metrics.widthPixels, metrics.heightPixels);
}
public void loadImages1(Context context, Drawable d) {
Resources res = context.getResources();
mImages.add(new ImageEntity(d, res));
float cx = SCREEN_MARGIN
+ (float) (Math.random() * (displayWidth - 2 * SCREEN_MARGIN));
float cy = SCREEN_MARGIN
+ (float) (Math.random() * (displayHeight - 2 * SCREEN_MARGIN));
Log.i("cx", ""+cx+" "+cy);
mImages.get(mImages.size() - 1).load(context, cx, cy);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int n = mImages.size();
for (int i = 0; i < n; i++){
mImages.get(i).draw(canvas);
}
}
public void trackballClicked() {
mUIMode = (mUIMode + 1) % 3;
invalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return multiTouchController.onTouchEvent(event);
}
/**
* Get the image that is under the single-touch point, or return null
* (canceling the drag op) if none
*/
@Override
public MultiTouchEntity getDraggableObjectAtPoint(PointInfo pt) {
float x = pt.getX(), y = pt.getY();
int n = mImages.size();
for (int i = n - 1; i >= 0; i--) {
ImageEntity im = (ImageEntity) mImages.get(i);
if (im.containsPoint(x, y))
return im;
}
return null;
}
/**
* Select an object for dragging. Called whenever an object is found to be
* under the point (non-null is returned by getDraggableObjectAtPoint()) and
* a drag operation is starting. Called with null when drag op ends.
*/
@Override
public void selectObject(MultiTouchEntity img, PointInfo touchPoint) {
currTouchPoint.set(touchPoint);
if (img != null) {
// Move image to the top of the stack when selected
mImages.remove(img);
mImages.add(img);
} else {
// Called with img == null when drag stops.
}
invalidate();
}
/**
* Get the current position and scale of the selected image. Called whenever
* a drag starts or is reset.
*/
@Override
public void getPositionAndScale(MultiTouchEntity img,
PositionAndScale objPosAndScaleOut) {
objPosAndScaleOut.set(img.getCenterX(), img.getCenterY(),
(mUIMode & UI_MODE_ANISOTROPIC_SCALE) == 0,
(img.getScaleX() + img.getScaleY()) / 2,
(mUIMode & UI_MODE_ANISOTROPIC_SCALE) != 0, img.getScaleX(),
img.getScaleY(), (mUIMode & UI_MODE_ROTATE) != 0,
img.getAngle());
}
/** Set the position and scale of the dragged/stretched image. */
@Override
public boolean setPositionAndScale(MultiTouchEntity img,
PositionAndScale newImgPosAndScale, PointInfo touchPoint) {
currTouchPoint.set(touchPoint);
boolean ok = ((ImageEntity) img).setPos(newImgPosAndScale);
if (ok)
invalidate();
return ok;
}
@Override
public boolean pointInObjectGrabArea(PointInfo pt, MultiTouchEntity img) {
return false;
}
public void unloadImages(){
mImages = new ArrayList<MultiTouchEntity>();
invalidate();
}
}
|
/*
* Robot Explorer
*
* Stefan-Dobrin Cosmin
* 342C4
*/
package explorer.gui;
import java.awt.Color;
import java.awt.Graphics2D;
import explorer.Cell;
/**
* The Class CellGraphics.
*/
public class CellGraphics extends Cell {
public static final int size = 32;
public static final int padding = 1;
public static final Color knownColor = new Color(0.6f,0.6f,0.6f);
public static final Color visibleColor = new Color(0.87f,0.88f,0.97f);
public static final Color hiddenColor = Color.GRAY.darker();
public static final Color emptyColor = new Color(0.2f, 0.5f, 0.4f);
public static final Color trapColor = Color.ORANGE;
public static final Color wallColor = Color.RED;
public static final Color wallBackColor = new Color(0.3f,0.3f,0.3f);
public static final Color goalColor = Color.MAGENTA;
public static final Color exitColor = Color.BLUE;
public static final Color currentPositionColor = Color.CYAN;
public static final Color currentTargetColor = new Color(0.95f,0.7f,0.7f);
public static final Color enemyColor = Color.RED;
public static final Color deadColor = Color.GREEN.darker().darker();
public static int minXCell = 0;
public static int minYCell = 0;
public static int maxYCell = 0;
/**
* Instantiates a new cell graphics.
*
* @param x the x
* @param y the y
* @param type the type
*/
public CellGraphics(int x, int y, Type type) {
super(x, y, type);
}
/**
* Draw the cell.
*
* @param g the g
*/
public void draw(Graphics2D g, int mapSkipXCells, int mapSkipYCells)
{
// Calculate which cell this one is (compared to the most left and top
// one)
// Also, skip 1 row and 1 column (padding)
int xCount = this.x - CellGraphics.minXCell + 1 + mapSkipXCells;
int yCount = this.y - CellGraphics.minYCell + 1 + mapSkipYCells;
// Calculate coordinates
int xPos = xCount * (size + padding);
int yPos = yCount * (size + padding);
drawAt(g, yPos, xPos); //swap to consider x as line number and y as column number
}
/**
* Draw the cell at a given position.
*
* @param g the g
* @param xPos the x pos
* @param yPos the y pos
*/
public void drawAt(Graphics2D g, int xPos, int yPos)
{
// Prepare attributes
String text = null;
Color colorText = null;
Color color = null;
int textXPos = xPos + 10;
int textYPos = yPos + 22;
// Color
switch (this.visible)
{
case Known: color=knownColor; break;
case Hidden: color=hiddenColor; break;
case Visible: color=visibleColor; break;
case Current: color=currentPositionColor; break;
case Target: color=currentTargetColor; break;
case Finished: color=deadColor; break;
}
// Text attributes
switch (this.type) {
case Empty:
text = "";
colorText = emptyColor;
break;
case Trap:
textXPos-=6;
text = String.format("%2.1f", probability);
colorText = trapColor;
break;
case Wall:
text = "#";
colorText = wallColor;
color = wallBackColor;
break;
case Clue:
text = "?"+this.hint;
textXPos-=8;
colorText = emptyColor;
break;
case Goal:
text = "G";
colorText = goalColor;
break;
case Exit:
text = "e";
colorText = exitColor;
break;
default:
text = "!";
colorText = Color.RED;
}
if(enemy!=null)
{
text = "X"+enemy;
textXPos-=4;
colorText=enemyColor;
}
// Draw the cell
g.setColor(color);
g.fillRect(xPos, yPos, size, size);
// Draw the text inside
g.setColor(colorText);
g.drawString(text, textXPos, textYPos);
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public CellGraphics clone() {
CellGraphics newCell=new CellGraphics(this.x, this.y, this.type);
newCell.cost=this.cost;
newCell.damage=this.damage;
newCell.hint=this.hint;
newCell.predecessor=null;
newCell.probability=this.probability;
newCell.visible=this.visible;
return newCell;
}
}
|
/**
* Copyright 2013-present febit.org (support@febit.org)
*
* 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 org.febit.arango;
import com.arangodb.ArangoDB;
import com.arangodb.ArangoDatabase;
import java.net.UnknownHostException;
import org.febit.util.Petite;
import static org.testng.Assert.*;
import org.testng.annotations.Test;
/**
*
* @author zqq90
*/
@Test(enabled = false)
public class ArangoDaoTest {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(ArangoDaoTest.class);
protected String host = null;//"localhost";
protected int port = 8529;
protected String user = "arango";
protected String password = "arango";
protected String database = "test";
ArangoDao<Foo> _fooDao;
@Petite.Init
public void init() {
if (host == null) {
return;
}
ArangoDB client = new ArangoDB.Builder()
.host(host, port)
.user(user)
.password(password)
.registerModule(new VPackFebitModule())
.build();
try {
client.createDatabase(database);
} catch (Exception e) {
LOG.warn("", e);
}
ArangoDatabase db = client.db(database);
try {
db.createCollection("Foo");
db.createCollection("app_sys_seq");
} catch (Exception e) {
LOG.warn("", e);
}
_fooDao = new ArangoDao<>(Foo.class, db.collection("Foo"), null);
}
@Test(groups = "ignore")
public void fooTest() {
ArangoDao<Foo> dao = _fooDao;
Foo foo = new Foo();
foo.string = "first";
dao.save(foo);
foo.string = "asdasdas";
foo.i = 1;
dao.update(foo);
foo.string = "aaaa";
foo.i = 2;
foo.bar = new Bar("name2", "detail");
dao.update(foo);
System.out.println();
assertEquals(_fooDao.findXById(foo.getId(), "bar", Bar.class), foo.bar);
foo.string = "bbbb";
foo.i = 3;
foo.bar = new Bar("name3", "detail");
dao.update(foo);
assertEquals(_fooDao.findXById(foo.getId(), "string", String.class), "bbbb");
System.out.println(dao.list(new Condition().in("i", 1, 3, 4, 5).contains("string", "bb"), FooPart.class));
}
@Test(groups = "ignore")
public void seqTest() throws UnknownHostException {
ArangoDatabase db = _fooDao.db();
System.out.println("xxx: " + ArangoUtil.nextSeq(db, "xxx"));
System.out.println("xxx: " + ArangoUtil.nextSeq(db, "xxx"));
System.out.println("yyy: " + ArangoUtil.nextSeq(db, "yyy"));
System.out.println("yyy: " + ArangoUtil.nextSeq(db, "yyy"));
}
}
|
package person.config.datasource;
import lombok.extern.log4j.Log4j;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* Created by wz2063677 on 2017/3/22.
*/
@Log4j
@Configuration
public class DataSourceConfiguration {
@Bean("ds-user")
@ConfigurationProperties(prefix = "app.datasource.user")
public DataSource createUserDataSource(){
log.info("create user ds");
return DataSourceBuilder.create().build();
}
@Bean("ds-app")
@Primary
@ConfigurationProperties(prefix = "app.datasource.app")
public DataSource createAppDataSource(){
log.info("create app ds");
return DataSourceBuilder.create().build();
}
@Bean("ds-dynamic")
public DataSource createDynamicDataSource(){
log.info("create dynamic ds");
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setDefaultTargetDataSource(createAppDataSource());
Map targetDataSources = new HashMap();
targetDataSources.put("ds-user",createUserDataSource());
targetDataSources.put("ds-app",createAppDataSource());
dynamicDataSource.setTargetDataSources(targetDataSources);
return dynamicDataSource;
}
}
|
import java.util.ArrayList;
import java.util.Scanner;
public class CCIBS {
/**
* creates a new scanner called user_input
* prints welcome message
* creates a new player called player_test with attributes "Jacob" and 10000.0
* prints out attributes created in player_test
* creates new RoomGen called roomgen and calls getroom function in RoomGen
* creates a new ActionMenu called action_menu
* @param args
*/
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
System.out.println("Welcome to Crash Course in Brain Surgery");
Player player_test = new Player("The Big Gay", 600.0);
System.out.println(player_test.toStringPlayer());
System.out.println();
RoomGen roomgen = new RoomGen();
roomgen.getroom();
ActionMenu action_menu = new ActionMenu();
/**
* while loop - calls on roomgen to spawn a room, player is placed in the room, room info is printed
*/
while (player_test.position < roomgen.roomlist.size()) {
Room current_room = roomgen.roomlist.get(player_test.position);
System.out.println("--------------");
/**
* while loop - while the spawned room has enemies the player is prompted to choose which enemy to fight and shoot
*/
while (current_room.hasEnemies()) {
int position = action_menu.fight_menu(current_room);
int shoot = action_menu.shoot(current_room, position);
Enemy enemy_we_fight = current_room.enemylist.get(position);
/**
* if player presses 1 to shoot then the player_attack function and the enemy's Attack function will be called
*/
if (shoot == 1) {
player_test.player_attack(enemy_we_fight);
if (enemy_we_fight.enemy_health > 0){
enemy_we_fight.Attack(player_test);
/**
* after player_attack and Attack have ran the enemy's health and player's health will be checked resulting in either an enemy removed or game over for the player
*/
}
if (enemy_we_fight.enemy_health <= 0) {
current_room.enemylist.remove(position);
}
if (player_test.player_health <= 0) {
System.out.print("You Died, Game Over!!!!!");
break;
}
}
}
/**
* if the ArrayList called enemylist within the spawned room is empty then the player is prompted to change rooms
*/
if (current_room.enemylist.isEmpty()){
int input = action_menu.next_room(current_room, roomgen, player_test);
if(input == 1) {
player_test.position += 1;
}
}
/**
* if player's health is less than 0 then the game ends
*/
if (current_room.enemylist.isEmpty()){
int input = action_menu.next_room(current_room, roomgen, player_test);
if(input == 1) {
roomgen.roomlist.remove(player_test.position);
}
}
if (player_test.player_health <= 0) {
System.out.println("Game Over....");
break;
}
/**
* if all spawned rooms have been cleared then the player wins, the game is finished
*/
if (roomgen.roomlist.isEmpty()) {
System.out.println("You win");
break;
}
}
}
}
|
package com.tencent.mm.plugin.fav.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.g.a.ch;
class b$1 implements OnClickListener {
final /* synthetic */ ch iXT;
b$1(ch chVar) {
this.iXT = chVar;
}
public final void onClick(DialogInterface dialogInterface, int i) {
if (i == -2) {
b.a(this.iXT);
}
}
}
|
package com.google.android.exoplayer2;
import com.google.android.exoplayer2.g.f;
import com.google.android.exoplayer2.h.b;
import com.google.android.exoplayer2.h.j;
import com.google.android.exoplayer2.i.m;
import com.google.android.exoplayer2.i.t;
public final class c implements m {
private final j acs;
private final long act;
private final long acu;
private final long acv;
private final long acw;
private final m acx;
private int acy;
private boolean isBuffering;
public c() {
this(new j());
}
private c(j jVar) {
this(jVar, (byte) 0);
}
private c(j jVar, byte b) {
this(jVar, 0);
}
private c(j jVar, char c) {
this.acs = jVar;
this.act = 15000000;
this.acu = 30000000;
this.acv = 2500000;
this.acw = 5000000;
this.acx = null;
}
public final void iy() {
reset(false);
}
public final void a(r[] rVarArr, f fVar) {
int i = 0;
this.acy = 0;
while (i < rVarArr.length) {
if (fVar.aAu[i] != null) {
this.acy += t.df(rVarArr[i].getTrackType());
}
i++;
}
this.acs.cV(this.acy);
}
public final void onStopped() {
reset(true);
}
public final void iz() {
reset(true);
}
public final b iA() {
return this.acs;
}
public final boolean c(long j, boolean z) {
long j2 = z ? this.acw : this.acv;
return j2 <= 0 || j >= j2;
}
public final boolean p(long j) {
boolean z = false;
boolean z2 = j > this.acu ? false : j < this.act ? true : true;
boolean z3;
if (this.acs.lR() >= this.acy) {
z3 = true;
} else {
z3 = false;
}
boolean z4 = this.isBuffering;
if (z2 || (z2 && this.isBuffering && !z3)) {
z = true;
}
this.isBuffering = z;
if (!(this.acx == null || this.isBuffering == z4)) {
if (this.isBuffering) {
m mVar = this.acx;
synchronized (mVar.lock) {
mVar.aCs.add(Integer.valueOf(0));
mVar.aCt = Math.max(mVar.aCt, 0);
}
} else {
this.acx.mo();
}
}
return this.isBuffering;
}
private void reset(boolean z) {
this.acy = 0;
if (this.acx != null && this.isBuffering) {
this.acx.mo();
}
this.isBuffering = false;
if (z) {
this.acs.reset();
}
}
}
|
package com.figureshop.springmvc.service.impl;
import com.figureshop.springmvc.constants.PricingConstants;
import com.figureshop.springmvc.model.Product;
import com.figureshop.springmvc.model.ProductItem;
import com.figureshop.springmvc.model.Translation;
import com.figureshop.springmvc.service.ProductService;
import org.junit.BeforeClass;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.RoundingMode;
import static org.junit.Assert.*;
public class ProductServiceImplTest {
private ProductService productService = new ProductServiceImpl();
@Test
public void getTotalPriceWithTVA() {
BigDecimal totalPrice = new BigDecimal(98.23);
BigDecimal totalPriceTVA = new BigDecimal(118.8583).setScale(2, BigDecimal.ROUND_HALF_UP);
assertTrue(totalPriceTVA.compareTo(productService.getTotalPriceWithTVA(totalPrice).setScale(2, BigDecimal.ROUND_HALF_UP)) == 0);
}
@Test
public void getVATAmount() {
BigDecimal totalPrice = new BigDecimal(15.29);
BigDecimal tvaAmount = new BigDecimal(3.2109).setScale(2, RoundingMode.HALF_UP);
assertTrue(tvaAmount.compareTo(productService.getVATAmount(totalPrice).setScale(2, RoundingMode.HALF_UP)) == 0);
totalPrice = new BigDecimal(38.28);
tvaAmount = new BigDecimal(8.0388).setScale(2, RoundingMode.HALF_UP);
assertTrue(tvaAmount.compareTo(productService.getVATAmount(totalPrice).setScale(2, RoundingMode.HALF_UP)) == 0);
}
@Test
public void updateTotalPrice() {
Translation translation = new Translation();
Product product = new Product();
product.setPrice(new BigDecimal(10.58));
translation.setProduct(product);
ProductItem productItem = new ProductItem();
productItem.setTranslation(translation);
productItem.setQuantity(18);
productItem.setSubTotal(new BigDecimal(190.44));
int qty = 17;
BigDecimal totalPrice = productItem.getSubTotal();
BigDecimal newTotalPrice = new BigDecimal(179.86).setScale(2, BigDecimal.ROUND_HALF_UP);
assertTrue(newTotalPrice.compareTo(productService.updateTotalPrice(productItem, qty, totalPrice).setScale(2, BigDecimal.ROUND_HALF_UP)) == 0);
qty = 19;
newTotalPrice = new BigDecimal(201.02).setScale(2, RoundingMode.HALF_UP);
assertTrue(newTotalPrice.compareTo(productService.updateTotalPrice(productItem, qty, totalPrice).setScale(2, BigDecimal.ROUND_HALF_UP)) == 0);
}
@Test
public void updateTotalPriceDown() {
BigDecimal totalPrice = new BigDecimal(220);
BigDecimal subTotal = new BigDecimal(20);
BigDecimal newTotal = new BigDecimal(200).setScale(2, RoundingMode.HALF_UP);
assertTrue(newTotal.compareTo(productService.updateTotalPriceDown(totalPrice, subTotal).setScale(2, RoundingMode.HALF_UP)) == 0);
totalPrice = new BigDecimal(112.44);
subTotal = new BigDecimal(110.22);
newTotal = new BigDecimal(2.22).setScale(2, RoundingMode.HALF_UP);
assertTrue(newTotal.compareTo(productService.updateTotalPriceDown(totalPrice, subTotal).setScale(2, RoundingMode.HALF_UP)) == 0);
}
@Test
public void updateTotalPriceUp() {
BigDecimal totalPrice = new BigDecimal(222.22);
BigDecimal subTotal = new BigDecimal(112.22);
BigDecimal formerSubTotal = new BigDecimal(111.11);
BigDecimal newTotal = new BigDecimal(223.33).setScale(PricingConstants.PRICE_SCALE, RoundingMode.HALF_UP);
assertTrue(newTotal.compareTo(productService.updateTotalPriceUp(totalPrice, subTotal, formerSubTotal).setScale(PricingConstants.PRICE_SCALE, RoundingMode.HALF_UP)) == 0);
totalPrice = new BigDecimal(929);
subTotal = new BigDecimal(125);
formerSubTotal = new BigDecimal(25);
newTotal = new BigDecimal(1029).setScale(PricingConstants.PRICE_SCALE, RoundingMode.HALF_UP);
assertTrue(newTotal.compareTo(productService.updateTotalPriceUp(totalPrice, subTotal, formerSubTotal).setScale(PricingConstants.PRICE_SCALE, RoundingMode.HALF_UP)) == 0);
}
@Test
public void getSubTotal() {
BigDecimal price = new BigDecimal(20.98);
int qty = 15;
BigDecimal subTotal = new BigDecimal(314.7).setScale(2, BigDecimal.ROUND_HALF_UP);
assertTrue(subTotal.compareTo(productService.getSubTotal(price, qty).setScale(2, BigDecimal.ROUND_HALF_UP)) == 0);
qty = 22;
price = new BigDecimal(40);
subTotal = new BigDecimal(880).setScale(2, RoundingMode.HALF_UP);
assertTrue(subTotal.compareTo(productService.getSubTotal(price, qty).setScale(2, BigDecimal.ROUND_HALF_UP)) == 0);
}
}
|
package com.mathpar.students.ukma.Morenets.MPI_3;
import java.util.Arrays;
import mpi.*;
public class MPI_3_5 {
public static void main(String[] args) throws MPIException {
MPI.Init(args);
int myrank = MPI.COMM_WORLD.getRank();
int n = Integer.parseInt(args[0]);
int np = MPI.COMM_WORLD.getSize();
int[] a = new int[n * np];
if(myrank == 0){
for (int i = 0; i < a.length; i++)
a[i] = i;
System.out.println("myrank = " + myrank + ": a = " + Arrays.toString(a));
}
int[] q = new int[n];
MPI.COMM_WORLD.barrier();
MPI.COMM_WORLD.scatterv(a, new int[]{n, n, n, n},
new int[]{0, 4, 8, 12}, MPI.INT, q, n, MPI.INT, 0);
System.out.println("myrank = " + myrank + ": q = " + Arrays.toString(q));
MPI.Finalize();
}
}
/*
Command: mpirun -np 4 java -cp out/production/MPI_3_5 MPI_3_5 4
Output:
myrank = 0: a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
myrank = 0: q = [0, 1, 2, 3]
myrank = 3: q = [12, 13, 14, 15]
myrank = 1: q = [4, 5, 6, 7]
myrank = 2: q = [8, 9, 10, 11]
*/
|
package io.jh.service.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.time.Instant;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
import io.jh.domain.enumeration.Week;
/**
* A DTO for the {@link io.jh.domain.WeekMenu} entity.
*/
@ApiModel(description = "一周菜单,用于在公众号上展示的菜品列表\n@author Jo")
public class WeekMenuDTO implements Serializable {
private Long id;
@NotNull
private Week week;
/**
* 菜品在所在天的顺序
*/
@NotNull
@Min(value = 0)
@Max(value = 999999999)
@ApiModelProperty(value = "菜品在所在天的顺序", required = true)
private Integer sort;
@NotNull
private Instant lastModifiedDate;
@NotNull
@Size(max = 20)
private String lastModifiedBy;
private Long foodId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Week getWeek() {
return week;
}
public void setWeek(Week week) {
this.week = week;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Long getFoodId() {
return foodId;
}
public void setFoodId(Long foodId) {
this.foodId = foodId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WeekMenuDTO weekMenuDTO = (WeekMenuDTO) o;
if (weekMenuDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), weekMenuDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "WeekMenuDTO{" +
"id=" + getId() +
", week='" + getWeek() + "'" +
", sort=" + getSort() +
", lastModifiedDate='" + getLastModifiedDate() + "'" +
", lastModifiedBy='" + getLastModifiedBy() + "'" +
", foodId=" + getFoodId() +
"}";
}
}
|
package data;
public class Attaquant extends Joueur{
private int puissanceTir = 0;
private int precisionTir = 0;
public Attaquant(String nom, String prenom, int experience, int attaque, int defense, int passe, int dribble,
int puissanceTir, int precisionTir) {
super(prenom, nom, experience, attaque, defense, passe, dribble);
this.puissanceTir = puissanceTir;
this.precisionTir = precisionTir;
}
public Attaquant() {
super();
}
public int getPuissanceTir() {
return puissanceTir;
}
public void setPuissanceTir(int puissanceTir) {
this.puissanceTir = puissanceTir;
}
public int getPrecisionTir() {
return precisionTir;
}
public void setPrecisionTir(int precisionTir) {
this.precisionTir = precisionTir;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + precisionTir;
result = prime * result + puissanceTir;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Attaquant other = (Attaquant) obj;
if (precisionTir != other.precisionTir)
return false;
if (puissanceTir != other.puissanceTir)
return false;
return true;
}
}
|
package com.claycorp.nexstore.api.mock;
import java.time.LocalDateTime;
import java.util.Arrays;
import org.springframework.stereotype.Service;
import com.claycorp.nexstore.api.model.OrderItemVo;
import com.claycorp.nexstore.api.model.OrderVo;
import com.claycorp.nexstore.api.model.PriceVo;
import com.claycorp.nexstore.api.model.RefOrderItemStatusCodesVo;
import com.claycorp.nexstore.api.model.RefOrderStatusCodesVo;
import com.claycorp.nexstore.api.model.ShipmentItemsVo;
import com.claycorp.nexstore.api.model.ShipmentsVo;
@Service
public class MockResponseBuilder {
public ShipmentsVo buildMockShipment() {
ShipmentsVo shipmentVo = new ShipmentsVo();
OrderVo orderVo = buildOrderVo();
OrderItemVo orderItemVo = buildOrderItemVo();
orderVo.setOrderDetails(Arrays.asList(orderItemVo));
ShipmentItemsVo shipmentItemsVo = buildShipmentItemsVo();
shipmentVo.setShipmentId("asdas3yhr2hih2h4234sad").setOrder(orderVo)
.setInvoiceNumber(Long.valueOf(23423424))
.setShipmentTrackingNumber(Long.valueOf(32425425))
.setShipmentDate(LocalDateTime.now())
.setOtherShipmentDetails("Something")
.setShipmentItems(Arrays.asList(shipmentItemsVo));
return shipmentVo;
}
private ShipmentItemsVo buildShipmentItemsVo() {
ShipmentItemsVo shipmentItemVo = new ShipmentItemsVo();
shipmentItemVo.setOrderItemVo(buildOrderItemVo())
.setShipmentId("3242ewr2ew24fdfsf2");
return shipmentItemVo;
}
private OrderItemVo buildOrderItemVo() {
OrderItemVo orderItemVo = new OrderItemVo();
orderItemVo.setOrderItemId("ahadst327ga732yhdafd")
.setOrderItemPrice(new PriceVo("INR", Double.valueOf(342432)))
.setOrderItemQuantity(Long.valueOf(3))
.setOrderItemStatusCode(new RefOrderItemStatusCodesVo("ST12", "In Progress"))
.setProductId("adsa3242d23adda31dsa")
.setOtherOrderItemDetails("Something else")
.setRmaNumber(Long.valueOf(32423424))
.setRmaIssuedBy("Clayman")
.setRmaIssuedDate(LocalDateTime.now());
return orderItemVo;
}
private OrderVo buildOrderVo() {
OrderVo orderVo = new OrderVo();
orderVo.setId("gh32y4ui2uhhiu2das")
.setStatusCode(new RefOrderStatusCodesVo("ST32", "Some Status"))
.setDateOfOrderPlaced(LocalDateTime.now())
.setOrderDetails(Arrays.asList(buildOrderItemVo()));
return orderVo;
}
/*
* private Address buildAddressMock() { Address address = new Address();
* address.setAddress1("Church Stree1").setAddress2("Stree2").
* setLandmark("Park plaza").setPinCode("3424234"); return address; }
*/
}
|
package com.spring.shopping.review;
public class ReviewVO {
private int num;
private int reviewNum;
private int pref;
private String content;
private String name;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getPref() {
return pref;
}
public void setPref(int pref) {
this.pref = pref;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getReviewNum() {
return reviewNum;
}
public void setReviewNum(int reviewNum) {
this.reviewNum = reviewNum;
}
}
|
package cn.uway.task;
/**
* 任务执行的结果
*
* @author Niow
* @Date 2014-6-20
* @version 1.0
* @since 1.3.0
*/
public class TaskFuture{
/** 执行成功 */
public static final int TASK_CODE_SUCCESS = 0;
/** 执行失败,需要重新执行 */
public static final int TASK_CODE_FAILED = -1;
/** 执行结果不完整 */
public static final int TASK_CODE_INCOMPLETE = 1;
private String cause; // 失败原因
private Task task; // 参考对象
private int code;
/**
* 构造操作成功的结果对象
*/
public TaskFuture(){
super();
}
/**
* 构建任务执行的结果对象
*
* @param refObj 如果失败,可以填写一下参考对象
*/
public TaskFuture(int code, Task refObj){
super();
this.task = refObj;
this.code = code;
}
/**
* 构建任务执行的结果对象
*
* @param code 操作结果码
* @param cause 如果失败,可以填写一下原因
* @param refObj 如果失败,可以填写一下参考对象
*/
public TaskFuture(int code, String cause, Task refObj){
super();
this.cause = cause;
this.task = refObj;
this.code = code;
}
/**
* 获取失败原因
*/
public String getCause(){
return cause;
}
public void setCause(String cause){
this.cause = cause;
}
/**
* 获取参考引用对象
*/
public Task getTask(){
return task;
}
public void setTask(Task task){
this.task = task;
}
/**
* @return the code
*/
public int getCode(){
return code;
}
/**
* @param code the code to set
*/
public void setCode(int code){
this.code = code;
}
}
|
package com.jim.multipos.ui.lock_screen;
import com.jim.multipos.core.BaseView;
/**
* Created by DEV on 04.08.2017.
*/
public interface LockScreenView extends BaseView {
void successCheck();
void setError(int EMPTY);
}
|
package gov.smart.health.activity.login;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.StringRequestListener;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import gov.smart.health.R;
import gov.smart.health.activity.HomeActivity;
import gov.smart.health.activity.login.model.LoginModel;
import gov.smart.health.activity.login.model.RegisterUserModel;
import gov.smart.health.utils.SHConstants;
import gov.smart.health.utils.SharedPreferencesHelper;
public class RegisterActivity extends AppCompatActivity {
private TextView userName,userPhone,userMail,userFirstPwd ,userSecondPwd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
View btnRegister = findViewById(R.id.btn_register_user);
userName = (TextView)findViewById(R.id.register_user_name);
userPhone = (TextView)findViewById(R.id.register_user_phone);
userMail = (TextView)findViewById(R.id.register_mail);
userFirstPwd = (TextView)findViewById(R.id.register_first_pwd);
userSecondPwd = (TextView)findViewById(R.id.register_second_pwd);
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
registerUser();
}
});
findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
private void registerUser(){
String userNameTxt = userName.getText().toString();
String userPhoneTxt = userPhone.getText().toString();
String userMailTxt = userMail.getText().toString();
String userFirstPwdTxt = userFirstPwd.getText().toString();
String userSecondPwdTxt = userSecondPwd.getText().toString();
if(userNameTxt.isEmpty() || userPhoneTxt.isEmpty() ||userMailTxt.isEmpty() ||userFirstPwdTxt.isEmpty() ||userSecondPwdTxt.isEmpty()){
Toast.makeText(getApplication(),"请输入完整信息",Toast.LENGTH_LONG).show();
return;
}
if(!Patterns.PHONE.matcher(userPhoneTxt).matches()){
Toast.makeText(getApplication(),"请输正确的手机号码!",Toast.LENGTH_LONG).show();
return;
}
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(userMailTxt).matches()){
Toast.makeText(getApplication(),"请输正确的邮箱地址!",Toast.LENGTH_LONG).show();
return;
}
if(!userFirstPwdTxt.equals(userSecondPwdTxt)){
Toast.makeText(getApplication(),"两次密码输入不正确",Toast.LENGTH_LONG).show();
return;
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(SHConstants.Register_Person_Code, userNameTxt);
jsonObject.put(SHConstants.Register_Person_name, userNameTxt);
jsonObject.put(SHConstants.Register_Mobile, userPhoneTxt);
jsonObject.put(SHConstants.Register_Email, userMailTxt);
jsonObject.put(SHConstants.Register_Password, userFirstPwdTxt);
} catch (JSONException e) {
e.printStackTrace();
}
AndroidNetworking.post(SHConstants.PersonSave)
.addJSONObjectBody(jsonObject) // posting json
.addHeaders(SHConstants.HeaderContentType, SHConstants.HeaderContentTypeValue)
.addHeaders(SHConstants.HeaderAccept, SHConstants.HeaderContentTypeValue)
.setPriority(Priority.MEDIUM)
.build()
.getAsString(new StringRequestListener() {
@Override
public void onResponse(String response) {
Gson gson = new Gson();
RegisterUserModel model = gson.fromJson(response,RegisterUserModel.class);
if (model.success){
Toast.makeText(getApplication(),"注册成功",Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(getApplication(),"注册失败",Toast.LENGTH_LONG).show();
}
}
@Override
public void onError(ANError anError) {
Log.d("","response error"+anError.getErrorDetail());
Toast.makeText(getApplication(),"注册失败",Toast.LENGTH_LONG).show();
}
});
}
}
|
package com.tencent.mm.plugin.account.friend.a;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.tencent.mm.a.g;
import com.tencent.mm.plugin.account.a;
import com.tencent.mm.plugin.account.a.f;
import com.tencent.mm.protocal.c.arf;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.applet.b;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public final class i extends BaseAdapter {
private Context context;
public List<String[]> eHv;
public int[] eIr;
public LinkedList<arf> eKc = new LinkedList();
private LinkedList<arf> eKd = new LinkedList();
private List<String[]> eKe = new LinkedList();
private a eKf;
public b eKg = new b(new 1(this));
private b.b eKh = null;
int showType = 1;
public i(Context context, a aVar, int i) {
this.context = context;
this.showType = i;
this.eKf = aVar;
this.eIr = new int[this.eKc.size()];
}
public final int getSelectCount() {
int i = 0;
for (int i2 : this.eIr) {
if (this.showType == 1) {
if (i2 == 1) {
i++;
}
} else if (this.showType == 2 && i2 == 2) {
i++;
}
}
return i;
}
public final boolean Xx() {
if (this.eIr == null || this.eIr.length == 0) {
return false;
}
for (int i : this.eIr) {
if (this.showType == 1) {
if (i == 0) {
return false;
}
} else if (this.showType == 2 && i == 0) {
return false;
}
}
return true;
}
public final void jb(int i) {
if (this.showType == 1) {
this.eIr[i] = 1;
} else if (this.showType == 2) {
this.eIr[i] = 2;
}
notifyDataSetChanged();
}
public final void ci(boolean z) {
int i;
int i2;
if (this.showType == 1) {
for (i = 0; i < this.eIr.length; i++) {
int[] iArr = this.eIr;
if (z) {
i2 = 1;
} else {
i2 = 0;
}
iArr[i] = i2;
}
} else if (this.showType == 2) {
for (i = 0; i < this.eIr.length; i++) {
int[] iArr2 = this.eIr;
if (z) {
i2 = 2;
} else {
i2 = 0;
}
iArr2[i] = i2;
}
}
notifyDataSetChanged();
}
public final void notifyDataSetChanged() {
super.notifyDataSetChanged();
if (this.eKf != null) {
this.eKf.notifyDataSetChanged();
}
}
public final void p(LinkedList<arf> linkedList) {
if (linkedList != null) {
this.eKd.clear();
this.eKc.clear();
this.eKe.clear();
for (String[] strArr : this.eHv) {
Iterator it = linkedList.iterator();
while (it.hasNext()) {
arf arf = (arf) it.next();
if (this.showType == 1) {
if ((arf.hcd == 1 || arf.hcd == 0) && !bi.oW(strArr[2]) && arf.mEl.equals(g.u(strArr[2].getBytes()))) {
a(arf, strArr);
}
} else if (this.showType == 2 && arf.hcd == 2 && !bi.oW(strArr[2]) && arf.mEl.equals(g.u(strArr[2].getBytes()))) {
a(arf, strArr);
}
}
}
}
this.eIr = new int[this.eKd.size()];
this.eKc.addAll(this.eKd);
this.eKd.clear();
}
private void a(arf arf, String[] strArr) {
Iterator it = this.eKd.iterator();
while (it.hasNext()) {
arf arf2 = (arf) it.next();
if (arf2.mEl != null && arf.mEl != null && arf2.mEl.equals(arf.mEl)) {
x.d("MicroMsg.FriendAdapter", "tigerreg mobile already added");
return;
}
}
this.eKd.add(arf);
this.eKe.add(new String[]{strArr[2], strArr[1]});
}
public final int getCount() {
return this.eKc.size();
}
/* renamed from: jc */
public final arf getItem(int i) {
return (arf) this.eKc.get(i);
}
public final long getItemId(int i) {
return (long) ((arf) this.eKc.get(i)).hashCode();
}
public final View getView(int i, View view, ViewGroup viewGroup) {
b bVar;
if (this.showType == 1) {
if (this.eKh == null) {
this.eKh = new 2(this);
}
if (this.eKg != null) {
this.eKg.a(i, this.eKh);
}
}
arf arf = (arf) this.eKc.get(i);
if (view == null) {
bVar = new b();
if (this.showType == 1) {
view = View.inflate(this.context, a.g.find_friend_add_item, null);
bVar.eIz = (TextView) view.findViewById(f.mobile_friend_name);
bVar.eKl = (TextView) view.findViewById(f.mobile_friend_add_state);
bVar.eKm = (Button) view.findViewById(f.mobile_friend_add_tv);
bVar.eKn = (Button) view.findViewById(f.mobile_friend_invite_tv);
bVar.eKk = (ImageView) view.findViewById(f.friend_avatar_iv);
bVar.eKo = (TextView) view.findViewById(f.mobile_friend_selected);
bVar.eKp = (TextView) view.findViewById(f.mobile_friend_unselect);
view.setTag(bVar);
} else if (this.showType == 2) {
view = View.inflate(this.context, a.g.find_friend_item, null);
bVar.eIz = (TextView) view.findViewById(f.mobile_friend_name);
bVar.eKl = (TextView) view.findViewById(f.mobile_friend_add_state);
bVar.eKm = (Button) view.findViewById(f.mobile_friend_add_tv);
bVar.eKn = (Button) view.findViewById(f.mobile_friend_invite_tv);
bVar.eKo = (TextView) view.findViewById(f.mobile_friend_selected);
bVar.eKp = (TextView) view.findViewById(f.mobile_friend_unselect);
view.setTag(bVar);
}
} else {
bVar = (b) view.getTag();
}
bVar.eKp.setOnClickListener(new 3(this, i));
if (this.showType == 1) {
if (!bi.oW(((String[]) this.eKe.get(i))[1])) {
bVar.eIz.setText(((String[]) this.eKe.get(i))[1]);
} else if (bi.oW(arf.hcS)) {
bVar.eIz.setText(arf.hbL);
} else {
bVar.eIz.setText(arf.hcS);
}
bVar.eKm.setOnClickListener(new 4(this, i));
com.tencent.mm.pluginsdk.ui.a.b.a(bVar.eKk, arf.hbL);
} else if (this.showType == 2) {
bVar.eIz.setText(((String[]) this.eKe.get(i))[1]);
bVar.eKn.setOnClickListener(new 5(this, i));
}
switch (this.eIr[i]) {
case 0:
if (this.showType != 1) {
if (this.showType == 2) {
bVar.eKl.setVisibility(8);
bVar.eKm.setVisibility(8);
bVar.eKn.setVisibility(0);
bVar.eKo.setVisibility(8);
bVar.eKp.setVisibility(8);
break;
}
}
bVar.eKl.setVisibility(8);
bVar.eKm.setVisibility(0);
bVar.eKn.setVisibility(8);
bVar.eKo.setVisibility(8);
bVar.eKp.setVisibility(8);
break;
break;
case 1:
bVar.eKm.setVisibility(8);
bVar.eKl.setVisibility(0);
bVar.eKo.setVisibility(0);
bVar.eKp.setVisibility(0);
break;
case 2:
bVar.eKm.setVisibility(8);
bVar.eKn.setVisibility(8);
bVar.eKl.setVisibility(0);
bVar.eKo.setVisibility(0);
bVar.eKp.setVisibility(0);
break;
case 3:
bVar.eKm.setVisibility(8);
bVar.eKl.setVisibility(0);
bVar.eKo.setVisibility(0);
bVar.eKp.setVisibility(0);
break;
}
return view;
}
public final void pu(String str) {
List arrayList = new ArrayList();
for (int i = 0; i < this.eKe.size(); i++) {
if (this.eIr[i] == 2) {
arrayList.add(((String[]) this.eKe.get(i))[0]);
}
}
com.tencent.mm.kernel.g.DF().a(new ai(str, arrayList), 0);
}
}
|
package com.product.controller;
import com.product.entity.UnitMasterEntity;
import com.product.service.UnitMasterService;
import com.system.constants.BaseErrorConstants;
import com.system.util.*;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class UnitMasterController {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(UnitMasterController.class);
@Autowired
private UnitMasterService unitMasterService;
/**
* find list
*
* @Author chenxichao
* @Description //TODO
* @Date 2019-05-16 16:12
* @Param [request]
**/
@GetMapping(value = "/unit/findList")
public ServiceResult<List<UnitMasterEntity>> findList(HttpServletRequest request) {
ServiceResult<List<UnitMasterEntity>> result = new ServiceResult<List<UnitMasterEntity>>();
PagerInfo<?> pagerInfo = null;
Map<String, Object> params = null;
int unitId = ConvertUtil.toInt(request.getParameter("unitId"), 0);
int storeId = ConvertUtil.toInt(request.getParameter("storeId"), 0);
try {
if (!StringUtil.isEmpty(request.getParameter("pageSize"))) {
pagerInfo = BaseWebUtil.getPageInfoForPC(request);
}
params = new HashMap<String, Object>();
if (unitId > 0) {
params.put("unitId", unitId);
}
if (storeId > 0) {
params.put("storeId", storeId);
}
result = unitMasterService.findList(params, pagerInfo);
} catch (Exception e) {
LOGGER.error("[UnitMasterController][findList]:query findList occur exception", e);
result.setError(BaseErrorConstants.ERROR_CODE_SERVICE_CONTROLLER, "Find unit list error.");
}
return result;
}
/**
* find info
*
* @Author chenxichao
* @Description //TODO
* @Date 2019-05-16 16:12
* @Param [request]
**/
@GetMapping(value = "/unit/findInfo")
public ServiceResult<UnitMasterEntity> findInfo(HttpServletRequest request) {
ServiceResult<UnitMasterEntity> result = new ServiceResult<UnitMasterEntity>();
Map<String, Object> params = null;
int unitId = ConvertUtil.toInt(request.getParameter("unitId"), 0);
try {
params = new HashMap<String, Object>();
if (unitId > 0) {
params.put("unitId", unitId);
}
result = unitMasterService.findInfo(params);
} catch (Exception e) {
LOGGER.error("[UnitMasterController][findInfo]:query findInfo occur exception", e);
result.setError(BaseErrorConstants.ERROR_CODE_SERVICE_CONTROLLER, "Find unit error.");
}
return result;
}
/**
* do insert
*
* @Author chenxichao
* @Description //TODO
* @Date 2019-05-16 16:12
* @Param [brandMasterEntity]
**/
@PostMapping(value = "/unit/doInsert")
public ServiceResult<Integer> doInsert(@RequestBody UnitMasterEntity unitMasterEntity) {
ServiceResult<Integer> result = new ServiceResult<Integer>();
try {
result = unitMasterService.doInsert(unitMasterEntity);
} catch (Exception e) {
LOGGER.error("[UnitMasterController][doInsert]:Insert occur exception", e);
result.setError(BaseErrorConstants.ERROR_CODE_SERVICE_CONTROLLER, "Insert error.");
}
return result;
}
/**
* do update
*
* @Author chenxichao
* @Description //TODO
* @Date 2019-05-16 16:12
* @Param [brandMasterEntity]
**/
@PostMapping(value = "/unit/doUpdate")
public ServiceResult<Integer> doUpdate(@RequestBody UnitMasterEntity unitMasterEntity) {
ServiceResult<Integer> result = new ServiceResult<Integer>();
try {
result = unitMasterService.doUpdate(unitMasterEntity);
} catch (Exception e) {
LOGGER.error("[UnitMasterController][doUpdate]:Update occur exception", e);
result.setError(BaseErrorConstants.ERROR_CODE_SERVICE_CONTROLLER, "Update error.");
}
return result;
}
/**
* do delete
*
* @Author chenxichao
* @Description //TODO
* @Date 2019-05-16 16:12
* @Param [brandId]
**/
@PostMapping(value = "/unit/doDelete")
public ServiceResult<Boolean> doDelete(@RequestParam("unitId") int unitId) {
ServiceResult<Boolean> result = unitMasterService.doDelete(unitId);
return result;
}
}
|
package com.yixin.web.service.message;
import com.yixin.kepler.common.RestTemplateUtil;
import com.yixin.web.dto.message.MessageBodyDTO;
import com.yixin.web.dto.message.MessageInfoDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @description:
* @date: 2018-09-03 15:04
*/
@Service
public class EmailSendService {
private static final Logger logger = LoggerFactory.getLogger(EmailSendService.class);
@Value("${spring.message.host}")
private String messageHost;
@Value("${spring.notice.mail.from}")
private String mailFrom;
@Value("${spring.subject_prefix}")
private String subjectPrefix;
/**
* 发送邮件
*
* @return
*/
public void sendEmail(String mailTo, String subject, String emailTemplate, Object[] values) {
String url = messageHost + "/mc/yxMessage/send";
logger.info("send email start , mail to:{}, subject:{}", mailTo, subject);
try {
MessageInfoDTO messageInfo = buildEmailData(mailTo, subject, emailTemplate, values);
String msgRespJson = RestTemplateUtil.sendRequestNoBaffle(url, messageInfo);
logger.info("send email end, mail to:{}, subject:{}, result:{}", mailTo, subject, msgRespJson);
} catch (Exception e) {
logger.error("send email error", e);
}
}
/**
* 组织邮件数据
*
* @param mailTo
* @param subject
* @param emailTemplate
* @param values
* @return
*/
private MessageInfoDTO buildEmailData(String mailTo, String subject, String emailTemplate, Object... values) {
MessageInfoDTO emailMsgInfo = new MessageInfoDTO();
emailMsgInfo.setType(2);
MessageBodyDTO messageBody = new MessageBodyDTO();
emailMsgInfo.setData(messageBody);
messageBody.setMailFrom(mailFrom);
messageBody.setMailTo(mailTo);
String mailText = String.format(emailTemplate, values);
messageBody.setMailText(mailText);
messageBody.setMailSubject(buildSubject(subject));
return emailMsgInfo;
}
private String buildSubject(String subject) {
return subjectPrefix + subject;
}
}
|
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
public class BookingRegister {
// attribute
HashMap<Facility, ArrayList<Booking>> bookinglist = new HashMap<Facility, ArrayList<Booking>>();
ArrayList<Booking> exact;
// constructor
public BookingRegister(HashMap<Facility, ArrayList<Booking>> bookinglist) {
super();
this.bookinglist = bookinglist;
}
// property
public HashMap<Facility, ArrayList<Booking>> getBookinglist() {
return bookinglist;
}
public void setBookinglist(HashMap<Facility, ArrayList<Booking>> bookinglist) {
this.bookinglist = bookinglist;
}
//add booking to hashmap
public void addBooking(Member member, Facility facility, LocalDate fromdate, LocalDate enddate)
throws BadBookingException {
// use key to get the exact facility's booking list
exact = bookinglist.get(facility);
int j = 0;
// create a new booking
Booking newBooking = new Booking(member, facility, fromdate, enddate);
// if the facility doesn't have a booking,create a list for it
if (exact == null) {
exact = new ArrayList<Booking>();
} else {
// if it has a booking,check if has overlap ,if not ,add it
for (int i = 0; i < exact.size(); i++) {
if (newBooking.overlaps(exact.get(i)) == true) {
j = -1;
break;
}
}
}
if (j == 0) {
exact.add(newBooking);
bookinglist.put(facility, exact);
}
}
//remove booking
public void removeBooking(Booking booking) {
Facility exactfacility = null;
for (Facility o : bookinglist.keySet()) {
if (bookinglist.get(o).equals(booking)) {
exactfacility = o;
}
ArrayList<Booking> exact = bookinglist.get(o);
exact.remove(booking);
}
}
//get all booking of exact facility
public ArrayList<Booking> get(Facility facility) {
ArrayList<Booking> bookings = new ArrayList<Booking>();
bookings = bookinglist.get(facility);
// TODO Auto-generated method stub
return bookings;
}
}
|
package com.pine.template.mvp.ui.fragment;
import android.os.Bundle;
import android.view.View;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.pine.template.base.recycle_view.adapter.BaseListAdapter;
import com.pine.template.mvp.R;
import com.pine.template.mvp.adapter.MvpShopListPaginationAdapter;
import com.pine.template.mvp.contract.IMvpShopPaginationContract;
import com.pine.template.mvp.presenter.MvpShopPaginationListPresenter;
import com.pine.tool.architecture.mvp.ui.MvpFragment;
/**
* Created by tanghongfeng on 2018/9/28
*/
public class MvpShopPaginationListFragment extends MvpFragment<IMvpShopPaginationContract.Ui, MvpShopPaginationListPresenter>
implements IMvpShopPaginationContract.Ui, SwipeRefreshLayout.OnRefreshListener {
private SwipeRefreshLayout swipe_refresh_layout;
private RecyclerView recycle_view;
@Override
protected int getFragmentLayoutResId() {
return R.layout.mvp_fragment_shop_pagination_list;
}
@Override
protected void findViewOnCreateView(View layout, Bundle savedInstanceState) {
swipe_refresh_layout = layout.findViewById(R.id.swipe_refresh_layout);
recycle_view = layout.findViewById(R.id.recycle_view);
}
@Override
protected void init(Bundle savedInstanceState) {
swipe_refresh_layout.setOnRefreshListener(this);
swipe_refresh_layout.setColorSchemeResources(
R.color.red,
R.color.yellow,
R.color.green
);
swipe_refresh_layout.setDistanceToTriggerSync(250);
if (swipe_refresh_layout != null) {
swipe_refresh_layout.setRefreshing(true);
}
swipe_refresh_layout.setEnabled(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycle_view.setLayoutManager(linearLayoutManager);
recycle_view.setHasFixedSize(true);
MvpShopListPaginationAdapter adapter = mPresenter.getListAdapter();
adapter.setOnScrollListener(recycle_view,
new BaseListAdapter.IOnScrollListener() {
@Override
public void onLoadMore() {
onLoadingMore();
}
});
recycle_view.setAdapter(adapter);
swipe_refresh_layout.post(new Runnable() {
@Override
public void run() {
swipe_refresh_layout.setRefreshing(true);
onRefresh();
}
});
}
@Override
public void onRefresh() {
mPresenter.loadShopPaginationListData(true);
}
public void onLoadingMore() {
mPresenter.loadShopPaginationListData(false);
}
@Override
public void setLoadingUiVisibility(boolean processing) {
if (swipe_refresh_layout == null) {
return;
}
swipe_refresh_layout.setRefreshing(processing);
}
}
|
package com.tencent.map.lib.thread;
import java.io.Serializable;
import java.util.AbstractQueue;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class HighThreadExecutor$a<E> extends AbstractQueue<E> implements Serializable, BlockingQueue<E> {
transient b<E> a;
final /* synthetic */ HighThreadExecutor b;
private int c;
private final AtomicInteger d = new AtomicInteger();
private final ReentrantLock e = new ReentrantLock();
private final Condition f = this.e.newCondition();
private final ReentrantLock g = new ReentrantLock();
private final Condition h = this.g.newCondition();
class b<E> {
E a;
b<E> b;
b(E e) {
this.a = e;
}
}
public HighThreadExecutor$a(HighThreadExecutor highThreadExecutor, int i) {
this.b = highThreadExecutor;
this.c = i;
this.a = new b(null);
}
public Iterator<E> iterator() {
return new a(this);
}
public int size() {
return this.d.get();
}
public int drainTo(Collection<? super E> collection) {
return drainTo(collection, Integer.MAX_VALUE);
}
public int drainTo(Collection<? super E> collection, int i) {
ReentrantLock reentrantLock;
int i2;
Throwable th;
int i3 = 1;
if (collection == null) {
throw new NullPointerException();
} else if (collection == this) {
throw new IllegalArgumentException();
} else if (i <= 0) {
return 0;
} else {
reentrantLock = this.e;
reentrantLock.lock();
b bVar;
try {
int min = Math.min(i, this.d.get());
bVar = this.a;
i2 = 0;
while (i2 < min) {
b bVar2 = bVar.b;
collection.add(bVar2.a);
bVar2.a = null;
bVar.b = bVar;
i2++;
bVar = bVar2;
}
if (i2 > 0) {
this.a = bVar;
if (this.d.getAndAdd(-i2) != this.c) {
i3 = 0;
}
} else {
i3 = 0;
}
reentrantLock.unlock();
if (i3 != 0) {
d();
}
return min;
} catch (Throwable th2) {
th = th2;
i2 = i3;
}
}
reentrantLock.unlock();
if (i2 != 0) {
d();
}
throw th;
}
public boolean offer(E e) {
if (e == null) {
throw new NullPointerException();
}
AtomicInteger atomicInteger = this.d;
if (atomicInteger.get() == this.c) {
return false;
}
int i = -1;
b bVar = new b(e);
ReentrantLock reentrantLock = this.g;
reentrantLock.lock();
try {
if (atomicInteger.get() < this.c) {
a(bVar);
i = atomicInteger.getAndIncrement();
if (i + 1 < this.c) {
this.h.signal();
}
}
reentrantLock.unlock();
if (i == 0) {
e();
}
if (i >= 0) {
return true;
}
return false;
} catch (Throwable th) {
reentrantLock.unlock();
}
}
public boolean offer(E e, long j, TimeUnit timeUnit) {
if (e == null) {
throw new NullPointerException();
}
long toNanos = timeUnit.toNanos(j);
ReentrantLock reentrantLock = this.g;
AtomicInteger atomicInteger = this.d;
reentrantLock.lockInterruptibly();
while (atomicInteger.get() == this.c) {
try {
if (toNanos <= 0) {
return false;
}
toNanos = this.h.awaitNanos(toNanos);
} finally {
reentrantLock.unlock();
}
}
a(new b(e));
int andIncrement = atomicInteger.getAndIncrement();
if (andIncrement + 1 < this.c) {
this.h.signal();
}
reentrantLock.unlock();
if (andIncrement == 0) {
e();
}
return true;
}
public E poll(long j, TimeUnit timeUnit) {
long toNanos = timeUnit.toNanos(j);
AtomicInteger atomicInteger = this.d;
ReentrantLock reentrantLock = this.e;
reentrantLock.lockInterruptibly();
while (atomicInteger.get() == 0) {
try {
if (toNanos <= 0) {
return null;
}
toNanos = this.f.awaitNanos(toNanos);
} finally {
reentrantLock.unlock();
}
}
E b = b();
int andDecrement = atomicInteger.getAndDecrement();
if (andDecrement > 1) {
this.f.signal();
}
reentrantLock.unlock();
if (andDecrement != this.c) {
return b;
}
d();
return b;
}
public void put(E e) {
if (e == null) {
throw new NullPointerException();
}
b bVar = new b(e);
ReentrantLock reentrantLock = this.g;
AtomicInteger atomicInteger = this.d;
reentrantLock.lockInterruptibly();
while (atomicInteger.get() == this.c) {
try {
this.h.await();
} catch (Throwable th) {
reentrantLock.unlock();
}
}
a(bVar);
int andIncrement = atomicInteger.getAndIncrement();
if (andIncrement + 1 < this.c) {
this.h.signal();
}
reentrantLock.unlock();
if (andIncrement == 0) {
e();
}
}
public int remainingCapacity() {
return this.c - this.d.get();
}
public E take() {
AtomicInteger atomicInteger = this.d;
ReentrantLock reentrantLock = this.e;
reentrantLock.lockInterruptibly();
while (atomicInteger.get() == 0) {
try {
this.f.await();
} catch (Throwable th) {
reentrantLock.unlock();
}
}
E b = b();
int andDecrement = atomicInteger.getAndDecrement();
if (andDecrement > 1) {
this.f.signal();
}
reentrantLock.unlock();
if (andDecrement == this.c) {
d();
}
return b;
}
public E peek() {
E e = null;
if (this.d.get() != 0) {
ReentrantLock reentrantLock = this.e;
reentrantLock.lock();
try {
b bVar = this.a.b;
if (bVar != null) {
e = bVar.a;
reentrantLock.unlock();
}
} finally {
reentrantLock.unlock();
}
}
return e;
}
public E poll() {
E e = null;
AtomicInteger atomicInteger = this.d;
if (atomicInteger.get() != 0) {
int i = -1;
ReentrantLock reentrantLock = this.e;
reentrantLock.lock();
try {
if (atomicInteger.get() > 0) {
e = b();
i = atomicInteger.getAndDecrement();
if (i > 1) {
this.f.signal();
}
}
reentrantLock.unlock();
if (i == this.c) {
d();
}
} catch (Throwable th) {
reentrantLock.unlock();
}
}
return e;
}
private void a(b<E> bVar) {
bVar.b = this.a.b;
this.a.b = bVar;
}
private E b() {
b bVar = this.a.b;
if (bVar == null) {
return null;
}
this.a.b = bVar.b;
bVar.b = null;
E e = bVar.a;
bVar.a = null;
return e;
}
private void c() {
this.g.lock();
this.e.lock();
}
void a() {
this.e.unlock();
this.g.unlock();
}
void a(b<E> bVar, b<E> bVar2) {
bVar.a = null;
bVar2.b = bVar.b;
if (this.d.getAndDecrement() == this.c) {
this.h.signal();
}
}
private void d() {
ReentrantLock reentrantLock = this.g;
reentrantLock.lock();
try {
this.h.signal();
} finally {
reentrantLock.unlock();
}
}
private void e() {
ReentrantLock reentrantLock = this.e;
reentrantLock.lock();
try {
this.f.signal();
} finally {
reentrantLock.unlock();
}
}
}
|
package exer;
import java.util.Scanner;
/**
* @author menglanyingfei
* @date 2017-7-12
*/
public class Main11_TimeConvert {
/**
* @param args
* 待定?
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String now = null;
String str = in.nextLine();
String judge = new String("END");
String right = new String("$GPRMC");
while (!str.equals(judge)) // 输入为END ,结束输入
{
String[] ss = str.split(",");// 以逗号为分割 把str分割为若干字符串 放入数组ss
if (!ss[0].equals(right))// 如果第一个逗号以前的部分不为所要求,读入下一列,结束这一行处理
{
str = in.nextLine();
continue;
}
int i, result = 0;
char ch;
ch = str.charAt(1);// 从第二个字符开始做异或,存入result
for (result = str.charAt(1), i = 2; ch != '*'; i++, ch = str
.charAt(i)) {
ch = str.charAt(i);
result ^= (int) ch;
}
result %= 65536;
String num = str.substring(i + 1, i + 3);// 取*后面两位
char state = ss[2].charAt(0);
num = num.toLowerCase();// 转化为小写
if (num.equals(Integer.toHexString(result)) && state == 'A')// 如果相同
now = ss[1];
str = in.nextLine();
}
if (now == null)
System.exit(0);
String hh = now.substring(0, 2);
String mm = now.substring(2, 4);
String ss = now.substring(4, 6);
int hour = Integer.parseInt(hh);
hour = (hour + 8) % 24;
if (hour < 10)
System.out.print(0);
System.out.println(hour + ":" + mm + ":" + ss);// 输出时间
}
}
|
package cn.edu.hebtu.software.sharemate.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import java.util.ArrayList;
import cn.edu.hebtu.software.sharemate.R;
import cn.edu.hebtu.software.sharemate.tools.SelectInterestUtil;
public class SelectInterestActivity extends AppCompatActivity {
private Button button;
private CheckBox cbBeauty, cbTravel, cbSport, cbFood, cbScience, cbAnime;
private int typeId;
private int userId;
private String remark;
private ArrayList<Integer> type = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_interest);
findViews();
userId = getIntent().getIntExtra("userId", 0);
button.setOnClickListener(new ButtonClickListener());
cbBeauty.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("isChecked3",isChecked+"");
typeId = 3;
if(isChecked){
remark = "add";
type.add(3);
SelectInterestUtil selectInterest = new SelectInterestUtil(SelectInterestActivity.this,getResources().getString(R.string.server_path));
selectInterest.execute(userId, typeId,remark);
}else{
remark = "delete";
int i = type.indexOf(3);
type.remove(i);
SelectInterestUtil selectInterest = new SelectInterestUtil(SelectInterestActivity.this,getResources().getString(R.string.server_path));
selectInterest.execute(userId, typeId,remark);
}
}
});
cbTravel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("isChecked2",isChecked+"");
typeId = 2;
if(isChecked){
remark = "add";
type.add(2);
SelectInterestUtil selectInterest = new SelectInterestUtil(SelectInterestActivity.this,getResources().getString(R.string.server_path));
selectInterest.execute(userId, typeId,remark);
}else {
remark = "delete";
int i = type.indexOf(2);
type.remove(i);
SelectInterestUtil selectInterest = new SelectInterestUtil(SelectInterestActivity.this,getResources().getString(R.string.server_path));
selectInterest.execute(userId, typeId,remark);
}
}
});
cbSport.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("isChecked5",isChecked+"");
typeId = 5;
if(isChecked){
remark = "add";
type.add(5);
SelectInterestUtil selectInterest = new SelectInterestUtil(SelectInterestActivity.this,getResources().getString(R.string.server_path));
selectInterest.execute(userId, typeId,remark);
}else {
remark = "delete";
int i = type.indexOf(5);
type.remove(i);
SelectInterestUtil selectInterest = new SelectInterestUtil(SelectInterestActivity.this,getResources().getString(R.string.server_path));
selectInterest.execute(userId, typeId,remark);
}
}
});
cbFood.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("isChecked1",isChecked+"");
typeId = 1;
if(isChecked){
remark = "add";
type.add(1);
SelectInterestUtil selectInterest = new SelectInterestUtil(SelectInterestActivity.this,getResources().getString(R.string.server_path));
selectInterest.execute(userId, typeId,remark);
}else {
remark = "delete";
int i = type.indexOf(1);
type.remove(i);
SelectInterestUtil selectInterest = new SelectInterestUtil(SelectInterestActivity.this,getResources().getString(R.string.server_path));
selectInterest.execute(userId, typeId,remark);
}
}
});
cbScience.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("isChecked6",isChecked+"");
typeId = 6;
if(isChecked){
remark = "add";
type.add(6);
SelectInterestUtil selectInterest = new SelectInterestUtil(SelectInterestActivity.this,getResources().getString(R.string.server_path));
selectInterest.execute(userId, typeId,remark);
}else {
remark = "delete";
int i = type.indexOf(6);
type.remove(i);
SelectInterestUtil selectInterest = new SelectInterestUtil(SelectInterestActivity.this,getResources().getString(R.string.server_path));
selectInterest.execute(userId, typeId,remark);
}
}
});
cbAnime.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("isChecked4",isChecked+"");
typeId = 4;
if(isChecked){
remark = "add";
type.add(4);
SelectInterestUtil selectInterest = new SelectInterestUtil(SelectInterestActivity.this,getResources().getString(R.string.server_path));
selectInterest.execute(userId, typeId,remark);
}else {
remark = "delete";
int i = type.indexOf(4);
type.remove(i);
SelectInterestUtil selectInterest = new SelectInterestUtil(SelectInterestActivity.this,getResources().getString(R.string.server_path));
selectInterest.execute(userId, typeId,remark);
}
}
});
}
private void findViews() {
button = findViewById(R.id.btn_next);
cbBeauty = findViewById(R.id.cb_beauty);
cbTravel = findViewById(R.id.cb_travel);
cbSport = findViewById(R.id.cb_sport);
cbFood = findViewById(R.id.cb_food);
cbScience = findViewById(R.id.cb_science);
cbAnime = findViewById(R.id.cb_anime);
}
/**
* 点击下一步
*/
private class ButtonClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Log.e("type",type+"");
Intent intent = new Intent(SelectInterestActivity.this,SelectTopicActivity.class);
intent.putExtra("userId",userId);
intent.putIntegerArrayListExtra("type",type);
startActivity(intent);
}
}
}
|
package entities;
import java.sql.Timestamp;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import com.fasterxml.jackson.annotation.JsonIgnore;
import interfaces.Activity;
import interfaces.Item;
import interfaces.Request;
import interfaces.Transaction;
@Entity
@Table(name = "item_loan_request")
public class ItemLoanRequest implements Item, Request {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@JsonIgnore
@Fetch(FetchMode.JOIN)
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "timebank_id")
private Timebank itemLoanRequestTimebank;
@JsonIgnore
@Fetch(FetchMode.JOIN)
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "borrower_id")
private User itemLoanRequestUser;
@Fetch(FetchMode.JOIN)
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "category_id")
private ItemCategory itemLoanRequestCategory;
@Fetch(FetchMode.JOIN)
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "subcategory_id")
private ItemSubcategory itemLoanRequestSubcategory;
@Column(name = "days_requested")
private int daysRequested;
private String title;
private String description;
private Timestamp created;
@Column(name = "global_visibility")
private Boolean globalVisibility;
@Column(name = "last_update")
private Timestamp lastUpdate;
@Fetch(FetchMode.JOIN)
@OneToOne(targetEntity = User.class, cascade = CascadeType.PERSIST)
@JoinColumn(name = "last_update_user_id")
private User lastUpdateUser;
private Boolean active;
@Column(name = "moderator_closed")
private Boolean moderatorClosed;
@Fetch(FetchMode.JOIN)
@OneToOne(targetEntity = User.class, cascade = CascadeType.PERSIST)
@JoinColumn(name = "closing_moderator_id")
private User closingModerator;
@JsonIgnore
@Fetch(FetchMode.JOIN)
@OneToMany(mappedBy = "itemLoanRequestActivityParent", cascade = CascadeType.PERSIST)
private List<ItemLoanRequestActivity> itemLoanRequestActivities;
@JsonIgnore
@Fetch(FetchMode.JOIN)
@OneToOne(mappedBy = "itemLoanRequestTxParent", cascade = CascadeType.PERSIST)
private ItemLoanRequestTx itemLoanRequestTx;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Timebank getItemLoanRequestTimebank() {
return itemLoanRequestTimebank;
}
public void setItemLoanRequestTimebank(Timebank itemLoanRequestTimebank) {
this.itemLoanRequestTimebank = itemLoanRequestTimebank;
}
public User getItemLoanRequestUser() {
return itemLoanRequestUser;
}
public void setItemLoanRequestUser(User itemLoanRequestUser) {
this.itemLoanRequestUser = itemLoanRequestUser;
}
public ItemCategory getItemLoanRequestCategory() {
return itemLoanRequestCategory;
}
public void setItemLoanRequestCategory(ItemCategory itemLoanRequestCategory) {
this.itemLoanRequestCategory = itemLoanRequestCategory;
}
public ItemSubcategory getItemLoanRequestSubcategory() {
return itemLoanRequestSubcategory;
}
public void setItemLoanRequestSubcategory(ItemSubcategory itemLoanRequestSubcategory) {
this.itemLoanRequestSubcategory = itemLoanRequestSubcategory;
}
public int getDaysRequested() {
return daysRequested;
}
public void setDaysRequested(int daysRequested) {
this.daysRequested = daysRequested;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getCreated() {
return created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public Boolean getGlobalVisibility() {
return globalVisibility;
}
public void setGlobalVisibility(Boolean globalVisibility) {
this.globalVisibility = globalVisibility;
}
public Timestamp getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Timestamp lastUpdate) {
this.lastUpdate = lastUpdate;
}
public User getLastUpdateUser() {
return lastUpdateUser;
}
public void setLastUpdateUser(User lastUpdateUser) {
this.lastUpdateUser = lastUpdateUser;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Boolean getModeratorClosed() {
return moderatorClosed;
}
public void setModeratorClosed(Boolean moderatorClosed) {
this.moderatorClosed = moderatorClosed;
}
public User getClosingModerator() {
return closingModerator;
}
public void setClosingModerator(User closingModerator) {
this.closingModerator = closingModerator;
}
public List<ItemLoanRequestActivity> getItemLoanRequestActivities() {
return itemLoanRequestActivities;
}
public void setItemLoanRequestActivities(List<ItemLoanRequestActivity> itemLoanRequestActivities) {
this.itemLoanRequestActivities = itemLoanRequestActivities;
}
public ItemLoanRequestTx getItemLoanRequestTx() {
return itemLoanRequestTx;
}
public void setItemLoanRequestTx(ItemLoanRequestTx itemLoanRequestTx) {
this.itemLoanRequestTx = itemLoanRequestTx;
}
@Override
public Timebank getTimebank() {
return this.itemLoanRequestTimebank;
}
@Override
public User getOwner() {
return this.itemLoanRequestUser;
}
@Override
public List<Transaction> getTransactions() {
return null;
}
@Override
public List<Activity> getActivity() {
return null;
}
@Override
public void setTimebank(Timebank timebank) {
this.itemLoanRequestTimebank = timebank;
}
@Override
public void setOwner(User owner) {
this.itemLoanRequestUser = owner;
}
@Override
public ItemCategory getCategory() {
return this.itemLoanRequestCategory;
}
@Override
public void setItemCategory(ItemCategory category) {
this.itemLoanRequestCategory = category;
}
@Override
public ItemSubcategory getSubcategory() {
return this.itemLoanRequestSubcategory;
}
@Override
public void setItemSubcategory(ItemSubcategory subcategory) {
this.itemLoanRequestSubcategory = subcategory;
}
@Override
public void setActivity(List<Activity> activity) {
}
@Override
public void setTransactions(List<Transaction> transactions) {
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((lastUpdate == null) ? 0 : lastUpdate.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ItemLoanRequest other = (ItemLoanRequest) obj;
if (id != other.id)
return false;
if (lastUpdate == null) {
if (other.lastUpdate != null)
return false;
} else if (!lastUpdate.equals(other.lastUpdate))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ItemLoanRequest [id=").append(id).append(", title=").append(title).append(", created=")
.append(created).append(", active=").append(active).append("]");
return builder.toString();
}
}
|
package vlad.fp.services.synchronous.server;
import vlad.fp.services.model.EmailAddress;
import vlad.fp.services.model.Report;
import vlad.fp.services.model.ReportID;
import vlad.fp.services.synchronous.api.EmailService;
import vlad.fp.services.synchronous.api.ReportsService;
import java.util.logging.Logger;
public class EmailServer implements EmailService {
private final ReportsService reportsService;
public EmailServer(ReportsService reportsService) {
this.reportsService = reportsService;
}
@Override
public void sendReport(EmailAddress emailAddress, ReportID reportID) {
reportsService.getReport(reportID);
}
}
|
package org.sbbs.base.pagequery.hibernate;
import org.hibernate.Criteria;
import org.hibernate.Session;
public interface CustomCriteria {
public Criteria getCustomCriteria(Class clazz, Session session)
throws Exception;
}
|
package kevin.jugg.cache_server.mq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import javax.swing.text.TabableView;
import java.util.Arrays;
import java.util.Scanner;
/**
* @ClassName NewTask
* @Description TODO
* @Author Kevin
* @Date 2020/7/8 8:47 上午
* @Version
*/
public class NewTask {
private static final String TASK_QUEUE_NAME = "task_queue";
public static void main(String[] args) {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try {
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
System.out.println("输入要发送的消息以.结尾");
Scanner input = new Scanner(System.in);
String a = input.nextLine();
String[] array = a.split(".");
Arrays.asList(array).stream().forEach(s -> System.out.println(s));
String message = String.join(" ", a);
channel.basicPublish("", TASK_QUEUE_NAME,
MessageProperties.PERSISTENT_TEXT_PLAIN,
message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
} catch (Exception e) {
}
}
}
|
package org.opentosca.portability.service.model;
import java.util.List;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* @author Marcus Eisele - marcus.eisele@gmail.com
*
*/
public class DeploymentArtifact {
private String name;
private String type;
private ArtifactReferences references;
private Document artifactSpecificContent;
protected DeploymentArtifact() {
}
public DeploymentArtifact(String name, String type, ArtifactReferences references) {
super();
this.setName(name);
this.setType(type);
this.setReferences(references);
}
public DeploymentArtifact(String name, String type, List<String> references) {
super();
this.setName(name);
this.setType(type);
this.setReferences(new ArtifactReferences(references));
}
public DeploymentArtifact(String name, String type, Document artifactSpecificContent) {
super();
this.setName(name);
this.setType(type);
this.setArtifactSpecificContent(artifactSpecificContent);
}
public DeploymentArtifact(String name, String type) {
super();
this.setName(name);
this.setType(type);
}
@XmlTransient
public Document getArtifactSpecificContent() {
return artifactSpecificContent;
}
public void setArtifactSpecificContent(Document artifactSpecificContent) {
this.artifactSpecificContent = artifactSpecificContent;
}
@XmlAnyElement(lax = false)
private Element getJaxbArtifactSpecificContent() {
if (artifactSpecificContent == null) {
return null;
}
return this.artifactSpecificContent.getDocumentElement();
}
@XmlAttribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlAttribute
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@XmlElement(name = "references", type = ArtifactReferences.class)
public ArtifactReferences getReferences() {
return references;
}
public void setReferences(ArtifactReferences references) {
this.references = references;
}
}
|
package step._01_IOAndOperations;
/* date : 2021-06-14 (월)
* author : develiberta
* number : 10172
*
* [단계]
* 01. 입출력과 사칙연산
* 입력, 출력과 사칙연산을 연습해 봅시다. Hello World!
* [제목]
* 04. 개 (10172)
* 주어진 예제처럼 출력하는 문제 4
* [문제]
* 아래 예제와 같이 개를 출력하시오.
* [입력]
* 없음
* [출력]
* 개를 출력한다.
* (예제 출력 1)
* |\_/|
* |q p| /}
* ( 0 )"""\
* |"^"` |
* ||_/=\\__|
*/
public class _04_10172_Dog {
public static void main(String[] args) {
System.out.println("|\\_/|");
System.out.println("|q p| /}");
System.out.println("( 0 )\"\"\"\\");
System.out.println("|\"^\"` |");
System.out.println("||_/=\\\\__|");
}
}
|
import java.io.*;
import java.util.*;
//A class used to parse arguments and options entered in the command line programs
public class Administrator implements IAdmin{
//Define the valid options: help, verbose and banner options
public static final Option help = new Option("-h", "-help", "List a summary of all options and their arguments.");
public static final Option verbose = new Option("-v", "-verbose", "Enable verbose output.");
public static final Option banner = new Option("-b" , "-banner", "Print the application's banner.");
public static File srcFile = null;
protected String srcFilename;
private String args[];
public List<String> filesList = new ArrayList<String>(); //A list of all valid files entered by the user
/**
* Administrator constructor
* @param args[] command line arguments array
*/
public Administrator(String[] args) {
this.args = args;
}
/**
* A method to parse the command line arguments array
* @param args[] command line arguments array
* @return boolean, true: valid arguments, false: invalid arguments
*/
public boolean parseOptionsArgs(String args[]) throws IOException {
FileCheck fileChecker = new FileCheck();
if(!checkEmptyArgs(args)) { //Check if user has entered arguments
for(int i = 0; i < args.length; i++) { //loop all arguments, check if it is an option or a file
if (checkOptions(args[i]));
else if(fileChecker.fileExists(args[i], this)); //make process in a separate file
else
return false;
}
return true;
}
else
return false;
}
/**
* A method to check if the argument is an option then enable it and disable the other options
* @param arg : an argument
* @return true if arg is a valid option, false otherwise
*/
public boolean checkOptions(String arg) {
if(help.getOptionVersions().contains(arg)) {
help.setStatus("enabled");
Option.verboseEnabled = false;
banner.setStatus("disabled");
return true;
}
else if(verbose.getOptionVersions().contains(arg)) {
help.setStatus("disabled");
Option.verboseEnabled = true;
banner.setStatus("disabled");
return true;
}
else if(banner.getOptionVersions().contains(arg)) {
help.setStatus("disabled");
Option.verboseEnabled = false;
banner.setStatus("enabled");
return true;
}
return false;
}
/**
* A method to check if arguments array is empty
* @param args
* @return true if args length = 0, false otherwise
*/
public boolean checkEmptyArgs(String [] args) {
return args.length == 0;
}
/**
* A method to return the valid list of files entered by user
* @return String[] files List
*/
public String [] getFilesList() {
return filesList.toArray(new String[filesList.size()]);
}
}
|
package com.tencent.mm.ui.voicesearch;
import com.tencent.mm.aa.q;
import com.tencent.mm.ab.l;
import com.tencent.mm.model.s;
import com.tencent.mm.platformtools.ab;
import com.tencent.mm.plugin.messenger.a.f;
import com.tencent.mm.protocal.c.biy;
import com.tencent.mm.protocal.c.bja;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.LinkedList;
class b$3 implements Runnable {
final /* synthetic */ l bFp;
final /* synthetic */ b uFM;
b$3(b bVar, l lVar) {
this.uFM = bVar;
this.bFp = lVar;
}
public final void run() {
bja bcS = ((f) this.bFp).bcS();
x.d("MicroMsg.SearchResultAdapter", "count " + bcS.rHb);
if (bcS.rHb > 0) {
for (biy biy : bcS.rHc) {
if (s.gU(biy.rTe)) {
if (b.f(this.uFM) == null) {
b.a(this.uFM, new LinkedList());
}
b.f(this.uFM).add(biy);
}
}
} else {
String a = ab.a(bcS.rvi);
x.d("MicroMsg.SearchResultAdapter", "user " + a);
if (bi.oV(a).length() > 0) {
biy biy2 = new biy();
biy2.rvi = bcS.rvi;
biy2.rTe = bcS.rTe;
biy2.eJK = bcS.eJK;
biy2.rQz = bcS.rQz;
biy2.eJM = bcS.eJM;
biy2.eJQ = bcS.eJQ;
biy2.eJJ = bcS.eJJ;
biy2.eJI = bcS.eJI;
biy2.eJH = bcS.eJH;
biy2.rTf = bcS.rTf;
biy2.rTi = bcS.rTi;
biy2.rTg = bcS.rTg;
biy2.rTh = bcS.rTh;
biy2.rTk = bcS.rTk;
q.Kp().g(a, ab.a(bcS.rcn));
if (b.f(this.uFM) == null) {
b.a(this.uFM, new LinkedList());
}
b.f(this.uFM).clear();
if (s.gU(biy2.rTe)) {
b.f(this.uFM).add(biy2);
}
x.d("MicroMsg.SearchResultAdapter", "count " + b.f(this.uFM).size());
}
}
b.b(this.uFM, false);
}
}
|
package info.ntek.gsp.data.time;
import info.ntek.gsp.data.ScheduleItem;
import java.util.ArrayList;
/**
* @author Milos Milanovic
*/
public class TimeItem extends ScheduleItem {
private ArrayList<HourItem> mHourItems = null;
public TimeItem(String timeID, ArrayList<HourItem> hourItems) {
super(timeID);
mHourItems = hourItems;
}
public ArrayList<HourItem> getHourItems() {
return mHourItems;
}
@Override
public String toString() {
return TimeType.fromValue(Integer.valueOf(getValue())) + " " + mHourItems;
}
}
|
package listexer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
public class CollectionTest {
@Test
public void test1(){
Collection coll = new ArrayList();
//add(Object e)增加对象
coll.add(123);
coll.add(456);
coll.add(789);
coll.add("adv");
System.out.println(coll);
//size()获取个数
System.out.println(coll.size());
//addAll(Collection coll1)
Collection coll1 = Arrays.asList(456,789,002);
coll.addAll(coll1);
System.out.println(coll.size());
}
@Test
public void test2(){
Collection coll = new ArrayList();
Collection coll1 = Arrays.asList(456,789,002);
//clear()清除
// coll1.clear();
//isEmpty()是否为空
System.out.println(coll1.isEmpty());
//contains(Object obj)包含
boolean contains = coll.contains(456);
System.out.println(contains);
//containsAll(Collection coll1)
System.out.println(coll.containsAll(coll1));
}
@Test
public void test3(){
Collection coll = new ArrayList();
Collection coll1 = Arrays.asList(456,789,002);
//remove(Object obj)移除一个obj
//removeAll(Collection coll1)移除coll1
//retainAll(Collection coll1)求交集
//equals(Object obj)要想返回true,需要当前集合和形参集合的元素都相同
//hashcode()返回当前的哈希值
int code = coll.hashCode();
System.out.println(code);
System.out.println("============");
//集合-->数组:toArray()
Object[] array = coll.toArray();
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
//数组-->集合:asList()
List list = Arrays.asList(new int[]{123,456});
System.out.println(list.size());
System.out.println(list);
List list1 = Arrays.asList(new Integer[]{123,456});
System.out.println(list1);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.