text
stringlengths 10
2.72M
|
|---|
package com.goldgov.dygl.module.portal.webservice.deptuserscore.impl;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.goldgov.dygl.module.portal.webservice.deptuserscore.DeptUserScoreInfo;
import com.goldgov.dygl.module.portal.webservice.deptuserscore.DeptUserScoreInfoWebserviceServiceService;
import com.goldgov.dygl.module.portal.webservice.deptuserscore.ExamRecordQueryCommond;
import com.goldgov.dygl.module.portal.webservice.deptuserscore.bean.DeptCourseQueryBean;
import com.goldgov.dygl.module.portal.webservice.deptuserscore.bean.ExamRecordQueryBean;
@Service("deptUserScoreService")
public class DeptUserScoreService {
@Autowired
@Qualifier("propertiesReader")
private Properties prop;
public DeptUserScoreInfo getService(){
URL url = null;
try {
String el = prop.getProperty("el.domain");
url = new URL(el+"/webservice/deptuserscorewebservice?wsdl");
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
DeptUserScoreInfoWebserviceServiceService deptUserScoreInfoWebserviceServiceService = new DeptUserScoreInfoWebserviceServiceService(url);
DeptUserScoreInfo deptUserScoreInfoService = deptUserScoreInfoWebserviceServiceService.getDeptUserScoreInfoPort();
return deptUserScoreInfoService;
}
public List<ExamRecordQueryBean> queryDeptUserScoreInfo(ExamRecordQueryCommond query){
try {
String json = getService().queryDeptUserScoreInfo(query);
ObjectMapper mapper = new ObjectMapper();
DeptCourseQueryBean readValue = mapper.readValue(json, DeptCourseQueryBean.class);
return readValue.getExamRecord();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
ExamRecordQueryCommond query = new ExamRecordQueryCommond();
query.setSearchDeptId("-1");
query.setSearchCourseId("COURSETREE_01001_05");
//COURSETREE_01001_03,COURSETREE_01001_04,COURSETREE_01001_05
try {
String json = new DeptUserScoreService().getService().queryDeptUserScoreInfo(query);
ObjectMapper mapper = new ObjectMapper();
DeptCourseQueryBean readValue = mapper.readValue(json, DeptCourseQueryBean.class);
System.out.println(json);
System.out.println(readValue);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.hx.controller;
import javax.servlet.http.HttpSession;
import com.hx.entity.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.github.pagehelper.PageInfo;
import com.hx.config.Log;
import com.hx.entity.CementStrength;
import com.hx.entity.User;
import com.hx.model.BusinessType;
import com.hx.model.MainDataModel;
import com.hx.model.Response;
import com.hx.service.CementStrengthService;
@Controller
@RequestMapping(value = "/cement")
public class CementStrengthController {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
CementStrengthService cementStrengthService;
@GetMapping(value = "/getByPage")
public ModelAndView findByPage(MainDataModel model){
//pageNum 当前页 pageSize 每页的数量 size 当前页的数量
Integer pageNum1 = model.getPageNum();
int pageNum=(pageNum1==null)?1:pageNum1;
Integer pageSize1 = model.getPageSize();
int pageSize=(pageSize1==null)?10:pageSize1;
Integer status = model.getStatus();
String sampleNo = model.getCondition();
PageInfo<CementStrength> pageInfo = cementStrengthService.findByPage(pageNum, pageSize,status,sampleNo);
ModelAndView mv = new ModelAndView("list");
mv.addObject("pageInfo",pageInfo);
mv.addObject("requestModel",model);
return mv;
}
/* public ModelAndView findByPage(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum ){
Integer pageSize=18;//pageNum 当前页 pageSize 每页的数量 size 当前页的数量
PageInfo<CementStrength> pageInfo = cementStrengthService.findByPage(pageNum, pageSize);
ModelAndView mv = new ModelAndView("list");
mv.addObject("pageInfo",pageInfo);
return mv;
}*/
@PostMapping(value = "/getDataByPage")
@ResponseBody
public Response getDataByPage(MainDataModel model) {
logger.debug("数据查询:");
Response response = null;
try {
Integer pageNum = model.getPageNum();
Integer pageSize = model.getPageSize();
Integer status = model.getStatus();
String sampleNo = model.getCondition();
PageInfo<CementStrength> pageInfo = cementStrengthService.findByPage(pageNum, pageSize,status,sampleNo);
response = new Response(200,null,pageInfo,model);
}catch (Exception e){
e.printStackTrace();
response = new Response(500,null,null,model);
}
return response;
}
/**
* 水泥强度数据同步
* @param session
* @return
*/
@ResponseBody
@PostMapping(value = "/synchronize")
@Log(businessModule = "水泥强度", businessType = BusinessType.SYNCHRONIZE)
public Response dataSynchronize(HttpSession session) {
logger.info("同步数据开始.....");
// SysUser user = (SysUser) session.getAttribute("USER_SESSION");
boolean result = cementStrengthService.dataSynchronize();
logger.info("同步数据结束......");
Response response = null;
if(result){
response = new Response(200,"success");
}else {
response = new Response(500,"fail");
}
return response;
}
/**
* 水泥强度:数据上传
* @param session
* @param ids
* @return
*/
@PostMapping(value = "/upload")
@ResponseBody
@Log(businessModule = "水泥强度", businessType = BusinessType.UPLOAD)
public Response calculateAndCreateFile(HttpSession session, String[] ids){
logger.info("开始上传数据生成文件...");
logger.debug("param ids.size():" + ids.length);
User user = (User)session.getAttribute("USER_SESSION");
boolean result = cementStrengthService.createFile(ids);
logger.info("数据上传完成...");
Response response = null;
if(result){
response = new Response(200,"success");
}else {
response = new Response(500,"fail");
}
return response;
}
}
|
package io.github.wickhamwei.wessential.eventlistener;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
import java.util.Objects;
public class CreeperListener implements Listener {
@EventHandler
public void creeperExplode(EntityExplodeEvent event) {
if (event.getEntityType().equals(EntityType.CREEPER)) {
Objects.requireNonNull(event.getLocation().getWorld()).playSound(event.getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 1, 0);
event.setCancelled(true);
}
}
}
|
package cn.izouxiang.rpc.service.api;
import cn.izouxiang.domain.RedEnvelope;
import cn.izouxiang.rpc.service.api.base.BaseService;
public interface RedEnvelopeService extends BaseService<RedEnvelope> {
}
|
package com.tencent.mm.ui.widget.sortlist;
import android.graphics.Point;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
public final class a extends d implements OnGestureListener, OnTouchListener {
private int fW;
private int gbM;
private int gbN;
private int ioh;
private GestureDetector uG;
private int uMT = 0;
boolean uMU = true;
boolean uMV = false;
private boolean uMW = false;
private GestureDetector uMX;
private int uMY = -1;
private int uMZ = -1;
private int uNa = -1;
private int[] uNb = new int[2];
private int uNc;
private int uNd;
private boolean uNe = false;
private float uNf = 500.0f;
private int uNg;
private int uNh;
private int uNi;
private boolean uNj;
private DragSortListView uNk;
private int uNl;
private OnGestureListener uNm = new 1(this);
public a(DragSortListView dragSortListView, int i, int i2, int i3, int i4, int i5) {
super(dragSortListView);
this.uNk = dragSortListView;
this.uG = new GestureDetector(dragSortListView.getContext(), this);
this.uMX = new GestureDetector(dragSortListView.getContext(), this.uNm);
this.uMX.setIsLongpressEnabled(false);
this.fW = ViewConfiguration.get(dragSortListView.getContext()).getScaledTouchSlop();
this.uNg = i;
this.uNh = i4;
this.uNi = i5;
this.ioh = i3;
this.uMT = i2;
}
private boolean as(int i, int i2, int i3) {
int i4;
int i5;
boolean z = false;
if (!this.uMU || this.uMW) {
i4 = 0;
} else {
i4 = 12;
}
if (this.uMV && this.uMW) {
i5 = (i4 | 1) | 2;
} else {
i5 = i4;
}
DragSortListView dragSortListView = this.uNk;
int headerViewsCount = i - this.uNk.getHeaderViewsCount();
if (dragSortListView.uNZ && dragSortListView.uOa != null) {
View GK = dragSortListView.uOa.GK(headerViewsCount);
if (GK != null) {
z = dragSortListView.a(headerViewsCount, GK, i5, i2, i3);
}
}
this.uNe = z;
return this.uNe;
}
public final boolean onTouch(View view, MotionEvent motionEvent) {
if (this.uNk.uNF && !this.uNk.uOp) {
this.uG.onTouchEvent(motionEvent);
if (this.uMV && this.uNe && this.ioh == 1) {
this.uMX.onTouchEvent(motionEvent);
}
switch (motionEvent.getAction() & 255) {
case 0:
this.gbM = (int) motionEvent.getX();
this.gbN = (int) motionEvent.getY();
break;
case 1:
if (this.uMV && this.uMW) {
if ((this.uNl >= 0 ? this.uNl : -this.uNl) > this.uNk.getWidth() / 2) {
this.uNk.aE(0.0f);
break;
}
}
break;
case 3:
this.uMW = false;
this.uNe = false;
break;
}
}
return false;
}
public final void i(Point point) {
if (this.uMV && this.uMW) {
this.uNl = point.x;
}
}
private int k(MotionEvent motionEvent, int i) {
int pointToPosition = this.uNk.pointToPosition((int) motionEvent.getX(), (int) motionEvent.getY());
int headerViewsCount = this.uNk.getHeaderViewsCount();
int footerViewsCount = this.uNk.getFooterViewsCount();
int count = this.uNk.getCount();
if (pointToPosition != -1 && pointToPosition >= headerViewsCount && pointToPosition < count - footerViewsCount) {
View childAt = this.uNk.getChildAt(pointToPosition - this.uNk.getFirstVisiblePosition());
count = (int) motionEvent.getRawX();
int rawY = (int) motionEvent.getRawY();
View findViewById = i == 0 ? childAt : childAt.findViewById(i);
if (findViewById != null) {
findViewById.getLocationOnScreen(this.uNb);
if (count > this.uNb[0] && rawY > this.uNb[1] && count < this.uNb[0] + findViewById.getWidth()) {
if (rawY < findViewById.getHeight() + this.uNb[1]) {
this.uNc = childAt.getLeft();
this.uNd = childAt.getTop();
return pointToPosition;
}
}
}
}
return -1;
}
public final boolean onDown(MotionEvent motionEvent) {
int i = -1;
if (this.uMV && this.ioh == 0) {
this.uNa = k(motionEvent, this.uNh);
}
this.uMY = k(motionEvent, this.uNg);
if (this.uMY != -1 && this.uMT == 0) {
as(this.uMY, ((int) motionEvent.getX()) - this.uNc, ((int) motionEvent.getY()) - this.uNd);
}
this.uMW = false;
this.uNj = true;
this.uNl = 0;
if (this.ioh == 1) {
i = k(motionEvent, this.uNi);
}
this.uMZ = i;
return true;
}
public final boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent2, float f, float f2) {
int x = (int) motionEvent.getX();
int y = (int) motionEvent.getY();
int x2 = (int) motionEvent2.getX();
int y2 = (int) motionEvent2.getY();
int i = x2 - this.uNc;
int i2 = y2 - this.uNd;
if (!(!this.uNj || this.uNe || (this.uMY == -1 && this.uMZ == -1))) {
if (this.uMY != -1) {
if (this.uMT == 1 && Math.abs(y2 - y) > this.fW && this.uMU) {
as(this.uMY, i, i2);
} else if (this.uMT != 0 && Math.abs(x2 - x) > this.fW && this.uMV) {
this.uMW = true;
as(this.uMZ, i, i2);
}
} else if (this.uMZ != -1) {
if (Math.abs(x2 - x) > this.fW && this.uMV) {
this.uMW = true;
as(this.uMZ, i, i2);
} else if (Math.abs(y2 - y) > this.fW) {
this.uNj = false;
}
}
}
return false;
}
public final void onLongPress(MotionEvent motionEvent) {
if (this.uMY != -1 && this.uMT == 2) {
this.uNk.performHapticFeedback(0);
as(this.uMY, this.gbM - this.uNc, this.gbN - this.uNd);
}
}
public final boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent2, float f, float f2) {
return false;
}
public final boolean onSingleTapUp(MotionEvent motionEvent) {
if (this.uMV && this.ioh == 0 && this.uNa != -1) {
DragSortListView dragSortListView = this.uNk;
int headerViewsCount = this.uNa - this.uNk.getHeaderViewsCount();
dragSortListView.uOn = false;
dragSortListView.k(headerViewsCount, 0.0f);
}
return true;
}
public final void onShowPress(MotionEvent motionEvent) {
}
}
|
package co.aurasphere.courseware.java.jaxb;
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.StringWriter;
import java.net.URL;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
import co.aurasphere.courseware.java.jaxb.model.PeopleList;
public class JaxbDemo {
private static JAXBContext context;
private static StringWriter writer;
public static void writeXml(Object object, String filename) throws IOException, JAXBException {
context.createMarshaller().marshal(object, writer);
BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
bw.write(writer.toString());
bw.flush();
bw.close();
}
public static PeopleList readXml(String filename) throws JAXBException, FileNotFoundException {
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
return (PeopleList) context.createUnmarshaller().unmarshal(br);
}
private static void validateXml(String filename, File schemaFile) throws IOException, SAXException {
Source xmlFile = new StreamSource(new File(filename));
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new StreamSource(schemaFile));
Validator validator = schema.newValidator();
try {
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is invalid: " + e.getLocalizedMessage());
}
}
public static void main(String[] args) throws JAXBException, IOException, SAXException {
context = JAXBContext.newInstance(PeopleList.class);
writer = new StringWriter();
URL inputXml = JaxbDemo.class.getClassLoader().getResource("people-list.xml");
String inputXmlFileName = inputXml.getFile();
String outputXmlFileName = "C:/output.xml";
URL xmlSchema = JaxbDemo.class.getClassLoader().getResource("people-list-schema.xsd");
File xmlSchemaFile = new File(xmlSchema.getFile());
validateXml(inputXmlFileName, xmlSchemaFile);
PeopleList list = readXml(inputXmlFileName);
System.out.println(list);
writeXml(list, outputXmlFileName);
}
}
|
package com.sdl.webapp.common.controller;
/**
* <p>RequestAttributeNames interface.</p>
*/
public interface RequestAttributeNames {
/**
* Constant <code>PAGE_MODEL="pageModel"</code>
*/
String PAGE_MODEL = "pageModel"; // NOTE: Cannot be "page" because that interferes with the built-in "page" variable in JSPs
/**
* Constant <code>REGION_MODEL="region"</code>
*/
String REGION_MODEL = "region";
/** Constant <code>ENTITY_MODEL="entity"</code> */
String ENTITY_MODEL = "entity";
/** Constant <code>PAGE_ID="pageId"</code> */
String PAGE_ID = "pageId";
/** Constant <code>LOCALIZATION="localization"</code> */
String LOCALIZATION = "localization";
/** Constant <code>MARKUP="markup"</code> */
String MARKUP = "markup";
/** Constant <code>MEDIAHELPER="mediaHelper"</code> */
String MEDIAHELPER = "mediaHelper";
/** Constant <code>SCREEN_WIDTH="screenWidth"</code> */
String SCREEN_WIDTH = "screenWidth";
/** Constant <code>SOCIALSHARE_URL="socialshareUrl"</code> */
String SOCIALSHARE_URL = "socialshareUrl";
/** Constant <code>CONTEXTENGINE="contextengine"</code> */
String CONTEXTENGINE = "contextengine";
}
|
package com.dh.Services;
import com.dh.JavaBean.*;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public interface AdminServices {
Admin login(String name, String password);
void adminRelease(Recruit recruit);
List<remuse> findAllremuse();
remuse findremusebyid(Integer id);
User findUserbyname(String username);
void deleteremuse(Integer id);
void updateRemuseStruts(Integer id);
void updateUser(Integer uid);
List<User> findUserbyStruts();
void addDept(String deptname, Date date);
List<Dept> selectDept();
void addPosi(Integer deptid, String posiname);
User findUserByid(Integer uid);
List<posi> findPosiBydeptid(Integer deptid);
void updateEmployeeBydept(String username, Integer deptid, Integer posiid);
List<UserDetils> findEmployeeBydeptandposi(Integer dept, Integer posi);
List<UserDetils> findEmplyBydeptid(Integer dept);
void updateStruts(User user);
void saveCadets(Cadets cadets);
List<EmployeePay> selectClocking();
List<posi> SelectAllPosi();
void updateDeptname(String updateDeptname, Integer deptid);
void updatePosi(String updatePosiname, Integer posiid);
boolean deleteDept(Integer deptid);
boolean deletePosi(Integer posiid);
}
|
package com.design.state;
public class TVRemoteClient {
public static void main(String[] args) {
PdkContext context = new PdkContext();
PdkState tvStartState = new TVStartState();
PdkState tvStopState = new TVStopState();
context.setState(tvStartState);
context.doAction();
context.setState(tvStopState);
context.doAction();
}
}
|
package com.lrs.admin.service;
import java.util.Map;
import com.lrs.admin.util.ParameterMap;
public interface IEsotericaService {
public Map<String,Object> save(ParameterMap pm);
public Map<String,Object> find(ParameterMap pm);
public Map<String,Object> del(ParameterMap pm);
public Map<String,Object> update(ParameterMap pm);
public Map<String,Object> getSpeechraftList(ParameterMap pm);
}
|
package com.timmy.advance.animation;
import android.os.Bundle;
import com.timmy.R;
import com.timmy.base.BaseActivity;
public class RubberIndicatiorActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rubber_indicatior);
}
}
|
package com.tencent.mm.an;
import com.tencent.mm.g.a.js;
import com.tencent.mm.protocal.c.avq;
import com.tencent.mm.sdk.b.a;
import com.tencent.mm.sdk.platformtools.ah;
import java.util.List;
public final class b {
/* renamed from: com.tencent.mm.an.b$7 */
static class AnonymousClass7 implements Runnable {
final /* synthetic */ List ebc;
final /* synthetic */ int ebd;
public AnonymousClass7(List list, int i) {
this.ebc = list;
this.ebd = i;
}
public final void run() {
js jsVar = new js();
jsVar.bTw.action = 0;
jsVar.bTw.bPa = this.ebc;
jsVar.bTw.bTz = this.ebd;
a.sFg.m(jsVar);
}
}
public static final void yL() {
ah.A(new 1());
}
public static final void yM() {
ah.A(new 2());
}
public static final void PW() {
ah.A(new 3());
}
public static final void PX() {
ah.A(new 4());
}
public static final void a(avq avq) {
ah.A(new 5(avq));
}
public static boolean PY() {
js jsVar = new js();
jsVar.bTw.action = -3;
a.sFg.m(jsVar);
return jsVar.bTx.bGZ;
}
public static boolean PZ() {
js jsVar = new js();
jsVar.bTw.action = 9;
a.sFg.m(jsVar);
return jsVar.bTx.bGZ;
}
public static avq Qa() {
js jsVar = new js();
jsVar.bTw.action = -2;
a.sFg.m(jsVar);
return jsVar.bTx.bTy;
}
public static void b(avq avq) {
ah.A(new 6(avq));
}
public static void c(avq avq) {
ah.A(new 8(avq));
}
public static boolean d(avq avq) {
if (avq == null) {
return false;
}
switch (avq.rYj) {
case 1:
case 8:
case 9:
return true;
default:
return false;
}
}
public static boolean if(int i) {
js jsVar = new js();
jsVar.bTw.action = 7;
jsVar.bTw.position = i;
a.sFg.m(jsVar);
return jsVar.bTx.bGZ;
}
public static d Qb() {
js jsVar = new js();
jsVar.bTw.action = 8;
a.sFg.m(jsVar);
return jsVar.bTx.bTC;
}
}
|
package amu.electrical.deptt.utils;
public class FacultyMember {
protected String name, designation, responsibility, mobile, intext;
public FacultyMember() {
}
public FacultyMember(String name, String designation, String responsibility, String mobile, String intext) {
this.name = name;
this.designation = designation;
this.responsibility = responsibility;
this.mobile = mobile;
this.intext = intext;
}
}
|
package com.osce;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @ClassName: OsceServiceBoot
* @Description: service启动类
* @Author yangtongbin
* @Date 2019-05-01
*/
@EnableDubbo
@SpringBootApplication(scanBasePackages = { "com.osce.*"})
@MapperScan(value = "com.osce.orm.*")
public class OsceService {
public static void main(String[] args) {
SpringApplication.run(OsceService.class, args);
}
}
|
package classes;
public final class Constants {
private Constants() {}
public static final String databaseName = "daviddb"; // The name of the database. Can be changed as necessary.
public static final String userCollection = "users"; // The name of the user collection.
public static final String userIDField = "unique_id"; // The name of the ID field in the userCollection.
public static final String userPrefs = "favorites"; // The name of the array of a user's favorite itemID's.
public static final String itemCollection = "movies"; // Because the test case uses movies.
public static final String itemIDField = "movie_id"; // The name of the ID field in the itemCollection.
public static final String itemName = "title"; // Again because the example uses movies.
public static final String itemCategory = "genre"; // Identify what type of item we're dealing with.
public static final String mongoClient = "mongo"; // The name of the MongoClient.
public static final int numberOfRecommendations = 9; // Relatively small number to ensure good recs.
}
|
package com.cskaoyan.service.impl;
import com.cskaoyan.bean.MaterialMessage;
import com.cskaoyan.mapper.MaterialMessageMapper;
import com.cskaoyan.service.MaterialMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MaterialMessageServiceImpl implements MaterialMessageService {
private MaterialMessageMapper mapper;
@Autowired
public MaterialMessageServiceImpl(MaterialMessageMapper mapper) {
this.mapper = mapper;
}
@Override
public List<MaterialMessage> queryAllMaterialMessage() {
return mapper.queryAllMaterialMessage();
}
@Override
public boolean insertMaterialMessage(MaterialMessage materialMessage) {
System.out.println(materialMessage);
boolean b = mapper.inserMaterialMessage(materialMessage);
return b;
}
@Override
public List<MaterialMessage> queryMaterialById(String searchValue) {
List<MaterialMessage> list = mapper.queryMaterialById(searchValue);
return list;
}
@Override
public List<MaterialMessage> queryMaterialByType(String searchValue) {
List<MaterialMessage> list = mapper.queryMaterialByType(searchValue);
return list;
}
@Override
public int deleteMaterialById(String[] ids) {
mapper.deleteMaterialById(ids,ids.length);
return 111;
}
@Override
public int materialEdit(MaterialMessage materialMessage) {
mapper.materialEdit(materialMessage);
return 0;
}
}
|
package io.github.vibrouter;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import io.github.vibrouter.databinding.ActivityMainBinding;
import io.github.vibrouter.fragments.NavigationFragment;
import io.github.vibrouter.managers.MainService;
public abstract class BaseActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = BaseActivity.class.getSimpleName();
private final int UI_VISIBILITY_FLAGS = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
ActivityMainBinding mBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
getWindow().getDecorView().setSystemUiVisibility(UI_VISIBILITY_FLAGS);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mBinding.drawerLayout, null, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mBinding.drawerLayout.addDrawerListener(toggle);
toggle.syncState();
mBinding.navView.setNavigationItemSelectedListener(this);
changeFragmentTo(new NavigationFragment());
Intent intent = new Intent(this, MainService.class);
startService(intent);
}
@Override
protected void onDestroy() {
mBinding = null;
super.onDestroy();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
this.getWindow().getDecorView().setSystemUiVisibility(UI_VISIBILITY_FLAGS);
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = mBinding.drawerLayout;
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void changeFragmentTo(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
|
package com.fleet.file.controller;
import com.fleet.file.config.FileConfig;
import com.fleet.file.entity.MultipartFileParam;
import com.fleet.file.json.R;
import com.fleet.file.service.StorageService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.File;
/**
* @author April Han
*/
@RestController
@RequestMapping(value = "/bigFile")
public class BigFileController {
private static final Logger logger = LoggerFactory.getLogger(BigFileController.class);
@Resource
private StorageService storageService;
@Resource
FileConfig fileConfig;
/**
* 秒传判断,断点判断
*/
@RequestMapping("/checkFile")
public R checkFile(String md5) throws Exception {
File md5Dir = new File(fileConfig.getBigFilePath() + md5);
if (!md5Dir.exists()) {
return R.ok(101, "未上传");
}
// status 进度文件分片记录上传进度
File status = new File(fileConfig.getBigFilePath() + md5 + File.separatorChar + "status");
byte[] bytes = FileUtils.readFileToByteArray(status);
for (byte b : bytes) {
if (b != Byte.MAX_VALUE) {
return R.ok(101, "未上传");
}
}
return R.ok(100, "已上传");
}
/**
* 上传文件
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(MultipartFileParam param) {
try {
// 方法1
// storageService.uploadFileByRandomAccessFile(param);
// 方法2 这个更快点
storageService.uploadFileByMappedByteBuffer(param);
} catch (Exception e) {
e.printStackTrace();
logger.error("文件上传失败。{}", param.toString());
return "失败";
}
return "成功";
}
}
|
import java.util.LinkedList;
import java.util.Queue;
import java.util.Vector;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class GasStation extends Thread {
private Lock noFreePumpLock = new ReentrantLock();
private Condition noFreePump = noFreePumpLock.newCondition();
private MainFuelPool mainFuelPool = new MainFuelPool();
private CleaningService cleaningService = new CleaningService();
//private Queue<Car> fuelWaitingList;
private Queue<FuelPump> freePumps;
private Vector<GasStationModelListener> listeners;
public GasStation(int numOfPumps) {
//fuelWaitingList = new LinkedList<Car>();
freePumps = new LinkedList<FuelPump>();
listeners = new Vector<GasStationModelListener>();
for (int i=0;i<numOfPumps;i++)
freePumps.add(new FuelPump());
}
public void registerListener(GasStationModelListener gasStationListener) {
listeners.add(gasStationListener);
}
@Override
public void run() {
//needed???????
}
public FuelPump getFreePump() throws Exception{
// TODO Auto-generated method stub
noFreePumpLock.lock();
FuelPump pump=freePumps.poll();
while(pump==null){
System.out.println("waiting for fuel pump");
noFreePump.await();
System.out.println("waking up for fuel pump");
pump = freePumps.poll();
}
noFreePumpLock.unlock();
return pump;
}
public void releasePump(FuelPump fuelPump) {
// TODO Auto-generated method stub
noFreePumpLock.lock();
freePumps.add(fuelPump);
noFreePump.signal();
noFreePumpLock.unlock();
}
public MainFuelPool getMainFuelPool() {
return mainFuelPool;
}
public void setMainFuelPool(MainFuelPool mainFuelPool) {
this.mainFuelPool = mainFuelPool;
}
public CleaningService getCleaningService() {
return cleaningService;
}
public void setCleaningService(CleaningService cleaningService) {
this.cleaningService = cleaningService;
}
public synchronized void addCarTModel(int licensePlate, int numOfLiters,
boolean wantWash) {
// TODO Auto-generated method stub
Car car = new Car(licensePlate, numOfLiters, wantWash, this);
//fuelWaitingList.add(car);
car.start();
System.out.println("in model");
this.notify();
}
// public synchronized void notifyCar() {
// Car firstCar = fuelWaitingList.poll();
// System.out.println("car wants" + firstCar.getNumOfLiters());
// if (firstCar != null) {
// System.out.println("Gas Station is notifying car #"
// + firstCar.getId());
// synchronized (firstCar) {
// firstCar.notifyAll();
// }
// }
//
// }
}
|
package jp.co.tau.web7.admin.supplier.dto;
import lombok.Getter;
import lombok.Setter;
/**
* <p>ファイル名 : InfoCarDTO</p>
* <p>説明 : InfoCarDTO</p>
* @author hung.pd
* @since : 2018/05/31
*/
@Getter
@Setter
public class InfoCarDTO {
/**メーカーコード*/
private String mkCd;
/** メーカー */
private String mkNm;
/**モデルコード*/
private String mdCd;
/** モデル */
private String mdNm;
/**グレードコード*/
private String gdCd;
/** グレード */
private String gdNm;
/** 初年度登録年 */
private String fstRegYy;
/** 形式 */
private String inspMd;
/** 形式指定 */
private String inspMdSpecificationNo;
/** 類別番号 */
private String classificationNo;
/** 排気量 */
private String displacement;
/** エンジン形式 */
private String engineInspMd;
/**使用燃料種別コード*/
private String fuelTypeCd;
/** 燃料 */
private String fuelTypeNm;
/**車台番号*/
private String chassisNo;
/** シリアル番号 */
private String serialNo;
/** 走行距離 */
private String runningMileage;
/**カラーコード*/
private String colorCd;
/** 色 */
private String colorNm;
/**ハンドル種別コード*/
private String steeringWheelTypeCd;
/**ハンドル*/
private String steeringWheelTypeNm;
/**走行条件コード*/
private String runningConditionCd;
/**走行条件*/
private String runningConditionNm;
/**駆動方式区分コード*/
private String driveSysDivCd;
/**駆動方式*/
private String driveSysDivNm;
/**積込程度自走可*/
private String drvCanBeLoadedFlg;
/**トランスミッション種別コード*/
private String transmissionTypeCd;
/** 変速機 */
private String transmissionTypeNm;
/**入庫予定先*/
private String delvSpBaseCd;
/** 乗車定員 */
private String capacity;
/** リサイクル料金 */
private String recycleChargeDivCd;
/** 書類有無 */
private String supplierDocClsCd;
/** 車検期限 */
private String inspLmtYy;
/** inspLmtMm*/
private String inspLmtMm;
/** 長さ */
private String length;
/** 最大積載量 */
private String maxCarryKg;
/** 幅 */
private String width;
/** 車両重量 */
private String carWeightKg;
/** 高さ */
private String high;
/** 車両総重量 */
private String carGrossWeight;
/** file image name */
private String atta;
/** directory image */
private String attaDir;
}
|
package com.tencent.mm.plugin.appbrand.jsapi;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.util.Log;
import android.view.View;
import com.tencent.mm.plugin.appbrand.canvas.widget.a;
import com.tencent.mm.plugin.appbrand.jsapi.coverview.CoverViewContainer;
import com.tencent.mm.plugin.appbrand.l;
import com.tencent.mm.plugin.appbrand.page.p;
import com.tencent.mm.plugin.appbrand.q.c;
import com.tencent.mm.plugin.appbrand.q.f;
import com.tencent.mm.plugin.appbrand.r.m;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.smtt.sdk.WebView;
import java.nio.ByteBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public final class t extends a {
public static final int CTRL_INDEX = 373;
public static final String NAME = "canvasPutImageData";
public final void a(l lVar, JSONObject jSONObject, int i) {
super.a(lVar, jSONObject, i);
try {
int i2 = jSONObject.getInt("canvasId");
p d = d(lVar);
if (d == null) {
x.w("MicroMsg.JsApiCanvasPutImageData", "invoke JsApi canvasGetImageData failed, current page view is null.");
lVar.E(i, f("fail:page is null", null));
return;
}
View lx = d.agU().lx(i2);
if (lx == null) {
x.w("MicroMsg.JsApiCanvasPutImageData", "view(%s) is null.", new Object[]{Integer.valueOf(i2)});
lVar.E(i, f("fail:view is null", null));
} else if (lx instanceof CoverViewContainer) {
View A = ((CoverViewContainer) lx).A(View.class);
if (A instanceof a) {
float aor = f.aor();
int optInt = jSONObject.optInt("x");
int optInt2 = jSONObject.optInt("y");
int optInt3 = jSONObject.optInt("width");
int optInt4 = jSONObject.optInt("height");
Math.round(((float) optInt) * aor);
Math.round(((float) optInt2) * aor);
Math.round(((float) optInt3) * aor);
Math.round(aor * ((float) optInt4));
if (optInt3 == 0 || optInt4 == 0) {
x.i("MicroMsg.JsApiCanvasPutImageData", "width(%s) or height(%s) is 0.(%s)", new Object[]{Integer.valueOf(optInt3), Integer.valueOf(optInt4), Integer.valueOf(i2)});
lVar.E(i, f("fail:width or height is 0", null));
return;
}
if (optInt3 < 0) {
optInt += optInt3;
i2 = -optInt3;
} else {
i2 = optInt3;
}
if (optInt4 < 0) {
optInt2 += optInt4;
optInt3 = -optInt4;
} else {
optInt3 = optInt4;
}
m.a(lVar, jSONObject, this);
try {
Object obj = jSONObject.get("data");
if (obj instanceof ByteBuffer) {
ByteBuffer byteBuffer = (ByteBuffer) obj;
JSONArray jSONArray = new JSONArray();
int[] h = h(byteBuffer);
JSONObject jSONObject2 = new JSONObject();
try {
JSONArray jSONArray2 = new JSONArray();
jSONArray2.put(optInt);
jSONArray2.put(optInt2);
jSONArray2.put(i2);
jSONArray2.put(optInt3);
jSONArray2.put(Bitmap.createBitmap(h, i2, optInt3, Config.ARGB_8888));
jSONObject2.put("method", "__setPixels");
jSONObject2.put("data", jSONArray2);
jSONArray.put(jSONObject2);
a aVar = (a) A;
aVar.b(jSONArray, new 1(this, lVar, i));
aVar.adk();
return;
} catch (JSONException e) {
x.w("MicroMsg.JsApiCanvasPutImageData", "put json value error : %s", new Object[]{e});
lVar.E(i, f("fail:build action JSON error", null));
return;
}
}
x.i("MicroMsg.JsApiCanvasPutImageData", "get data failed, value is not a ByteBuffer");
lVar.E(i, f("fail:illegal data", null));
return;
} catch (Throwable e2) {
x.i("MicroMsg.JsApiCanvasPutImageData", "get data failed, %s", new Object[]{Log.getStackTraceString(e2)});
lVar.E(i, f("fail:missing data", null));
return;
}
}
x.i("MicroMsg.JsApiCanvasPutImageData", "the view is not a instance of CanvasView.(%s)", new Object[]{Integer.valueOf(i2)});
lVar.E(i, f("fail:illegal view type", null));
} else {
x.w("MicroMsg.JsApiCanvasPutImageData", "the viewId is not a canvas(%s).", new Object[]{Integer.valueOf(i2)});
lVar.E(i, f("fail:illegal view type", null));
}
} catch (Throwable e22) {
x.i("MicroMsg.JsApiCanvasPutImageData", "get canvas id failed, %s", new Object[]{Log.getStackTraceString(e22)});
lVar.E(i, f("fail:illegal canvasId", null));
}
}
private static int[] h(ByteBuffer byteBuffer) {
int i = 0;
byte[] k = c.k(byteBuffer);
int[] iArr = new int[(k.length / 4)];
int i2 = 0;
while (true) {
int i3 = i;
if (i2 >= iArr.length) {
return iArr;
}
i = i3 + 1;
int i4 = i + 1;
i = ((k[i] & WebView.NORMAL_MODE_ALPHA) << 8) | ((k[i3] & WebView.NORMAL_MODE_ALPHA) << 16);
i3 = i4 + 1;
i4 = (k[i4] & WebView.NORMAL_MODE_ALPHA) | i;
i = i3 + 1;
iArr[i2] = ((k[i3] & WebView.NORMAL_MODE_ALPHA) << 24) | i4;
i2++;
}
}
}
|
package com.orca.page.objects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.orca.selenium.utils.TestUtils;
public class CodeRuntime extends BasePageObject{
protected WebDriver driver;
public SurveySubmenu submenu;
public CodeRuntime(WebDriver driver) {
submenu = new SurveySubmenu(driver);
this.driver = driver;
PageFactory.initElements(driver, this);
}
@FindBy(xpath="//*[@id='codeRuntime']/input[2]")
private WebElement nextMetric;
@FindBy(xpath="//*[@id='codeRuntime']/input[3]")
private WebElement goToSummary;
@FindBy(id="cpuThreshholdSlider")
private WebElement cpuThreshholdSlider;
@FindBy(id="memoryThreshholdSlider")
private WebElement memoryThreshholdSlider;
@FindBy(id="IOThreshholdSlider")
private WebElement IOThreshholdSlider;
public void setMetrics(int xAxis){
TestUtils.slideElement(driver, cpuThreshholdSlider, xAxis);
TestUtils.slideElement(driver, memoryThreshholdSlider, xAxis);
TestUtils.slideElement(driver, IOThreshholdSlider, xAxis);
}
public CodeStatic continueSurvey(){
TestUtils.slideElement(driver, cpuThreshholdSlider, -100);
TestUtils.slideElement(driver, memoryThreshholdSlider, -200);
TestUtils.slideElement(driver, IOThreshholdSlider, 100);
nextMetric.click();
return new CodeStatic(driver);
}
public EvaluationSummary goToSummary(){
goToSummary.click();
return new EvaluationSummary(driver);
}
public SurveySubmenu getSubmenu() {
return submenu;
}
public void setSubmenu(SurveySubmenu submenu) {
this.submenu = submenu;
}
}
|
package graphana.script.bindings.treeelems;
import genscript.execution.ExecuterTreeNodeLazy;
import genscript.syntax.tokens.Tokenizer;
import graphana.script.bindings.GraphanaScriptScope;
public abstract class GraphanaScriptOperationLazy extends ExecuterTreeNodeLazy<GraphanaScriptScope, Tokenizer> {
}
|
package com.pecodesoftware.navigation;
import com.pecodesoftware.driver.DriverRepository;
import org.openqa.selenium.WebDriver;
public class Navigation {
private String url = "https://www.pecodesoftware.com/qa-portal/test-task.pdf";
private WebDriver driver;
public Navigation() {
driver = DriverRepository.DRIVERS.get();
}
public void navigateToUrl() {
driver.get(url);
driver.manage().window().maximize();
}
}
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AddDialog extends JDialog {
private JPanel mainPanel;
private JPanel buttonPanel;
private JPanel surnamePanel;
private JPanel numberPanel;
private JPanel coursePanel;
private JPanel groupPanel;
private JTextField surnameField;
private JTextField numberField;
private JTextField courseField;
private JTextField groupField;
private JButton addButton;
private Student student;
AddDialog(JFrame owner) {
this.setAlwaysOnTop(true);
this.setModal(true);
this.setResizable(false);
this.setSize(400, 150);
this.setTitle("Add a student");
mainPanel = new JPanel();
buttonPanel = new JPanel();
surnamePanel = new JPanel();
numberPanel = new JPanel();
coursePanel = new JPanel();
groupPanel = new JPanel();
surnameField = new JTextField();
numberField = new JTextField();
courseField = new JTextField();
groupField = new JTextField();
addButton = new JButton("Add");
surnameField.setColumns(15);
numberField.setColumns(15);
courseField.setColumns(15);
groupField.setColumns(15);
this.setLayout(new BorderLayout());
this.add(mainPanel, BorderLayout.CENTER);
this.add(buttonPanel, BorderLayout.SOUTH);
mainPanel.setLayout(new FlowLayout());
mainPanel.add(surnamePanel);
mainPanel.add(numberPanel);
mainPanel.add(coursePanel);
mainPanel.add(groupPanel);
surnamePanel.setLayout(new BorderLayout());
surnamePanel.add(new JLabel("Surname"), BorderLayout.NORTH);
surnamePanel.add(surnameField, BorderLayout.SOUTH);
numberPanel.setLayout(new BorderLayout());
numberPanel.add(new JLabel("Number"), BorderLayout.NORTH);
numberPanel.add(numberField, BorderLayout.SOUTH);
coursePanel.setLayout(new BorderLayout());
coursePanel.add(new JLabel("Course"), BorderLayout.NORTH);
coursePanel.add(courseField, BorderLayout.SOUTH);
groupPanel.setLayout(new BorderLayout());
groupPanel.add(new JLabel("Group"), BorderLayout.NORTH);
groupPanel.add(groupField, BorderLayout.SOUTH);
buttonPanel.setLayout(new BorderLayout());
buttonPanel.add(new JPanel(), BorderLayout.WEST);
buttonPanel.add(new JPanel(), BorderLayout.EAST);
buttonPanel.add(addButton, BorderLayout.CENTER);
EnterListener enterListener = new EnterListener();
surnameField.addKeyListener(enterListener);
numberField.addKeyListener(enterListener);
courseField.addKeyListener(enterListener);
groupField.addKeyListener(enterListener);
addButton.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
String surname = surnameField.getText();
String number = numberField.getText();
String course = courseField.getText();
String group = groupField.getText();
if (surname.length() == 0 || number.length() == 0 ||
course.length() == 0 || group.length() == 0) {
JOptionPane.showMessageDialog(AddDialog.this, "Incorrect input!",
"Error", JOptionPane.ERROR_MESSAGE);
} else {
student = new Student(surname, Integer.parseInt(number),
Integer.parseInt(course), Integer.parseInt(group));
AddDialog.this.dispatchEvent(new WindowEvent(AddDialog.this, WindowEvent.WINDOW_CLOSING));
}
}
});
this.setLocationRelativeTo(owner);
}
private class EnterListener extends KeyAdapter {
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
for (ActionListener actionListener : addButton.getActionListeners()) {
actionListener.actionPerformed(new ActionEvent(this, 0, null));
}
}
}
}
public boolean isNull() {
return student == null;
}
public Student getStudent() {
return student;
}
}
|
/*
* 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 rcpl;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import java.sql.*;
/**
*
* @author Nilaya
*/
public class FileComplaintAction extends org.apache.struts.action.Action
{
/* forward name="success" path="" */
private static String SUCCESS = "success";
/**
* This is the action called from the Struts framework.
*
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception
{
FileComplaintBean ob=(FileComplaintBean)form;
String type=ob.getType();
String pid=ob.getPid();
String desc=ob.getDesc();
String aadhar=ob.getAadhar();
String contact=ob.getContact();
String email=ob.getEmail();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/police","root","password");
Statement st=con.createStatement();
ResultSet r=st.executeQuery("select sysdate() from dual");
r.next();
String sysdate=r.getString(1);
System.out.println(sysdate);
String id=""+sysdate.charAt(0)+sysdate.charAt(1)+sysdate.charAt(2)+sysdate.charAt(3)+sysdate.charAt(5)+sysdate.charAt(6)+sysdate.charAt(8)+sysdate.charAt(9)+sysdate.charAt(11)+sysdate.charAt(12)+sysdate.charAt(14)+sysdate.charAt(15)+sysdate.charAt(17)+sysdate.charAt(18)+sysdate.charAt(20);
PreparedStatement pst=con.prepareStatement("insert into complaint values(?,?,?,?,?,?,?,?)");
pst.setString(1,id);
pst.setString(2,type);
pst.setString(3,desc);
pst.setString(4,pid);
pst.setString(5,aadhar);
pst.setString(6,contact);
pst.setString(7,email);
pst.setString(8,"Filed");
int status=pst.executeUpdate();
if(status>0)
{
request.setAttribute("filedcompid", id);
request.setAttribute("filedcomptype", type);
request.setAttribute("filedcompdesc", desc);
request.setAttribute("filedcomppid", pid);
request.setAttribute("filedcompstatus", "filed");
SUCCESS="pass";
}
else
{
request.setAttribute("insertstatus", "failed");
request.setAttribute("message", "Complaint filing failed!");
}
}
catch(Exception e)
{
request.setAttribute("insertstatus", "failed");
request.setAttribute("message", "Compalint filing failed! Check details again.");
SUCCESS="fail";
}
return mapping.findForward(SUCCESS);
}
}
|
package ict.kosovo.growth.ora_5;
import java.util.Scanner;
public class Random {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Shkruaj nje numer nga 1-10: ");
int numri = sc.nextInt();
double random = Math.random();
double r = (int)(random * 10) + 1;
System.out.println(numri + " = " + r);
if (numri == r){
System.out.println("Urime, ja keni qelluar");
}else {
System.out.println("Suksese heren tjeter");
}
}
}
|
package pl.finsys.formValidation.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class PhoneValidator implements ConstraintValidator<Phone, String> {
@Override
public void initialize(Phone paramA) {
}
@Override
public boolean isValid(String phoneNo, ConstraintValidatorContext ctx) {
if(phoneNo == null){
return false;
}
//format "1234567890"
if (phoneNo.matches("\\d{10}")) return true;
//ze znakami -, . lub spacja
else if(phoneNo.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) return true;
//wew 3 to 5
else if(phoneNo.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}")) return true;
//kerunkowy w nawiasach
else if(phoneNo.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}")) return true;
else return false;
}
}
|
package com.example.android.guardiannewsfeedapp;
import android.content.AsyncTaskLoader;
import android.content.Context;
import java.util.List;
public class NewsFeedLoader extends AsyncTaskLoader<List<NewsFeed>> {
private static final String LOG_TAG = NewsFeedLoader.class.getName();
private String mUrl;
public NewsFeedLoader(Context context, String url) {
super(context);
mUrl = url;
}
@Override
protected void onStartLoading() {
forceLoad();
}
@Override
public List<NewsFeed> loadInBackground() {
if (mUrl == null) {
return null;
}
List<NewsFeed> news = QueryUtils.fetchData(mUrl);
return news;
}
}
|
package api.longpoll.bots.model.objects.additional.buttons;
import com.google.gson.JsonElement;
/**
* A button to send user location.
*/
public class LocationButton extends Button {
public LocationButton(Action action) {
super(action);
}
public static class Action extends Button.Action {
public Action() {
this(null);
}
public Action(JsonElement payload) {
super("location", payload);
}
}
}
|
/*
* Copyright (C) 2015 Miquel Sas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.qtplaf.library.swing.action;
import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.ListSelectionModel;
import com.qtplaf.library.app.Session;
import com.qtplaf.library.database.Condition;
import com.qtplaf.library.database.Criteria;
import com.qtplaf.library.database.Field;
import com.qtplaf.library.database.Order;
import com.qtplaf.library.database.PersistorException;
import com.qtplaf.library.database.Record;
import com.qtplaf.library.database.RecordSet;
import com.qtplaf.library.database.RecordSetCustomizer;
import com.qtplaf.library.database.Value;
import com.qtplaf.library.database.ValueArray;
import com.qtplaf.library.swing.ActionUtils;
import com.qtplaf.library.swing.EditContext;
import com.qtplaf.library.swing.EditField;
import com.qtplaf.library.swing.core.JLookupRecords;
import com.qtplaf.library.swing.core.SwingUtils;
import com.qtplaf.library.util.Alignment;
import com.qtplaf.library.util.Icons;
/**
* An action to lookup a list of records, select one of them and update the referred components.
* <p>
* Normally to define an action lookup it is required to follow the next steps:
* <ul>
* <li>1. Define the master record, used to display the possible values.
* <li>2. Define the columns to be displayed.
* <li>3. Define the link between the the screen context (using the field keys) and the fields of the displayed records.
* <li>4. Define the way to populate data:
* <ul>
* <li>Letting the action to automatically populate data. In this case you can create an optional criteria based on
* special search criteria. When collecting data also can be set the order and distinct flag.
* <li>Setting the record set.
* </ul>
* </ul>
*
* @author Miquel Sas
*/
public class ActionLookup extends AbstractAction {
/**
* The master record.
*/
private Record masterRecord;
/**
* The list of aliases of the fields to be displayed.
*/
private List<String> fieldAliases = new ArrayList<>();
/**
* The optional recordset so we do not have to look for it.
*/
private RecordSet recordSet;
/**
* The list of names of key edit field controls to be updated.
*/
private List<String> keyEditFieldNames = new ArrayList<>();
/**
* The list of aliases of key fields that relate to the key edit controls.
*/
private List<String> keyAliases = new ArrayList<>();
/**
* An optional criteria to further filter the recordset, either when retrieved from a database or when set directly.
*/
private Criteria criteria;
/**
* An optional customizer to further adapt the recordset.
*/
private RecordSetCustomizer recordSetCustomizer;
/**
* An optional selection or presentation order.
*/
private Order order;
/**
* An optional title for this lookup.
*/
private String title;
/**
* Default constructor.
*/
public ActionLookup() {
super();
ActionUtils.setSmallIcon(this, Icons.app_16x16_select_all);
}
/**
* Returns the working session, retrieved from the edit context in which this action lookup has been set.
*
* @return The working session.
*/
public Session getSession() {
EditContext editContext = ActionUtils.getEditContext(this);
if (editContext != null) {
return editContext.getSession();
}
return null;
}
/**
* Configure the action.
*
* @param masterRecord The master record.
* @param localKeyFields The list of local key fields.
* @param foreignKeyFields The list of foreign key fields.
*/
public void configure(Record masterRecord, List<Field> localKeyFields, List<Field> foreignKeyFields) {
// Set the master record.
setMasterRecord(masterRecord);
// Add the links between key edit controls and foreign key fields.
for (int i = 0; i < localKeyFields.size(); i++) {
Field localKeyField = localKeyFields.get(i);
Field foreignKeyField = foreignKeyFields.get(i);
String keyEditName = EditContext.getEditFieldName(localKeyField);
String keyAlias = foreignKeyField.getAlias();
addKeyLink(keyEditName, keyAlias);
}
// Add the field aliases to be displayed: foreign key fields and fields from the foreign table that are main
// description and lookup.
List<String> lookupFields = new ArrayList<>();
for (Field foreignKeyField : foreignKeyFields) {
lookupFields.add(foreignKeyField.getAlias());
}
for (int i = 0; i < masterRecord.getFieldCount(); i++) {
Field foreignField = masterRecord.getField(i);
if (foreignField.isMainDescription()) {
String alias = foreignField.getAlias();
if (!lookupFields.contains(alias)) {
lookupFields.add(alias);
}
}
}
for (int i = 0; i < masterRecord.getFieldCount(); i++) {
Field foreignField = masterRecord.getField(i);
if (foreignField.isLookup()) {
String alias = foreignField.getAlias();
if (!lookupFields.contains(alias)) {
lookupFields.add(alias);
}
}
}
for (String alias : lookupFields) {
addField(alias);
}
}
/**
* Add a field alias to the list of field aliases.
*
* @param alias The alias of the field.
*/
public void addField(String alias) {
fieldAliases.add(alias);
}
/**
* Adds a key link between an edit field and a field alias.
*
* @param keyEditField The key edit field name.
* @param keyAlias The key field alias.
*/
public void addKeyLink(String keyEditField, String keyAlias) {
keyEditFieldNames.add(keyEditField);
keyAliases.add(keyAlias);
}
/**
* Returns the master record.
*
* @return The master record.
*/
public Record getMasterRecord() {
return masterRecord;
}
/**
* Sets the master record.
*
* @param masterRecord The master record.
*/
public void setMasterRecord(Record masterRecord) {
this.masterRecord = masterRecord;
}
/**
* Returns the recordset.
*
* @return The recordset.
*/
public RecordSet getRecordSet() {
return recordSet;
}
/**
* Sets the recordset.
*
* @param recordSet The recordset.
*/
public void setRecordSet(RecordSet recordSet) {
this.recordSet = recordSet;
}
/**
* Returns the optional filteer criteria.
*
* @return The optional filteer criteria.
*/
public Criteria getCriteria() {
return criteria;
}
/**
* Sets the optional filter criteria.
*
* @param criteria The optional filter criteria.
*/
public void setCriteria(Criteria criteria) {
this.criteria = criteria;
}
/**
* Returns the recordset customizer.
*
* @return The recordset customizer.
*/
public RecordSetCustomizer getRecordSetCustomizer() {
return recordSetCustomizer;
}
/**
* Sets the recordset customizer.
*
* @param recordSetCustomizer The recordset customizer.
*/
public void setRecordSetCustomizer(RecordSetCustomizer recordSetCustomizer) {
this.recordSetCustomizer = recordSetCustomizer;
}
/**
* Returns the optional title.
*
* @return The optional title.
*/
public String getTitle() {
return title;
}
/**
* Sets the optional title.
*
* @param title The optional title.
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Returns the list of selected records.
*
* @return The list of selected records.
*/
public List<Record> getSelectedRecords() {
return ActionUtils.getSelectedRecords(this);
}
/**
* Set the list of selected records.
*
* @param selectedRecords The list of selected records.
*/
public void setSelectedRecords(List<Record> selectedRecords) {
ActionUtils.setSelectedRecords(this, selectedRecords);
}
/**
* Sets the multiple selection flag. By default the lookup action is single selection.
*
* @param b A boolean.
*/
public void setMultipleSelection(boolean b) {
ActionUtils.setMultipleSelection(this, b);
}
/**
* Check if this lookup action is multiple selection. By default the lookup action is single selection.
*
* @return A boolean.
*/
public boolean isMultipleSelection() {
return ActionUtils.isMultipleSelection(this);
}
/**
* Returns the presentation order.
*
* @return The order.
*/
public Order getOrder() {
return order;
}
/**
* Sets the presentation order.
*
* @param order The order.
*/
public void setOrder(Order order) {
this.order = order;
}
/**
* Invoked when normally from a masked field button.
*/
@Override
public void actionPerformed(ActionEvent e) {
// Check minimal necessary configuration
if (masterRecord == null) {
throw new IllegalStateException("The master record must be set.");
}
if (fieldAliases.isEmpty()) {
throw new IllegalStateException("The list of fields must be set.");
}
if (keyAliases.isEmpty()) {
throw new IllegalStateException("The list of key aliases and edit fields must be set.");
}
// Check that all display-able fields exist.
for (String alias : fieldAliases) {
if (masterRecord.getField(alias) == null) {
throw new IllegalStateException("Invalid field alias: " + alias);
}
}
// Check that all key aliases and related edit fields exist.
Component source = (Component) e.getSource();
Window topWindow = SwingUtils.getWindowAncestor(source);
Map<String, Component> componentMap = SwingUtils.getComponentMap(topWindow);
for (int i = 0; i < keyAliases.size(); i++) {
String alias = keyAliases.get(i);
if (masterRecord.getField(alias) == null) {
throw new IllegalStateException("Invalid key field alias: " + alias);
}
String name = keyEditFieldNames.get(i);
Component component = componentMap.get(name);
if (component == null) {
throw new IllegalStateException("Invalid key edit field name: " + name);
}
if (!(component instanceof EditField)) {
throw new IllegalStateException("Key edit field " + name + " is not an Edit Field");
}
}
// Build the list of records if not already built.
RecordSet workingRecordSet;
if (recordSet == null) {
// The record set has not been previously set. First check if there is a persistor to retrieve the data.
if (getMasterRecord().getPersistor() == null) {
throw new IllegalStateException("A Persistor is required if the record set is not previously set.");
}
// Build a working criteria to retrieve the data.
Criteria workingCriteria = new Criteria(Criteria.AND);
// Append the optional criteria if present.
if (criteria != null) {
workingCriteria.add(criteria);
}
// Append the criteria for key fields. If the field is string, then a partial value is admitted through a
// LikeLeft condition.
for (int i = 0; i < keyAliases.size(); i++) {
String alias = keyAliases.get(i);
String name = keyEditFieldNames.get(i);
Field field = masterRecord.getField(alias);
Component component = componentMap.get(name);
EditField editField = (EditField) component;
Value value = editField.getValue();
if (value.isValueArray()) {
workingCriteria.add(Condition.inList(field, value.getValueArray()));
} else {
if (field.isString()) {
workingCriteria.add(Condition.likeLeft(field, value));
} else {
workingCriteria.add(Condition.fieldEQ(field, value));
}
}
}
// The selection order. If not set, build it with the key fields.
Order selectionOrder;
if (order == null) {
if (getMasterRecord().getPersistor().getView().getOrderBy() != null) {
selectionOrder = getMasterRecord().getPersistor().getView().getOrderBy();
} else {
selectionOrder = new Order();
for (int i = 0; i < keyAliases.size(); i++) {
String alias = keyAliases.get(i);
Field field = masterRecord.getField(alias);
selectionOrder.add(field);
}
}
} else {
selectionOrder = order;
}
// Try filling the working record set.
try {
workingRecordSet = getMasterRecord().getPersistor().select(workingCriteria, selectionOrder);
} catch (PersistorException exc) {
exc.printStackTrace();
return;
}
} else {
// The record set was already set. Create one applying the optional criteria.
workingRecordSet = recordSet.getRecordSet(criteria);
// If an order was set, sort it.
if (order != null) {
workingRecordSet.sort(order);
}
}
// Apply the customizer if set.
if (recordSetCustomizer != null) {
recordSetCustomizer.customize(workingRecordSet);
}
// Configure the lookup.
JLookupRecords lookup;
if (topWindow != null) {
lookup = new JLookupRecords(getSession(), topWindow, masterRecord);
} else {
lookup = new JLookupRecords(getSession(), masterRecord);
}
// Set the selection mode.
if (isMultipleSelection()) {
lookup.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
} else {
lookup.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
// Get the source component that triggered this action and set the dialog anchor trying to leave the component
// visible.
if (source.getLocation().getX() < SwingUtils.getScreenSize(topWindow).getWidth() / 2) {
lookup.setHorizontalAlignment(Alignment.Right);
} else {
lookup.setHorizontalAlignment(Alignment.Left);
}
// Add fields (columns).
for (String alias : fieldAliases) {
lookup.addColumn(alias);
}
// Set the title. If the optional title is not set, build one using the key fields headers.
if (title == null) {
StringBuilder b = new StringBuilder();
b.append(getSession().getString("tokenSelect"));
for (int i = 0; i < keyAliases.size(); i++) {
String alias = keyAliases.get(i);
Field field = masterRecord.getField(alias);
if (i > 0) {
b.append(", ");
}
b.append(field.getDisplayHeader());
}
title = b.toString();
}
lookup.setTitle(title);
// Perform the lookup.
List<Record> selectedRecords = lookup.lookupRecords(workingRecordSet);
// Save the selected records.
ActionUtils.setSelectedRecords(this, selectedRecords);
// If no records selected, just return.
if (selectedRecords.isEmpty()) {
return;
}
// Set values to key edit fields.
for (int i = 0; i < keyAliases.size(); i++) {
String alias = keyAliases.get(i);
String name = keyEditFieldNames.get(i);
Component component = componentMap.get(name);
EditField editField = (EditField) component;
editField.setValue(getValue(alias, selectedRecords));
}
}
/**
* Returns the value related to the field alias and list of records.
*
* @param alias The field alias.
* @param selectedRecords The list of selected records.
* @return The related value.
*/
private Value getValue(String alias, List<Record> selectedRecords) {
Value value;
if (selectedRecords.size() == 1) {
Record record = selectedRecords.get(0);
value = new Value(record.getValue(alias));
} else {
ValueArray valueArray = new ValueArray();
for (Record record : selectedRecords) {
valueArray.add(new Value(record.getValue(alias)));
}
value = new Value(valueArray);
}
return value;
}
}
|
package org.sankozi.rogueland.control;
import org.sankozi.rogueland.model.coords.Coords;
import org.sankozi.rogueland.model.coords.Dim;
/**
* Interface for finding things on Level
* @author Michał
*/
public interface Locator {
/**
* Returns player location
* @return
*/
Coords getPlayerLocation();
Dim getLevelDim();
}
|
package intersection;
public class Quartic
{
public static final double TWO_PI_43 = 4.1887902047863909846168;
public static final double TWO_PI_3 = 2.0943951023931954923084;
public static final double EPSILON = 1.0e-10;
public double CubicRoots[] = new double[3];
public double QuarticRoots[] = new double[4];
public double smallest = Double.MAX_VALUE;
public boolean isanswer = false;
public int solveCubic(double a, double b, double c, double d)
{
double a0 = a;
double a1 = b / a0;
double a2 = c / a0;
double a3 = d / a0;
double A2 = a1 * a1;
double Q = (A2 - 3.0 * a2) / 9.0;
double R = (a1 * (A2 - 4.5 * a2) + 13.5 * a3) / 27.0;
double Q3 = Q * Q * Q;
double R2 = R * R;
double D = Q3 - R2;
double an = a1 / 3.0;
if (D >= 0.0)
{
D = R / Math.sqrt (Q3);
double theta = Math.acos(d) / 3.0;
double sQ = -2.0 * Math.sqrt(Q);
CubicRoots[0] = sQ * Math.cos (theta) - an;
CubicRoots[1] = sQ * Math.cos (theta + TWO_PI_3) - an;
CubicRoots[2] = sQ * Math.cos (theta + TWO_PI_43) - an;
return (3);
}
else
{
double sQ = Math.pow(Math.sqrt (R2 - Q3) + Math.abs(R), 1.0 / 3.0);
if (R < 0)
CubicRoots[0] = (sQ + Q / sQ) - an;
else
CubicRoots[0] = -(sQ + Q / sQ) - an;
return (1);
}
}
public int solveQuartic(double a, double b, double c, double d, double e)
{
//double c0 = a;
double c1 = b / a;
double c2 = c / a;
double c3 = d / a;
double c4 = e / a;
double c12 = c1 * c1;
double p = -0.375 * c12 + c2;
double q = 0.125 * c12 * c1 - 0.5 * c1 * c2 + c3;
double r = -0.01171875 * c12 * c12 + 0.0625 * c12 * c2 - 0.25 * c1 * c3 + c4;
double A = 1.0;
double B = -0.5 * p;
double C = -r;
double D = 0.5 * r * p - 0.125 * q * q;
int i = solveCubic(A, B, C, D);
double z;
if (i > 0)
z = CubicRoots[0];
else
return (0);
double d1 = 2.0 * z - p;
double d2;
if (d1 < 0.0)
{
if (d1 > -EPSILON)
d1 = 0.0;
else
return 0;
}
if (d1 < EPSILON)
{
d2 = z * z - r;
if (d2 < 0.0)
return (0);
d2 = Math.sqrt(d2);
}
else
{
d1 = Math.sqrt (d1);
d2 = 0.5 * q / d1;
}
double q1 = d1 * d1;
double q2 = -0.25 * c1;
i = 0;
p = q1 - 4.0 * (z - d2);
if (p == 0)
QuarticRoots[i++] = -0.5 * d1 - q2;
else if (p > 0)
{
p = Math.sqrt(p);
QuarticRoots[i++] = -0.5 * (d1 + p) + q2;
QuarticRoots[i++] = -0.5 * (d1 - p) + q2;
}
p = q1 - 4.0 * (z + d2);
if (p == 0)
QuarticRoots[i++] = 0.5 * d1 - q2;
else if (p > 0)
{
p = Math.sqrt(p);
QuarticRoots[i++] = 0.5 * (d1 + p) + q2;
QuarticRoots[i++] = 0.5 * (d1 - p) + q2;
}
return i;
}
public Quartic(double a, double b, double c, double d, double e)
{
int i = solveQuartic(a, b, c, d, e);
int j = 0;
while (j < i)
{
if (QuarticRoots[j] > 0.0 && QuarticRoots[j] < smallest)
{
smallest = QuarticRoots[j];
isanswer = true;
}
j++;
}
}
}
|
/**
* @ProjectName: 智能建筑
* @Copyright: 2017 HangZhou Hikvision System Technology Co., Ltd. All Right Reserved.
* @address: http://www.hikvision.com
* @date: 2018/8/27 15:16
* @Description: 本内容仅限于杭州海康威视数字技术系统公司内部使用,禁止转发.
*/
package cn.yhd.bean;
/**
* <p></p>
*
* @author yuhuadong6 2018/8/27 15:16
* @version V2.9
* @modificationHistory=========================逻辑或功能性重大变更记录
* @modify by user: {修改人} 2018/8/27
* @modify by reason:{方法名}:{原因}
*/
public class Friend {
private int status;
private String username;
private String friendname;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username= username;
}
public String getFriendname() {
return friendname;
}
public void setFriendname(String friendname) {
this.friendname = friendname;
}
public void setStatus(int status) {
this.status = status;
}
public int getStatus() {
return status;
}
public String toString(){
return username + " " + friendname;
}
}
|
package application;
import java.util.ArrayList;
import java.util.List;
import model.dao.DepartamentoDao;
import model.dao.FabricaDao;
import model.entidades.Departamento;
public class ProgramaDepartamento {
public static void main(String[] args) {
List<Departamento> listaDeDepartamentos = new ArrayList<>();
DepartamentoDao departamentoDao = FabricaDao.criarDepartamentoDao();
System.out.println();
System.out.println("=============== Localizar Pelo do Departamento ===============");
Departamento departamento = departamentoDao.localizarDepartamentoPeloId(2);
System.out.println(departamento);
System.out.println();
System.out.println("=============== Imprimir todos os Departamentos ==============");
listaDeDepartamentos = departamentoDao.listarTodosOsDepartamentos();
for(Departamento departamentoItem : listaDeDepartamentos) {
System.out.println(departamentoItem);
}
System.out.println();
System.out.println("=============== Insert =======================================");
departamento = new Departamento(null, "Nada");
departamentoDao.insertDepartamento(departamento);
System.out.println("Adicionado novo departamento ID: "+ departamento.getId() + " Nome: "+ departamento.getNome());
System.out.println();
System.out.println("=============== Update =======================================");
departamento = new Departamento(7, "Comida");
departamentoDao.updateDepartamento(departamento);;
System.out.println("Adicionado novo departamento ID: "+ departamento.getId() + " Nome: "+ departamento.getNome());
System.out.println();
System.out.println("=============== Delete =======================================");
int codigoDepartamento = 8;
departamentoDao.deletarDepartamentoPeloId(codigoDepartamento);
System.out.println("Departamento codigo: "+ codigoDepartamento + " foi deletado com sucesso!");
}
}
|
package com.example.webpageload;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
WebView simpleWebView;
Button loadWebPage, loadFromStaticHtml;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate buttons and a web view
loadFromStaticHtml = (Button) findViewById(R.id.loadFromStaticHtml);
loadFromStaticHtml.setOnClickListener(this);
loadWebPage = (Button) findViewById(R.id.loadWebPage);
loadWebPage.setOnClickListener(this);
simpleWebView = (WebView) findViewById(R.id.simpleWebView);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loadFromStaticHtml:
// define static html text
String customHtml = "<html><body><h1>Hello</h1>" +
"<h3>Welcome to the <em>restaurant</em></h3>" + "<p><mark>Buy 1 get 1 free</mark></p>" +
"<p>List of beverages</p>" + "<p><ol><li><b>Tea</b></li><li><u>Coffee</u></li><li>Milk</li></ol></p>" +
"<p><i>Have a good day</i></p>" + "<p><sup>Come</sup> back <sub>again</sub></p>" + "</body></html>";
simpleWebView.loadData(customHtml, "text/html", "UTF-8"); // load html string data in a web view
break;
case R.id.loadWebPage:
simpleWebView.setWebViewClient(new MyWebViewClient());
String url = "https://www.google.com/intl/en_in/gmail/about/";
simpleWebView.getSettings().setJavaScriptEnabled(true);
simpleWebView.loadUrl(url); // load a web page in a web view
break;
}
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
|
import java.util.List;
public interface IUser {
public boolean registrar(User user);
public List<User> obtener(User user);
public List<User> obtenerTodos();
public boolean actualizar(User user);
public boolean eliminar(User user);
}
|
package sortAlgorithm;
public class HeapSortDemo {
}
|
package org.sagebionetworks.repo.web.service;
import org.sagebionetworks.reflection.model.PaginatedResults;
import org.sagebionetworks.repo.model.ACCESS_TYPE;
import org.sagebionetworks.repo.model.AccessRequirement;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.RestrictableObjectDescriptor;
import org.sagebionetworks.repo.model.RestrictableObjectDescriptorResponse;
import org.sagebionetworks.repo.model.UnauthorizedException;
import org.sagebionetworks.repo.model.dataaccess.AccessRequirementConversionRequest;
import org.sagebionetworks.repo.web.NotFoundException;
public interface AccessRequirementService {
public AccessRequirement createAccessRequirement(Long userId,
AccessRequirement accessRequirement) throws Exception;
public AccessRequirement createLockAccessRequirement(Long userId,
String entityId) throws Exception;
public AccessRequirement getAccessRequirement(String requirementId)
throws DatastoreException, UnauthorizedException, NotFoundException;
public PaginatedResults<AccessRequirement> getAccessRequirements(
Long userId, RestrictableObjectDescriptor subjectId, Long limit, Long offset)
throws DatastoreException, UnauthorizedException,
NotFoundException;
public AccessRequirement updateAccessRequirement(
Long userId, String requirementId, AccessRequirement accessRequirement) throws Exception;
public void deleteAccessRequirements(Long userId, String requirementId)
throws DatastoreException, UnauthorizedException,
NotFoundException;
public AccessRequirement convertAccessRequirements(Long userId, AccessRequirementConversionRequest request);
public RestrictableObjectDescriptorResponse getSubjects(String requirementId, String nextPageToken);
}
|
package app;
import org.json.JSONObject;
public class Localization extends ReadJson{
JSONObject dic;
CharRep charRep;
protected void switchTo(String listname){
dic = obj.getJSONObject(listname);
}
private String lookUpField(String key) {
if(dic.has(key))
return dic.getString(key);
System.out.println("Key "+key+" was not found.");
return "Empty key";
}
public Localization() {
super("/json/localized.json");
charRep = new CharRep();
switchTo("EN");
}
public String Header(String key) {
return lookUpField(key);
}
public String getLocalizedText(String key) {
return charRep.toANSI(lookUpField(key));
}
public String wrapPrefix(String key) {
return "- " + lookUpField(key) + ": ";
}
}
|
package com.globomart.catalog.dao;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.globomart.catalog.defs.Category;
import com.globomart.catalog.models.Product;
import com.globomart.catalog.service.impl.CatalogServiceImpl;
import com.globomart.catalog.utils.JsonUtils;
@RunWith(SpringRunner.class)
public class ProductRepositoryTest {
private CatalogServiceImpl service;
private ProductRepository repository;
@Before
public void setUp() {
repository = mock(ProductRepository.class);
service = new CatalogServiceImpl(repository);
}
@Test
public void testBeans() {
assertNotNull(repository);
assertNotNull(service);
}
@Test
public void addProductTest() throws Exception{
try {
Product product=new Product();
product.setProductId(new Long(1234));
product.setProductName("Book");
product.setProductDescription("Java Programming");
product.setUnitPrice(new Double(1000));
product.setVendorId("100");
product.setCategory(Category.BOOKS.toString());
Product products=repository.save(product);
if(products==null){
System.out.println("Products NULL");
}else {
System.out.println(products.getProductName());
}
Optional<Product> product2=repository.findById(product.getProductId());
if(product2.isPresent()) {
System.out.println(JsonUtils.readValueAsString(product2.get()));
}else {
System.out.println("not present");
}
} catch (JsonProcessingException e) {
System.out.println("Exception: "+e.getMessage());
throw e;
}
}
@Test
public void insertTestData() {
RestTemplate restClient=new RestTemplate();
loadData().forEach((product)->{
try {
restClient.exchange("http://localhost:8080/v1/add",
HttpMethod.POST,
new HttpEntity<Product>(product),
Product.class);
} catch (Exception e) {
e.printStackTrace();
}
});
}
private static List<Product> loadData() {
List<Product> products=new ArrayList<>();
products.add(new Product(new Long(1001),
"TVS Apache",
"TVS bike",
new Double(2000000),
"BIKE",
"101"));
products.add(new Product(new Long(1002),
"Bajaj Domiar",
"Bajaj bike",
new Double(2500000),
"BIKE",
"102"));
products.add(new Product(new Long(1003),
"Hero bicycle",
"bicycle",
new Double(8000),
"BICYCLE",
"103"));
products.add(new Product(new Long(1004),
"Honda Citi",
"Honda Car",
new Double(1600000),
"CAR",
"104"));
products.add(new Product(new Long(1005),
"MUSTANG GT",
"GT Car",
new Double(3500000),
"CAR",
"105"));
products.add(new Product(new Long(1006),
"Honda bicycle",
"bicycle",
new Double(8000),
"BICYCLE",
"106"));
return products;
}
private static long getRandomIntegerBetweenRange(int min, int max){
long x = (int)(Math.random()*((max-min)+1))+min;
return x;
}
}
|
package com.nju.edu.cn.service;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class ContractServieceImplTest {
@Test
public void testGetCollectList(){
}
@Test
public void testCollect(){
}
@Test
public void testCancelCollect(){
}
@Test
public void testGetMyTradeList(){
}
@Test
public void testGetList(){
}
@Test
public void testIsCollected(){
}
@Test
public void testBuyProperties(){
}
@Test
public void testBuy(){
}
@Test
public void testGetDetail(){
}
@Test
public void testGetLiquidity(){
}
@Test
public void testHistoryMarket(){
}
@Test
public void testReem(){
}
}
|
package com.tencent.mm.plugin.fts.ui.a;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.tencent.mm.plugin.fts.a.d;
import com.tencent.mm.plugin.fts.a.d.a.a.b;
import com.tencent.mm.plugin.fts.ui.a.n.a;
import com.tencent.mm.plugin.fts.ui.m;
import com.tencent.mm.plugin.fts.ui.n$d;
import com.tencent.mm.plugin.fts.ui.n$f;
import com.tencent.mm.plugin.fts.ui.n.e;
public class n$b extends b {
final /* synthetic */ n jyN;
public n$b(n nVar) {
this.jyN = nVar;
super(nVar);
}
public final View a(Context context, ViewGroup viewGroup) {
View inflate = LayoutInflater.from(context).inflate(e.fts_more_item, viewGroup, false);
a aVar = new a(this.jyN);
aVar.jxy = (TextView) inflate.findViewById(n$d.tip_tv);
aVar.gmn = (ImageView) inflate.findViewById(n$d.icon_iv);
aVar.contentView = inflate.findViewById(n$d.search_item_content_layout);
inflate.setTag(aVar);
return inflate;
}
public final void a(Context context, com.tencent.mm.plugin.fts.a.d.a.a.a aVar, com.tencent.mm.plugin.fts.a.d.a.a aVar2, Object... objArr) {
a aVar3 = (a) aVar;
n nVar = (n) aVar2;
m.h(aVar3.contentView, this.jyN.jtj);
aVar3.jxy.setText(nVar.jyK);
aVar3.gmn.setImageResource(n$f.fts_more_button_icon);
}
public final boolean a(Context context, com.tencent.mm.plugin.fts.a.d.a.a aVar) {
Intent intent = new Intent();
intent.putExtra("detail_query", this.jyN.jrx.jrV);
intent.putExtra("detail_type", this.jyN.jtk);
intent.putExtra("Search_Scene", this.jyN.jsZ);
d.b(context, ".ui.FTSDetailUI", intent);
return true;
}
}
|
package com.spring.common;
public class UploadFileUtils {
}
|
import java.util.ArrayList;
import java.util.Scanner;
/*Write a program that extracts words from a string.
Words are sequences of characters that are at least two symbols long and consist only of English alphabet letters.
Use regex.*/
public class ExtractWords {
public static void main(String args[]) {
Scanner console = new Scanner(System.in);
String[] str = console.nextLine().split("[^a-zA-z]");
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < str.length; i++) {
String s = str[i];
if (!s.equals("") && s.length()>=2) {
list.add(s);
}
}
System.out.printf("%s", String.join(" ", list));
}
}
|
package CardModel;
/**
* @author Collin Gifford
* @author YUNHAO ZHANG
*/
/*
* Represents a card from a standard 52-card Poker deck.
* Has a suit from the set of Hearts, Diamonds, Clubs, and Spades,
* and a rank of 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, or Ace.
*/
public class Card implements Comparable<Card>
{
private Rank rank;
private Suit suit;
public Card(Rank rank, Suit suit)
{
this.rank = rank;
this.suit = suit;
}
@Override
public int compareTo(Card card)
{
if (this.rank.getValue() < card.rank.getValue())
{
return -1;
} else if (this.rank.getValue() > card.rank.getValue())
{
return 1;
} else
{
/*
* if (this.suit == card.suit) { throw new DuplicateCardException();
* }
*/
return 0;
}
}
public Rank getRank()
{
return this.rank;
}
public Suit getSuit()
{
return this.suit;
}
@Override
public String toString()
{
String rankRepresentation;
switch (this.rank)
{
case Ace:
rankRepresentation = "A";
break;
case King:
rankRepresentation = "K";
break;
case Queen:
rankRepresentation = "Q";
break;
case Jack:
rankRepresentation = "J";
break;
default:
rankRepresentation = Integer.toString(this.rank.getValue());
}
String suitRepresentation = "";
switch (this.suit)
{
case Hearts:
suitRepresentation = "H";
break;
case Diamonds:
suitRepresentation = "D";
break;
case Spades:
suitRepresentation = "S";
break;
case Clubs:
suitRepresentation = "C";
}
return rankRepresentation + suitRepresentation;
}
@Override
public int hashCode()
{
return ((this.rank.ordinal() << 4) | (this.suit.ordinal()));
}
@Override
public boolean equals(Object o)
{
if (o.getClass() == this.getClass())
{
if (this.rank == ((Card) o).rank && this.suit == ((Card) o).suit)
{
return true;
} else
{
return false;
}
} else
{
return false;
}
}
public int getImageFileNameNumber()
{
if (rank == null && suit == null)
return 0; // Special case for the back of a card
// Aces are 1, 2, 3, 4.png
// Kings are 5, 6, 7, 8.png
// Queens are 10, 11, 12, 13.png
// Deuces are 49, 50, 51, 52.png
return suit.getValue() + (52 - (rank.getValue() - 1) * 4);
}
}
|
package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.ArrayList;
public class Controller {
private ArrayList<Client> clients;
private DAO dao;
// Buscador layout
@FXML
private Button buttonSearcher;
@FXML
private TextField numberTextSearch;
@FXML
private ListView lvClients;
@FXML
private TextField textApellido;
public void initialize() {
dao = new DAO();
}
public void imageButtonClicked(MouseEvent mouseEvent) {
try {
Stage stage = (Stage) buttonSearcher.getScene().getWindow();
Parent root = FXMLLoader.load(getClass().getResource("addClient.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void buttonSearcherClicked(ActionEvent actionEvent) {
try {
lvClients.getItems().clear();
clients = dao.getClienteByNum(numberTextSearch.getText());
for (int i = 0; i < clients.size(); i++) {
lvClients.getItems().add(clients.get(i).getNombre() + ", " + clients.get(i).getApellido() + ", " + clients.get(i).getTelefono());
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public void onListViewClicked(MouseEvent mouseEvent) {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2) {
String clientInfo = (String) lvClients.getSelectionModel().getSelectedItem();
if (clientInfo != null && !clientInfo.isEmpty()) {
try {
FXMLLoader fmxlLoader = new FXMLLoader(getClass().getResource("sample.fxml"));
Parent root = fmxlLoader.load();
ControllerMain controller = fmxlLoader.getController();
controller.setClient(clientInfo);
Scene scene = new Scene(root);
Stage stage = (Stage) buttonSearcher.getScene().getWindow();
stage.setScene(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void buttonApellidoClicked(ActionEvent actionEvent) {
try {
lvClients.getItems().clear();
clients = dao.getClienteByName(textApellido.getText());
for (int i = 0; i < clients.size(); i++) {
lvClients.getItems().add(clients.get(i).getNombre() + ", " + clients.get(i).getApellido() + ", " + clients.get(i).getTelefono());
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
|
package com.dorothy.railway999.vo;
public class FreeboardVo {
private long freeboardNo;
private String freeboardTitle;
private String freeboardContent;
private long viewCnt;
private String createdDate;
private long memberNo;
private String memberName;
public long getFreeboardNo() {
return freeboardNo;
}
public void setFreeboardNo(long freeboardNo) {
this.freeboardNo = freeboardNo;
}
public String getFreeboardTitle() {
return freeboardTitle;
}
public void setFreeboardTitle(String freeboardTitle) {
this.freeboardTitle = freeboardTitle;
}
public String getFreeboardContent() {
return freeboardContent;
}
public void setFreeboardContent(String freeboardContent) {
this.freeboardContent = freeboardContent;
}
public long getViewCnt() {
return viewCnt;
}
public void setViewCnt(long viewCnt) {
this.viewCnt = viewCnt;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public long getMemberNo() {
return memberNo;
}
public void setMemberNo(long memberNo) {
this.memberNo = memberNo;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
@Override
public String toString() {
return "FreeboardVo [freeboardNo=" + freeboardNo + ", freeboardTitle="
+ freeboardTitle + ", freeboardContent=" + freeboardContent
+ ", viewCnt=" + viewCnt + ", createdDate=" + createdDate
+ ", memberNo=" + memberNo + ", memberName=" + memberName + "]";
}
}
|
package board.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import board.model.BoardVO;
import board.model.BoardDAO;
// 글 내용을 처리하는 액션 클래스
public class ContentAction implements CommandAction {
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable {
// TODO Auto-generated method stub
// 해당 글 번호
int num = Integer.parseInt(request.getParameter("num"));
// 해당 페이지 번호
String pageNum = request.getParameter("pageNum");
// 데이터베이스 연결처리
BoardDAO dbPro = BoardDAO.getInstance();
// 해당 글 번호에 대한 해당레코드
BoardVO article = dbPro.getArticle(num);
// 해당 뷰에서 사용할 속성
request.setAttribute("num", new Integer(num));
request.setAttribute("pageNum", new Integer(pageNum));
request.setAttribute("article", article);
return "/board/content.jsp";
}
}
|
package eu.ase.ro.dam.subway_route.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseUser;
import eu.ase.ro.dam.subway_route.R;
public class RegisterActivity extends AppCompatActivity {
TextInputEditText et_email;
TextInputEditText et_password;
TextInputEditText et_confirm_password;
Button button_register;
Intent intent;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
initView();
}
private void initView(){
et_email = findViewById(R.id.register_et_email);
et_password = findViewById(R.id.register_et_password);
et_confirm_password = findViewById(R.id.register_et_repeat_password);
button_register = findViewById(R.id.register_button);
mAuth = FirebaseAuth.getInstance();
button_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(infoValidation()) {
auth();
}
}
});
}
@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null){
}
}
private void auth(){
final String email = et_email.getText().toString().trim();
final String password = et_password.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(getApplicationContext(), R.string.info_creare_user, Toast.LENGTH_LONG).show();
intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
finish();
} else {
// autentificare nereusita
if(task.getException() instanceof FirebaseAuthUserCollisionException){
Toast.makeText(getApplicationContext(), R.string.errSameUser, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), R.string.errAuth, Toast.LENGTH_SHORT).show();
}
}
}
});
}
private boolean infoValidation(){
if(et_email.getText() == null || et_email.getText().toString().trim().isEmpty()){
Toast.makeText(getApplicationContext(), R.string.err_mail, Toast.LENGTH_LONG).show();
return false;
}
if(!Patterns.EMAIL_ADDRESS.matcher(et_email.getText().toString().trim()).matches()){
Toast.makeText(getApplicationContext(), R.string.errValidEmail, Toast.LENGTH_LONG).show();
return false;
}
if(et_password.getText() == null || et_password.getText().toString().trim().isEmpty() || et_password.getText().toString().trim().length()<7){
Toast.makeText(getApplicationContext(), R.string.err_set_pass, Toast.LENGTH_LONG).show();
return false;
}
if(et_confirm_password.getText() == null || et_confirm_password.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), R.string.err_confirm_pass, Toast.LENGTH_LONG).show();
return false;
}
if(!et_confirm_password.getText().toString().trim().matches(et_password.getText().toString().trim())){
Toast.makeText(getApplicationContext(), R.string.errSamePass, Toast.LENGTH_LONG).show();
return false;
}
return true;
}
}
|
package com.ib.dtos;
import java.util.Date;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import com.ib.misc.TimeSerializer;
/**
* Location dto to capture location related details
*
* @author ishmael
*
*/
@JsonAutoDetect(getterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY)
@JsonIgnoreProperties(ignoreUnknown = true)
public class LocationDTO {
@JsonProperty("name")
private String name;
@JsonProperty("country")
private String country;
@JsonProperty("coord")
private CoordinateDTO coordinate;
@JsonProperty("sunrise")
@JsonSerialize(using = TimeSerializer.class)
private Date sunriseTime;
@JsonProperty("sunset")
@JsonSerialize(using = TimeSerializer.class)
private Date sunsetTime;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public CoordinateDTO getCoordinate() {
return coordinate;
}
public void setCoordinate(CoordinateDTO coordinate) {
this.coordinate = coordinate;
}
public Date getSunriseTime() {
return sunriseTime;
}
public void setSunriseTime(Date sunriseTime) {
this.sunriseTime = sunriseTime;
}
public Date getSunsetTime() {
return sunsetTime;
}
public void setSunsetTime(Date sunsetTime) {
this.sunsetTime = sunsetTime;
}
}
|
package sukerPkg;
import java.io.IOException;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;
import javax.comm.CommPortIdentifier;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ExtendedModifyEvent;
import org.eclipse.swt.custom.ExtendedModifyListener;
import org.eclipse.swt.custom.LineStyleEvent;
import org.eclipse.swt.custom.LineStyleListener;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;
public class AndroSuker_TabItem_SerialComm implements AndroSuker_Definition, Observer {
private static Composite SerialComm_composite;
private List<String> readList;
private List<String> writeList;
private Text addCommandEdit;
private Table CmdTable;
private int values_cnt;
private StyledText mLogText;
private String info_highlight_keyword;
private String mCurrentCmdStr;
private Button btnOpenPort;
private Button btnClosePort;
private Button btnRun;
private Button btnClearText;
private Button btnComPortScan;
private Group comboGroup;
private static Combo combo_atcmd_port;
private static Combo combo_atcmd_baudrate;
private static Combo combo_atcmd_data;
private static Combo combo_atcmd_parity;
private static Combo combo_atcmd_stop;
private static Combo combo_atcmd_flowcontrol;
private Button btnCheckButton;
private final int ATCMD_BTN_OPENPORT = 500;
private final int ATCMD_BTN_CLOSEPORT = 501;
private final int ATCMD_BTN_ADD = 502;
private final int ATCMD_BTN_DEL = 503;
private final int ATCMD_BTN_DO = 504;
private final int ATCMD_BTN_CLEARTEXT = 505;
private final int ATCMD_BTN_SCAN = 506;
private final int ATCMD_CHK_BTN = 600;
private final int MAX_TABLE_CNT = 30;
private static Shell thisShell;
private static AndroSuker_SerialParameters serialParameters;
private static AndroSuker_SerialConnection serialConnection;
private boolean lock_myself;
public boolean isPossibleReadFromSerial;
public AndroSuker_TabItem_SerialComm(Shell shell, TabFolder tabFolder, AndroSuker_Execute mExecute) {
thisShell = shell;
createPage(tabFolder);
lock_myself = false;
isPossibleReadFromSerial = false;
serialParameters = new AndroSuker_SerialParameters();
serialConnection = new AndroSuker_SerialConnection(this, serialParameters, thisShell);
btnClosePort.setEnabled(false);
btnRun.setEnabled(false);
mCurrentCmdStr = "";
initParameters();
initPage();
}
public static void start() {
if (!serialConnection.isOpen()) {
listPortChoices();
}
}
public static Composite getInstance() {
return SerialComm_composite;
}
public String getCurrentClsName() {
return this.getClass().getName();
}
public void __onFinally() {
writeList = AndroSuker_Main_Layout.getWriteFileList();
TableItem[] cmdTableItems = CmdTable.getItems();
if (btnCheckButton.getSelection())
AndroSuker_INIFile.writeIniFile("ATCMD_SETUP_LGATCMD_CHECKBOX", "true", writeList);
else
AndroSuker_INIFile.writeIniFile("ATCMD_SETUP_LGATCMD_CHECKBOX", "false", writeList);
AndroSuker_INIFile.writeIniFile("ATCMD_SETUP_BAUTRATE", serialParameters.getBaudRateIndexToString(combo_atcmd_baudrate.getSelectionIndex()), writeList);
AndroSuker_INIFile.writeIniFile("ATCMD_SETUP_DATABIT", serialParameters.getDatabitsIndexToString(combo_atcmd_data.getSelectionIndex()), writeList);
AndroSuker_INIFile.writeIniFile("ATCMD_SETUP_PARITY", serialParameters.getParityIndexToString(combo_atcmd_parity.getSelectionIndex()), writeList);
AndroSuker_INIFile.writeIniFile("ATCMD_SETUP_STOPBIT", serialParameters.getStopIndexToString(combo_atcmd_stop.getSelectionIndex()), writeList);
AndroSuker_INIFile.writeIniFile("ATCMD_SETUP_FLOWCONTROL", serialParameters.getFlowControlIndexToString(combo_atcmd_flowcontrol.getSelectionIndex()), writeList);
AndroSuker_INIFile.writeIniFile("ATCMD_VALUE_CNT", Integer.toString(CmdTable.getItemCount()), writeList);
for (int i = 0; i < values_cnt; i++) {
AndroSuker_INIFile.writeIniFile("ATCMD_VALUE_"+i, cmdTableItems[i].getText(), writeList);
}
serialCommTask.stopTimer();
serialConnection.closeConnection();
}
private void initPage() {
String resultStr = "none";
readList = AndroSuker_Main_Layout.getReadFileList();
if (readList != null){
resultStr = AndroSuker_INIFile.readIniFile(readList, "ATCMD_SETUP_LGATCMD_CHECKBOX");
if (resultStr.equals("true")) {
btnCheckButton.setSelection(true);
serialConnection.setATCMDpurpose(serialConnection.SERIALCOMM_PURPOSE_LGATCMD);
}
else {
btnCheckButton.setSelection(false);
serialConnection.setATCMDpurpose(serialConnection.SERIALCOMM_PURPOSE_GENERAL);
}
resultStr = AndroSuker_INIFile.readIniFile(readList, "ATCMD_SETUP_BAUTRATE");
if (resultStr.length() > 0)
combo_atcmd_baudrate.select(serialParameters.getBaudRateStringToIndex(resultStr));
else
combo_atcmd_baudrate.select(serialParameters.getBaudRateStringToIndex("9600"));
resultStr = AndroSuker_INIFile.readIniFile(readList, "ATCMD_SETUP_DATABIT");
if (resultStr.length() > 0)
combo_atcmd_data.select(serialParameters.getDatabitsStringToIndex(resultStr));
else
combo_atcmd_data.select(serialParameters.getDatabitsStringToIndex("8"));
resultStr = AndroSuker_INIFile.readIniFile(readList, "ATCMD_SETUP_PARITY");
if (resultStr.length() > 0)
combo_atcmd_parity.select(serialParameters.getParityStringToIndex(resultStr));
else
combo_atcmd_parity.select(serialParameters.getParityStringToIndex("None"));
resultStr = AndroSuker_INIFile.readIniFile(readList, "ATCMD_SETUP_STOPBIT");
if (resultStr.length() > 0)
combo_atcmd_stop.select(serialParameters.getStopbitsStringToIndex(resultStr));
else
combo_atcmd_stop.select(serialParameters.getStopbitsStringToIndex("1"));
resultStr = AndroSuker_INIFile.readIniFile(readList, "ATCMD_SETUP_FLOWCONTROL");
if (resultStr.length() > 0)
combo_atcmd_flowcontrol.select(serialParameters.getFlowControlStringToIndex(resultStr));
else
combo_atcmd_flowcontrol.select(serialParameters.getFlowControlStringToIndex("None"));
resultStr = AndroSuker_INIFile.readIniFile(readList, "ATCMD_VALUE_CNT");
if (resultStr.length() > 0)
values_cnt = Integer.parseInt(resultStr);
else
values_cnt = 0;
for (int i = 0; i < values_cnt; i++) {
TableItem item = new TableItem(CmdTable, SWT.FILL);
resultStr = AndroSuker_INIFile.readIniFile(readList, "ATCMD_VALUE_"+i);
item.setText(resultStr);
}
CmdTable.setSelection(0);
}
}
private void createPage(TabFolder tabFolder) {
//--------------------------------######### LogCat Main Frame ##########--------------------------------
SerialComm_composite = new Composite(tabFolder, SWT.FILL);
SerialComm_composite.setLayout(new GridLayout(5, false));
Label lblNewLabel = new Label(SerialComm_composite, SWT.NONE);
lblNewLabel.setText("Send Event");
new Label(SerialComm_composite, SWT.NONE);
new Label(SerialComm_composite, SWT.NONE);
new Label(SerialComm_composite, SWT.NONE);
new Label(SerialComm_composite, SWT.NONE);
addCommandEdit = new Text(SerialComm_composite, SWT.BORDER);
addCommandEdit.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1));
new Label(SerialComm_composite, SWT.NONE);
addCommandEdit.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
}
@SuppressWarnings("unused")
void displayMessage(String prefix, FocusEvent e) {
}
});
//------------------------------######### Group1 ##########---------------------------------
Group group_btn = new Group(SerialComm_composite, SWT.NONE);
GridData gd_group_btn = new GridData(SWT.CENTER, SWT.TOP, false, false, 1, 2);
gd_group_btn.heightHint = 97;
group_btn.setLayoutData(gd_group_btn);
//------------------------------######### add button ##########---------------------------------
Button btnAdd = new Button(group_btn, SWT.NONE);
btnAdd.setBounds(4, 14, 88, 24);
btnAdd.setText("Add to table");
btnAdd.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
_actionPerformed(ATCMD_BTN_ADD);
}
public void widgetDefaultSelected(SelectionEvent event) {
}
});
//------------------------------######### del button ##########---------------------------------
Button btnDelItem = new Button(group_btn, SWT.NONE);
btnDelItem.setBounds(4, 47, 88, 24);
btnDelItem.setText("Item delete");
btnDelItem.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
_actionPerformed(ATCMD_BTN_DEL);
}
public void widgetDefaultSelected(SelectionEvent event) {
}
});
//------------------------------######### run button ##########---------------------------------
btnRun = new Button(group_btn, SWT.NONE);
btnRun.setFont(SWTResourceManager.getFont("굴림", 9, SWT.BOLD));
btnRun.setBounds(4, 80, 88, 24);
btnRun.setText("Do");
new Label(SerialComm_composite, SWT.NONE);
btnRun.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
_actionPerformed(ATCMD_BTN_DO);
}
public void widgetDefaultSelected(SelectionEvent event) {
}
});
//------------------------------######### table ##########---------------------------------
CmdTable = new Table(SerialComm_composite, SWT.BORDER | SWT.FULL_SELECTION);
GridData gd_table = new GridData(SWT.FILL, SWT.TOP, true, true, 2, 1);
gd_table.heightHint = 70;
CmdTable.setLayoutData(gd_table);
CmdTable.setHeaderVisible(false);
CmdTable.setLinesVisible(false);
new Label(SerialComm_composite, SWT.NONE);
new Label(SerialComm_composite, SWT.NONE);
//------------------------------######### Text ##########---------------------------------
mLogText = new StyledText(SerialComm_composite, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
mLogText.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
mLogText.setDoubleClickEnabled(false);
GridData gd_styledText = new GridData(SWT.FILL, SWT.FILL, true, false, 3, 6);
gd_styledText.heightHint = 192;
mLogText.setLayoutData(gd_styledText);
mLogText.setText("");
mLogText.setEnabled(false);
mLogText.setEditable(false);
new Label(SerialComm_composite, SWT.NONE);
new Label(SerialComm_composite, SWT.NONE);
new Label(SerialComm_composite, SWT.NONE);
new Label(SerialComm_composite, SWT.NONE);
new Label(SerialComm_composite, SWT.NONE);
new Label(SerialComm_composite, SWT.NONE);
new Label(SerialComm_composite, SWT.NONE);
new Label(SerialComm_composite, SWT.NONE);
mLogText.addLineStyleListener(new LineStyleListener() {
public void lineGetStyle(LineStyleEvent event) {
if(info_highlight_keyword == null || info_highlight_keyword.length() == 0) {
event.styles = new StyleRange[0];
return;
}
String line = event.lineText;
int cursor = -1;
LinkedList<StyleRange> list = new LinkedList<StyleRange>();
while( (cursor = line.indexOf(info_highlight_keyword, cursor+1)) >= 0) {
list.add(getHighlightStyle(event.lineOffset+cursor, info_highlight_keyword.length()));
}
event.styles = (StyleRange[]) list.toArray(new StyleRange[list.size()]);
}
});
mLogText.addExtendedModifyListener(new ExtendedModifyListener() {
public void modifyText(ExtendedModifyEvent event){
if (serialConnection.getIsEchoStr() || lock_myself) {
return ;
}
String currText = mLogText.getText();
String newText = currText.substring(event.start, event.start + event.length);
if (newText.equals("\r\n")) {
if (!serialConnection.isOpen()) {
AsyncMsgBoxDraw.MessageBoxDraw(AndroSuker_MainCls.getShellInstance(), "Warning", "아직 com port가 연결되지 않았습니다.!!", SWT.OK);
return ;
}
if (mCurrentCmdStr.length() <= 0)
return ;
if (AndroSuker_Debug.DEBUG_MODE_ON) {
System.out.println("======== a 1 ========");
}
lock_myself = true;
serialCommTask.asyncSendEvent(thisShell, serialConnection, mLogText, mCurrentCmdStr.trim(), 100);
mCurrentCmdStr = "";
} else {
mCurrentCmdStr = mLogText.getLine(mLogText.getLineCount()-1);
}
}
});
//------------------------------######### port button ##########---------------------------------
btnOpenPort = new Button(SerialComm_composite, SWT.NONE);
btnOpenPort.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, false, false, 1, 1));
btnOpenPort.setText("Open port");
btnOpenPort.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
_actionPerformed(ATCMD_BTN_OPENPORT);
}
public void widgetDefaultSelected(SelectionEvent event) {
}
});
btnClosePort = new Button(SerialComm_composite, SWT.NONE);
btnClosePort.setText("Close port");
btnClosePort.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
_actionPerformed(ATCMD_BTN_CLOSEPORT);
}
public void widgetDefaultSelected(SelectionEvent event) {
}
});
//------------------------------######### Group2 ##########---------------------------------
comboGroup = new Group(SerialComm_composite, SWT.NONE);
GridData gd_group = new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1);
gd_group.heightHint = 177;
gd_group.widthHint = 172;
comboGroup.setLayoutData(gd_group);
combo_atcmd_port = new Combo(comboGroup, SWT.NONE);
combo_atcmd_port.setBounds(80, 25, 86, 20);
combo_atcmd_port.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
serialParameters.setPortName(combo_atcmd_port.getSelectionIndex());
}
});
combo_atcmd_baudrate = new Combo(comboGroup, SWT.NONE);
combo_atcmd_baudrate.setBounds(80, 51, 86, 20);
combo_atcmd_data = new Combo(comboGroup, SWT.NONE);
combo_atcmd_data.setBounds(80, 77, 86, 20);
combo_atcmd_parity = new Combo(comboGroup, SWT.NONE);
combo_atcmd_parity.setBounds(80, 105, 86, 20);
combo_atcmd_stop = new Combo(comboGroup, SWT.NONE);
combo_atcmd_stop.setBounds(80, 131, 86, 20);
combo_atcmd_flowcontrol = new Combo(comboGroup, SWT.NONE);
combo_atcmd_flowcontrol.setBounds(80, 157, 86, 20);
Label lbl_atcmd_port = new Label(comboGroup, SWT.NONE);
lbl_atcmd_port.setBounds(13, 28, 61, 12);
lbl_atcmd_port.setText("Port");
Label lbl_atcmd_baudrate = new Label(comboGroup, SWT.NONE);
lbl_atcmd_baudrate.setBounds(13, 51, 61, 12);
lbl_atcmd_baudrate.setText("Baud rate");
Label lbl_atcmd_data = new Label(comboGroup, SWT.NONE);
lbl_atcmd_data.setBounds(13, 77, 61, 12);
lbl_atcmd_data.setText("Data");
Label lbl_atcmd_parity = new Label(comboGroup, SWT.NONE);
lbl_atcmd_parity.setBounds(13, 105, 61, 12);
lbl_atcmd_parity.setText("Parity");
Label lbl_atcmd_stop = new Label(comboGroup, SWT.NONE);
lbl_atcmd_stop.setBounds(13, 131, 61, 12);
lbl_atcmd_stop.setText("Stop");
Label lbl_atcmd_flowcontrol = new Label(comboGroup, SWT.NONE);
lbl_atcmd_flowcontrol.setBounds(13, 157, 61, 12);
lbl_atcmd_flowcontrol.setText("Flow control");
btnClearText = new Button(SerialComm_composite, SWT.NONE);
GridData gd_btnNewButton_5 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_btnNewButton_5.widthHint = 127;
btnClearText.setLayoutData(gd_btnNewButton_5);
btnClearText.setText("Clear Text");
btnClearText.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
_actionPerformed(ATCMD_BTN_CLEARTEXT);
}
public void widgetDefaultSelected(SelectionEvent event) {
}
});
btnCheckButton = new Button(SerialComm_composite, SWT.CHECK);
btnCheckButton.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, false, 1, 1));
btnCheckButton.setText("LG ATCMD");
new Label(SerialComm_composite, SWT.NONE);
btnCheckButton.setSelection(true);
btnCheckButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
_actionPerformed(ATCMD_CHK_BTN);
}
public void widgetDefaultSelected(SelectionEvent event) {
}
});
btnComPortScan = new Button(SerialComm_composite, SWT.NONE);
btnComPortScan.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
btnComPortScan.setText("Com Port Scan");
btnComPortScan.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
_actionPerformed(ATCMD_BTN_SCAN);
}
public void widgetDefaultSelected(SelectionEvent event) {
}
});
}
private StyleRange getHighlightStyle(int startOffset, int length) {
StyleRange styleRange = new StyleRange();
styleRange.start = startOffset;
styleRange.length = length;
return styleRange;
}
public void _actionPerformed(int action) {
if (ATCMD_BTN_OPENPORT == action) {
try {
setSerialParameters();
serialConnection.openConnection();
} catch (SerialConnectionException e2) {
AsyncMsgBoxDraw.MessageBoxDraw(AndroSuker_MainCls.getShellInstance(), "Error", "com port 연결 실패 !!", SWT.OK);
return;
}
mLogText.setEnabled(true);
mLogText.setEditable(true);
btnOpenPort.setEnabled(false);
btnClosePort.setEnabled(true);
setEnableCombo(false);
btnRun.setEnabled(true);
btnComPortScan.setEnabled(false);
mLogText.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
} else if (ATCMD_BTN_CLOSEPORT == action) {
mLogText.setEnabled(false);
mLogText.setEditable(false);
btnOpenPort.setEnabled(true);
btnClosePort.setEnabled(false);
setEnableCombo(true);
btnRun.setEnabled(false);
btnComPortScan.setEnabled(true);
serialConnection.closeConnection();
mLogText.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
} else if (ATCMD_BTN_ADD == action) {
if (values_cnt == MAX_TABLE_CNT) {
AsyncMsgBoxDraw.MessageBoxDraw(AndroSuker_MainCls.getShellInstance(), "Warning", "더이상 추가할 수 없습니다. max 50개임", SWT.OK);
}
if (addCommandEdit.getText().length() > 1) {
TableItem item = new TableItem(CmdTable, SWT.NONE, values_cnt);
item.setText(addCommandEdit.getText().toString());
values_cnt++;
addCommandEdit.setText("");
}
} else if (ATCMD_BTN_DEL == action) {
CmdTable.remove(CmdTable.getSelectionIndices());
values_cnt--;
CmdTable.update();
} else if (ATCMD_BTN_DO == action) {
TableItem[] selectItem = CmdTable.getSelection();
lock_myself = true;
serialCommTask.asyncSendEvent(thisShell, serialConnection, mLogText, selectItem[0].getText(), 100);
mCurrentCmdStr = "";
} else if (ATCMD_BTN_CLEARTEXT == action) {
mLogText.setText("");
mCurrentCmdStr = "";
} else if (ATCMD_BTN_SCAN == action) {
listPortChoices();
AsyncMsgBoxDraw.MessageBoxDraw(AndroSuker_MainCls.getShellInstance(), "Success", "Scan 완료!", SWT.OK);
} else if (ATCMD_CHK_BTN == action) {
if (btnCheckButton.getSelection()) {
btnCheckButton.setSelection(true);
serialConnection.setATCMDpurpose(serialConnection.SERIALCOMM_PURPOSE_LGATCMD);
}
else {
btnCheckButton.setSelection(false);
serialConnection.setATCMDpurpose(serialConnection.SERIALCOMM_PURPOSE_GENERAL);
}
}
}
private static void initParameters()
{
combo_atcmd_baudrate.add("300");
combo_atcmd_baudrate.add("2400");
combo_atcmd_baudrate.add("9600");
combo_atcmd_baudrate.add("14400");
combo_atcmd_baudrate.add("28800");
combo_atcmd_baudrate.add("38400");
combo_atcmd_baudrate.add("57600");
combo_atcmd_baudrate.add("152000");
combo_atcmd_data.add("5");
combo_atcmd_data.add("6");
combo_atcmd_data.add("7");
combo_atcmd_data.add("8");
combo_atcmd_parity.add("None");
combo_atcmd_parity.add("Even");
combo_atcmd_parity.add("Odd");
combo_atcmd_stop.add("1");
combo_atcmd_stop.add("1.5");
combo_atcmd_stop.add("2");
combo_atcmd_flowcontrol.add("None");
combo_atcmd_flowcontrol.add("Xon/Xoff");
combo_atcmd_flowcontrol.add("RTS/CTS");
}
private void setEnableCombo(boolean available) {
combo_atcmd_port.setEnabled(available);
combo_atcmd_baudrate.setEnabled(available);
combo_atcmd_data.setEnabled(available);
combo_atcmd_parity.setEnabled(available);
combo_atcmd_stop.setEnabled(available);
combo_atcmd_flowcontrol.setEnabled(available);
}
static void listPortChoices() {
if (combo_atcmd_port != null) {
combo_atcmd_port.removeAll();
}
Enumeration<?> pList = CommPortIdentifier.getPortIdentifiers();
while (pList.hasMoreElements()) {
CommPortIdentifier cpi = (CommPortIdentifier)pList.nextElement();
serialParameters.setPortInfoHash(cpi.getName(), cpi, combo_atcmd_port);
// System.out.println("Port " + cpi.getName());
}
combo_atcmd_port.select(-1);
}
private static void setSerialParameters() {
serialParameters.setBaudRate(serialParameters.getBaudRateIndexToString(combo_atcmd_baudrate.getSelectionIndex()));
serialParameters.setDatabits(serialParameters.getDatabitsIndexToString(combo_atcmd_data.getSelectionIndex()));
serialParameters.setParity(serialParameters.getParityIndexToString(combo_atcmd_parity.getSelectionIndex()));
serialParameters.setStopbits(serialParameters.getStopIndexToString(combo_atcmd_stop.getSelectionIndex()));
serialParameters.setFlowControlIn(serialParameters.getFlowControlIndexToString(combo_atcmd_flowcontrol.getSelectionIndex()));
serialParameters.setFlowControlOut(serialParameters.getFlowControlIndexToString(combo_atcmd_flowcontrol.getSelectionIndex()));
}
@Override
public void update(Observable o, Object arg) {
serialCommTask.asyncReceiveReturnStr(thisShell, serialConnection, mLogText, 200);
lock_myself = false;
}
}
class serialCommTask {
final static Timer timer = new Timer();
static Shell thisShell;
static StyledText styledText;
static boolean ret;
static AndroSuker_SerialConnection sC;
static String sendStr;
static boolean isLGATCMD;
public static void asyncSendEvent(Shell shell, AndroSuker_SerialConnection serialConnection, StyledText msgText, String s, long d) {
thisShell = shell;
sC = serialConnection;
styledText = msgText;
sendStr = s;
TimerTask asyncLogTextTimer = new TimerTask() {
public void run() {
if (thisShell.isDisposed())
return ;
thisShell.getDisplay().asyncExec(new Runnable() {
public void run() {
try {
sC.sendEvent(sendStr);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
};
timer.schedule(asyncLogTextTimer, d);
}
public static void asyncReceiveReturnStr(Shell shell, AndroSuker_SerialConnection serialConnection, StyledText msgText, long d) {
thisShell = shell;
sC = serialConnection;
styledText = msgText;
TimerTask asyncLogTextTimer = new TimerTask() {
public void run() {
if (thisShell.isDisposed())
return ;
thisShell.getDisplay().asyncExec(new Runnable() {
public void run() {
if (sC.getReturnString().length() > 0) {
sC.setIsEchoStr(true);
styledText.append(sC.getReturnString());
styledText.setCaretOffset(styledText.getText().length());
styledText.setFocus();
styledText.selectAll();
styledText.setSelection(styledText.getCharCount());
sC.setIsEchoStr(false);
sC.setReturnString("");
}
}
});
}
};
timer.schedule(asyncLogTextTimer, d);
}
public static void stopTimer() {
if (timer != null) {
timer.cancel();
timer.purge();
}
}
}
|
package studio.baka.originiumcraft;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import org.apache.logging.log4j.Logger;
import studio.baka.originiumcraft.command.CommandFreshPRTS;
import studio.baka.originiumcraft.common.CommonProxy;
import studio.baka.originiumcraft.util.ReferenceConsts;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
@Mod(modid = ReferenceConsts.MODID, name = ReferenceConsts.MODNAME, version = ReferenceConsts.VERSION)
public class OriginiumCraft {
@Mod.Instance
public static OriginiumCraft instance;
public static Logger logger;
@SidedProxy(clientSide = ReferenceConsts.CLIENT_PROXY,serverSide = ReferenceConsts.COMMON_PROXY)
public static CommonProxy proxy;
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
logger = event.getModLog();
proxy.preInit(event);
}
@EventHandler
public void init(FMLInitializationEvent event)
{
proxy.init(event);
}
@EventHandler
public static void onServerStarting(FMLServerStartingEvent event){
event.registerServerCommand(new CommandFreshPRTS());
}
}
|
package com.kaysanshi.springsecurityoauth2.configure;
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 {
// 该对象用来支持 password 模式
@Autowired
AuthenticationManager authenticationManager;
// 将令牌信息存储redis中
@Autowired
TokenStore redisToken;
// 该对象将为刷新token提供支持
@Autowired
UserDetailsService userDetailsService;
/**
* 配置密码加密,因为再UserDetailsService是依赖与这个类的。
*
* @return
*/
// 指定密码的加密方式
@Bean
PasswordEncoder passwordEncoder() {
// 使用BCrypt强哈希函数加密方案(密钥迭代次数默认为10)
return new BCryptPasswordEncoder();
}
/**
* ClientDetailsServiceConfigurer
* 主要是注入ClientDetailsService实例对象(唯一配置注入)。其它地方可以通过ClientDetailsServiceConfigurer调用开发配置的ClientDetailsService。
* 系统提供的二个ClientDetailsService实现类:JdbcClientDetailsService、InMemoryClientDetailsService。
*
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {
// 配置一个客户端用于password认证的。同时也可以同时配置两个,可以再配置一个基于client认证的。
clients.inMemory()
.withClient("password")
.authorizedGrantTypes("password", "refresh_token") //授权模式为password和refresh_token两种
.accessTokenValiditySeconds(1800) // 配置access_token的过期时间
.resourceIds("rid") //配置资源id
.scopes("all") // 允许授权范围
.secret("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq") //123加密后的密码
;
}
/**
* AuthorizationServerEndpointsConfigurer 访问端点配置 是一个装载类
* 装载Endpoints所有相关的类配置(AuthorizationServer、TokenServices、TokenStore、ClientDetailsService、UserDetailsService)。
* tokenService用于存到redis中
*
* @param endpoints
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(redisToken) //配置令牌的存到redis
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
/**
* AuthorizationServerSecurityConfigurer继承SecurityConfigurerAdapter.
* 也就是一个 Spring Security安全配置提供给AuthorizationServer去配置AuthorizationServer的端点(/oauth/****)的安全访问规则、过滤器Filter。
*
* @param security
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
// 表示支持 client_id 和 client_secret 做登录认证
// 允许使用表单认证
security.allowFormAuthenticationForClients();
}
}
|
package com.ricex.cartracker.common.viewmodel.entity;
public class CommandViewModel {
private String name;
private String pid;
private boolean supported;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the pid
*/
public String getPid() {
return pid;
}
/**
* @param pid the pid to set
*/
public void setPid(String pid) {
this.pid = pid;
}
/**
* @return the supported
*/
public boolean isSupported() {
return supported;
}
/**
* @param supported the supported to set
*/
public void setSupported(boolean supported) {
this.supported = supported;
}
}
|
package org.example;
import org.example.util.CanReplace;
import org.example.util.impl.Replacer;
import org.example.util.impl.SimpleQualifier;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Application {
public static void main(String[] args) {
CanReplace replacer = new Replacer(new SimpleQualifier());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String string;
try {
string = bufferedReader.readLine();
System.out.println(replacer.replace(string));
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.projeto.fragment;
import android.app.DatePickerDialog;
import android.widget.DatePicker;
import android.widget.EditText;
import com.projeto.lib.DataLib;
/**
* Created by leo on 3/18/16.
*/
public class DataDialogListener implements DatePickerDialog.OnDateSetListener {
private EditText editData;
public DataDialogListener(EditText editData) {
this.editData = editData;
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String data = DataLib.getDataFormatada(dayOfMonth, monthOfYear+1, year);
editData.setText(data);
}
}
|
package composites;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import main.TestingFrame;
import util.ParseMessage;
import util.Util;
public class InverseReplacementComposite extends GeneralComposite {
private Map<String, Set<String>> inverseMap;
private Map<String, String> replacements;
private TableViewer tableViewer;
private CheckboxTableViewer checkboxTableViewer;
private Table table;
private Table table_2;
public InverseReplacementComposite(Composite parent, int style) {
super(parent, style);
}
@Override
protected void createContent(Composite content, int style) {
content.setLayout(new FillLayout(SWT.HORIZONTAL));
TabFolder tabFolder = new TabFolder(content, SWT.NONE);
TabItem tbtmCheckReplacedValues_1 = new TabItem(tabFolder, SWT.NONE);
tbtmCheckReplacedValues_1.setText("Check Replaced Values");
Composite composite = new Composite(tabFolder, SWT.NONE);
tbtmCheckReplacedValues_1.setControl(composite);
composite.setLayout(new GridLayout(2, false));
checkboxTableViewer = CheckboxTableViewer.newCheckList(composite, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
checkboxTableViewer.setAllChecked(false);
checkboxTableViewer.setContentProvider(ArrayContentProvider.getInstance());
checkboxTableViewer.setComparator(new ViewerComparator()); //By default, it will sort based on the toString()
table_2 = checkboxTableViewer.getTable();
table_2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2));
table_2.setSize(444, 265);
table_2.setLinesVisible(true);
table_2.setHeaderVisible(true);
TableViewerColumn tableViewerColumn_5 = new TableViewerColumn(checkboxTableViewer, SWT.NONE);
TableColumn tblclmnBeforeReplacement_1 = tableViewerColumn_5.getColumn();
tblclmnBeforeReplacement_1.setWidth(100);
tblclmnBeforeReplacement_1.setText("Before Replacement");
tableViewerColumn_5.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
if (element instanceof Map.Entry<?, ?>) {
Map.Entry<String, String> entry = (Entry<String, String>) element;
return entry.getKey();
}
return super.getText(element);
}
});
TableViewerColumn tableViewerColumn_6 = new TableViewerColumn(checkboxTableViewer, SWT.NONE);
TableColumn tblclmnAfterReplacement_1 = tableViewerColumn_6.getColumn();
tblclmnAfterReplacement_1.setWidth(100);
tblclmnAfterReplacement_1.setText("After Replacement");
tableViewerColumn_6.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
if (element instanceof Map.Entry<?, ?>) {
Map.Entry<String, String> entry = (Entry<String, String>) element;
return entry.getValue();
}
return super.getText(element);
}
});
Button btnNewButton = new Button(composite, SWT.NONE);
btnNewButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1));
btnNewButton.setText("Check All");
btnNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
checkboxTableViewer.setAllChecked(true);
}
});
Button btnUncheckAll = new Button(composite, SWT.NONE);
btnUncheckAll.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, true, 1, 1));
btnUncheckAll.setText("Uncheck All");
btnUncheckAll.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
checkboxTableViewer.setAllChecked(false);
}
});
TabItem tbtmInversemap = new TabItem(tabFolder, SWT.NONE);
tbtmInversemap.setText("Inverse Map");
tableViewer = new TableViewer(tabFolder, SWT.BORDER | SWT.FULL_SELECTION);
tableViewer.setContentProvider(ArrayContentProvider.getInstance());
table = tableViewer.getTable();
table.setLinesVisible(true);
table.setHeaderVisible(true);
tbtmInversemap.setControl(table);
TableViewerColumn tableViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE);
TableColumn tblclmnValue = tableViewerColumn.getColumn();
tblclmnValue.setWidth(100);
tblclmnValue.setText("Value");
tableViewerColumn.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
if (element instanceof Map.Entry<?, ?>) {
Map.Entry<String, Set<String>> entry = (Entry<String, Set<String>>) element;
return entry.getKey();
} else {
return super.getText(element);
}
}
});
TableViewerColumn tableViewerColumn_1 = new TableViewerColumn(tableViewer, SWT.NONE);
TableColumn tblclmnAttributes = tableViewerColumn_1.getColumn();
tblclmnAttributes.setWidth(100);
tblclmnAttributes.setText("Attributes");
tableViewerColumn_1.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
if (element instanceof Map.Entry<?, ?>) {
Map.Entry<String, Set<String>> entry = (Entry<String, Set<String>>) element;
return entry.getValue().toString();
} else {
return super.getText(element);
}
}
});
nextButton.setEnabled(true);
}
public void setInput(List<ParseMessagesComposite.Entry> entries, Set<String> unparsedMessages){
inverseMap = buildInverseMap(entries);
Map<String, String> tmpMap = buildUnparsedMessagesReplacementCandidates(unparsedMessages);
replacements = buildParsedMessagesReplacementCandidates(entries);
replacements.putAll(tmpMap);
System.out.println("List<ParseMessagesComposite.Entry> entries: "+ entries.size() +"; UnparsedMessagesReplacementCandidates:"+ tmpMap.size());
tableViewer.setInput(inverseMap.entrySet());
for (TableColumn column : table.getColumns()) {
column.pack();
}
checkboxTableViewer.setInput(replacements.entrySet());
for (TableColumn column : table_2.getColumns()) {
column.pack();
}
}
private Map<String, Set<String>> buildInverseMap(List<ParseMessagesComposite.Entry> entries) {
Map<String, Set<String>> returnMap = new HashMap<String, Set<String>>();
Map<String, String> valuesMap;
Set<String> attributesSet;
for (ParseMessagesComposite.Entry pEntry : entries) {
valuesMap = pEntry.getParsedValues();
for (Entry<String, String> entry : valuesMap.entrySet()) {
if(!Util.isInteger(entry.getKey())) {
attributesSet = returnMap.get(entry.getValue());
// случилось, что пустые значения добавляются в placeholdersRoot и подставляются в обратной замене
// Так я от этого защищаюсь.
if(entry.getValue().isEmpty()){
// System.out.println("entry.getValue() is \"\"");
continue;
}
if (attributesSet == null) {
attributesSet = new HashSet<String>();
returnMap.put(entry.getValue(), attributesSet);
attributesSet.add(entry.getKey());
} else {
attributesSet.add(entry.getKey());
}
}
}
}
return returnMap;
}
/**
* Метод на основе построенных обратных соответствий и переданного списка неразобранных сообщений
* строит кандидаты-соответствия для замены.
* @param unparsedMessages
*/
private Map<String, String> buildUnparsedMessagesReplacementCandidates(Set<String> unparsedMessages) {
Map <String, String> replacementCandidates = new HashMap<String, String>();
String template;
String regexp;
for(String message: unparsedMessages){
for (Entry<String, Set<String>> entry : inverseMap.entrySet()) {
// надо понять как-то, что нам надо сейчас заменять или же
// не нужно
if (entry.getValue().size() == 1) {
/*
* Текущее решение заключается в том, чтобы просто втупую
* заменять, а ошибки обнаруживать и исправлять руками,
* "дообучая" разбор =)
*/
regexp = ParseMessage.escapeSpecialRegexChars(entry.getKey());
template = message.replaceAll(regexp, "{" + entry.getValue().iterator().next() + "}");
if (!message.equals(template)) {
replacementCandidates.put(message, template);
}
}
}
}
return replacementCandidates;
}
/**
* Метод строит на основе разобранных сообщений обратные соответствия "сообщение - шаблон".
* При этом учитывается, что в шаблоне не должно быть нумерованных плейсхолдеров, только именованые.
* Нумерованные плейсхолдеры, оставшиеся после генерации шаблона, заменяются на значение -
* типа ничего не было.
* @param entries
* @return
*/
private Map<String, String> buildParsedMessagesReplacementCandidates(List<ParseMessagesComposite.Entry> entries) {
Map <String, String> replacementCandidates = new HashMap<String, String>();
Map<String, String> valuesMap;
String template;
for (ParseMessagesComposite.Entry pEntry : entries) {
valuesMap = pEntry.getParsedValues();
template = pEntry.getTemplate();
for (Entry<String, String> entry : valuesMap.entrySet()) {
if(Util.isInteger(entry.getKey())){
template = template.replace("{"+entry.getKey()+"}", valuesMap.get(entry.getKey()));
}
}
replacementCandidates.put(pEntry.getMessage(), template);
}
return replacementCandidates;
}
@Override
protected void nextPressed() {
replaceCheckedMessages(TestingFrame.messages);
Composite parent = getParent();
this.dispose();
SourceDataComposite sdc = new SourceDataComposite(parent, SWT.NONE);
sdc.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
sdc.setInput(TestingFrame.messages);
}
/**
* Заменяет в переданном списке сообщения, отмеченные в таблице, шаблоны
* @param messages
*/
public void replaceCheckedMessages(List<String> messages) {
Object[] checkedEntriesArray = checkboxTableViewer.getCheckedElements();
Map.Entry<String, String> entry;
for (Object o : checkedEntriesArray) {
if (o instanceof Map.Entry<?, ?>) {
entry = (Map.Entry<String, String>) o;
messages.set(messages.indexOf(entry.getKey()), entry.getValue());
} else {
throw new RuntimeException("object class is: " + o.getClass());
}
}
}
}
|
package com.Arrays;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MissingNumber {
public static void main (String[] args) throws FileNotFoundException {
//code
Scanner input = new Scanner(new File("input/dummy"));
int testCases = input.nextInt();
// starting time
long start = System.currentTimeMillis();
for(int i = 0; i < testCases; i++){
int numbers = input.nextInt();
int[] given = new int[numbers-1];
for(int j = 0; j < (numbers-1); j++)
given[j] = input.nextInt();
int missing = findMissing(given, numbers);
System.out.println(missing);
}
// starting time
long end = System.currentTimeMillis();
System.out.println("Time takes " +
(end - start) + "ms");
}
private static int findMissing(int[] given, int numbers){
int x1 = given[0];
int x2 = 1;
for(int i = 1; i < given.length; i++){
x1 = x1 ^ given[i];
}
for(int i = 2; i <= numbers; i++){
x2 = x2 ^ i;
}
return (x1 ^ x2);
}
}
|
package com.neo.test.druid;
import java.util.Map;
import java.util.Set;
import com.alibaba.druid.sql.ast.SQLOrderBy;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.expr.SQLInListExpr;
import com.alibaba.druid.sql.ast.statement.SQLSelectOrderByItem;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.visitor.SchemaStatVisitor;
import com.alibaba.druid.stat.TableStat;
import com.alibaba.druid.stat.TableStat.Column;
import com.alibaba.druid.stat.TableStat.Name;
public class MParseSql {
public static void main(String[] args) {
String sql = "select o.*,t.* from ordertable o left join trans t on t.orderid=o.orderid";
MySqlStatementParser parser = new MySqlStatementParser(sql);
SQLStatement statement = parser.parseStatement();
SchemaStatVisitor visitor = new SchemaStatVisitor();
statement.accept(visitor);
Map<Name, TableStat> tables = visitor.getTables();
Set<Name> names = tables.keySet();
for (Name name : names) {
System.out.println(name.getName());
}
Set<Column> cols = visitor.getColumns();
for (Column column : cols) {
System.out.println(column.getName());
}
SQLSelectStatement selectStatement = (SQLSelectStatement)statement;
selectStatement.getSelect().setOrderBy(new SQLOrderBy(new SQLIdentifierExpr("o.orderid desc")));
System.out.println(selectStatement.toString());
}
}
|
package com.org.jms.hospitalmanagement.eligibilitycheck;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
public class EligibilityCheckerApp {
public static void main(String[] args) throws NamingException, JMSException, InterruptedException {
InitialContext initialContext = new InitialContext();
Queue requestQueue = (Queue) initialContext.lookup("queue/requestQueue");
try(ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
JMSContext context = connectionFactory.createContext("eligibilityUser", "eligibilityPass")){
JMSConsumer consumer1 = context.createConsumer(requestQueue);
JMSConsumer consumer2 = context.createConsumer(requestQueue);
for (int i = 0; i < 5; i++) {
System.out.println("1 : " + consumer1.receive());
System.out.println("2 : " + consumer2.receive());
}
// consumer.setMessageListener(new EligibilityCheckListener());
// Thread.sleep(10000);
}
}
}
|
package com.kgisl.code;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* StreamEmp
*/
public class StreamEmp {
public static void main(String[] args) {
Emp c1 = new Emp(10, "GK", 10000f);
Emp c2 = new Emp(11, "Gopal", 13000f);
Emp c3 = new Emp(12, "krish", 14000f);
Emp c4 = new Emp(13, "prabha", 15000f);
ArrayList<Emp> list = new ArrayList<>();
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
}
}
|
package com.tencent.mm.plugin.sns.model;
import com.tencent.mm.model.ap;
import com.tencent.mm.protocal.c.boh;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.x;
class u$2 implements Runnable {
final /* synthetic */ u noA;
final /* synthetic */ boolean noB;
final /* synthetic */ boh noC;
final /* synthetic */ ag noz;
u$2(u uVar, boolean z, boh boh, ag agVar) {
this.noA = uVar;
this.noB = z;
this.noC = boh;
this.noz = agVar;
}
public final void run() {
if (this.noB) {
for (ap apVar : u.afl()) {
x.i("MicroMsg.NetSceneNewSyncAlbum", "notify list ");
apVar.HG();
}
}
this.noz.sendEmptyMessage(0);
}
}
|
package com.psybrainy.eshop.persistence.mapper;
import com.psybrainy.eshop.domain.Product;
import com.psybrainy.eshop.persistence.entity.ProductEntity;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import java.util.List;
import java.util.Optional;
@Mapper(componentModel = "spring")
public interface ProductMapper {
@Mappings({
@Mapping(source = "productId", target = "productId"),
@Mapping(source = "name", target = "name"),
@Mapping(source = "price", target = "price"),
@Mapping(source = "stock", target = "stock"),
@Mapping(source = "status", target = "active")
})
Product toProduct(ProductEntity productEntity);
List<Product> toProducts(List<ProductEntity> productEntities);
@InheritInverseConfiguration
ProductEntity toProductEntity(Product product);
}
|
package com.s24.redjob.client;
import com.s24.redjob.AbstractDao;
import com.s24.redjob.RedJobRedisConnectionFactory;
import com.s24.redjob.channel.ChannelDaoImpl;
import com.s24.redjob.lock.LockDaoImpl;
import com.s24.redjob.queue.FifoDaoImpl;
import com.s24.redjob.worker.WorkerDaoImpl;
import com.s24.redjob.worker.json.ExecutionRedisSerializer;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
/**
* {@link FactoryBean} for easy creation of a {@link Client}.
*/
public class ClientFactoryBean implements FactoryBean<Client>, InitializingBean {
/**
* Worker dao.
*/
private final WorkerDaoImpl workerDao = new WorkerDaoImpl();
/**
* Queue dao.
*/
private final FifoDaoImpl fifoDao = new FifoDaoImpl();
/**
* Channel dao.
*/
private final ChannelDaoImpl channelDao = new ChannelDaoImpl();
/**
* Lock dao.
*/
private final LockDaoImpl lockDao = new LockDaoImpl();
/**
* The instance.
*/
private final ClientImpl client = new ClientImpl();
@Override
public void afterPropertiesSet() throws Exception {
workerDao.afterPropertiesSet();
fifoDao.afterPropertiesSet();
channelDao.afterPropertiesSet();
lockDao.afterPropertiesSet();
client.setWorkerDao(workerDao);
client.setFifoDao(fifoDao);
client.setChannelDao(channelDao);
client.setLockDao(lockDao);
client.afterPropertiesSet();
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public Class<Client> getObjectType() {
return Client.class;
}
@Override
public Client getObject() throws Exception {
return client;
}
//
// Injections.
//
/**
* {@link RedisConnectionFactory} to access Redis.
*/
public RedisConnectionFactory getConnectionFactory() {
return fifoDao.getConnectionFactory();
}
/**
* {@link RedisConnectionFactory} to access Redis.
*/
@RedJobRedisConnectionFactory
@Autowired
public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
workerDao.setConnectionFactory(connectionFactory);
fifoDao.setConnectionFactory(connectionFactory);
channelDao.setConnectionFactory(connectionFactory);
lockDao.setConnectionFactory(connectionFactory);
}
/**
* Redis "namespace" to use. Prefix for all Redis keys. Defaults to {@value AbstractDao#DEFAULT_NAMESPACE}.
*/
public String getNamespace() {
return fifoDao.getNamespace();
}
/**
* Redis "namespace" to use. Prefix for all Redis keys. Defaults to {@value AbstractDao#DEFAULT_NAMESPACE}.
*/
public void setNamespace(String namespace) {
workerDao.setNamespace(namespace);
fifoDao.setNamespace(namespace);
channelDao.setNamespace(namespace);
lockDao.setNamespace(namespace);
}
/**
* Redis serializer for job executions.
*/
public ExecutionRedisSerializer getExecutions() {
return fifoDao.getExecutions();
}
/**
* Redis serializer for job executions.
*/
public void setExecutions(ExecutionRedisSerializer executions) {
fifoDao.setExecutions(executions);
channelDao.setExecutions(executions);
}
}
|
package VSMPhraseEmbeddings;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.logging.Logger;
import jeigen.DenseMatrix;
import no.uib.cipr.matrix.DenseVector;
import no.uib.cipr.matrix.VectorEntry;
import Jama.Matrix;
import VSMLogger.VSMLogger;
import VSMUtilityClasses.VSMUtil;
public class ReadPhraseEmbeddingMap {
private static final Logger LOGGER;
private static final String phraseEmbeddingsURL;
private static HashMap<String, DenseVector> embeddingsMap;
private static final String phraseEmbeddingMatrixURL;
static {
LOGGER = VSMLogger.setup(ReadPhraseEmbeddingMap.class.getName());
phraseEmbeddingsURL = "/group/project/vsm-nfs/PhraseEmbeddings/phraseEmbeddings.ser";
phraseEmbeddingMatrixURL = "/group/project/vsm-nfs/PhraseEmbeddings/phraseEmbeddingsNorm.ser";
}
public static void main(String... args) {
getUnnormalizedEmneddingsMap();
normalizeEmbeddingsMap();
serializeEmbeddingsMap();
}
private static void getUnnormalizedEmneddingsMap() {
ObjectInput in = null;
try {
System.out.println("Reading the object");
in = new ObjectInputStream(new FileInputStream(phraseEmbeddingsURL));
embeddingsMap = (HashMap<String, DenseVector>) in.readObject();
} catch (IOException e) {
LOGGER.severe("IOException while reading the object file" + e);
e.printStackTrace();
} catch (ClassNotFoundException e) {
LOGGER.severe("Class not found exception while reading the class"
+ e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void serializeEmbeddingsMap() {
System.out.println("+++SERIALIZING THE EmbeddingsMap OBJECT++");
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(
phraseEmbeddingMatrixURL));
out.writeObject(embeddingsMap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("++DONE SERIALIZATION++");
}
private static void normalizeEmbeddingsMap() {
System.out.println("Normalizing");
for (String phrase : embeddingsMap.keySet()) {
DenseVector vec = embeddingsMap.get(phrase);
normalizeVec(vec);
// overriding the previous vector with the normalized vector
embeddingsMap.put(phrase, vec);
}
System.out.println("NEW EMBEDDINGS MAP FORMED");
}
private static void normalizeVec(DenseVector vec) {
double norm2 = VSMUtil.norm2(vec.getData());
if (!(Double.isNaN(norm2))) {
vec = vec.scale((double) 1 / (double) norm2);
} else {
System.out.println("++++Norm is NAN+++");
LOGGER.severe("NORM is NAN for the vector");
}
}
}
|
package com.rsm.yuri.projecttaxilivredriver.editprofile;
import android.net.Uri;
import com.rsm.yuri.projecttaxilivredriver.historicchatslist.entities.Car;
import com.rsm.yuri.projecttaxilivredriver.historicchatslist.entities.Driver;
/**
* Created by yuri_ on 14/03/2018.
*/
public interface EditProfileRepository {
void saveProfile(Driver driver, Car car);
void updateDriver(Driver driver);
void updateCar(Car car);
void uploadPhoto(Uri selectedImageUri);
void retrieveDataUser();
/*void uploadPhotoDriver(Uri selectedImageUri);
void uploadPhotoCar(Uri selectedImageUri);*/
}
|
import java.io.*;
import java.util.*;
class Life
{
/*
* create a new 2D array, fill it with ' '
* representing that the entire board is empty.
*/
public static char[][] createNewBoard(int rows, int cols)
{
char[][] board = new char[rows][cols];
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
board[r][c] = ' ';
}
}
return board;
}
public static void printBoard(char[][] board)
{
for (int r = 0; r < board.length; r++)
{
for (int c = 0; c < board[r].length; c++)
{
System.out.printf("%c",board[r][c]);
}
System.out.println();
}
System.out.println("\n\n------------------\n\n");
}
/*
* set the cell (r,c) to value
*/
public static void setCell(char[][] board, int r, int c, char val)
{
if (r>=0 && r<board.length && c>=0 && c<board[r].length)
{
board[r][c] = val;
}
}
/*
* Count and return the number of living neigbords around board[r][c]
*/
public static int countNeighbours(char[][] board, int r, int c)
{
int count = 0;
//Account for EDGE cases
int rowStart, colStart;
if(r==0)
rowStart = 0;
else
rowStart = r - 1;
if(c == 0)
colStart = 0;
else
colStart = c -1;
//Loop through the 9 spots on the board
for(int row = rowStart; row >=0 && row < board.length && row <= r+1 ; row++)
{
for(int col = colStart; col >=0 && col < board.length && col <= c+1 ; col++)
{
if(board[row][col] == 'X' && !(col==c && row==r))
count++;
}
}
// count -= board[r][c] == 'X' ? 1 : 0;
return count;
}//End countNeighbours
/*
given a board and a cell, determine, based on the rules for
Conway's GOL if the cell is alive ('X') or dead (' ') in the
next generation.
*/
public static char getNextGenCell(char[][] board,int r, int c)
{
// Any LIVE cell with two or three live neighbours survives.
// Any dead cell with three live neighbours becomes a live cell.
// All other live cells die in the next generation. Similarly, all other dead cells stay dead.
int count = countNeighbours(board, r, c);
if(board[r][c] == 'X') //LIVE
{
if(count == 2 || count ==3)
return 'X';
else
return ' ';
}
else //dead
{
if(count ==3)
return 'X';
else
return ' ';
}
}
/*
scan the board to generate a NEW board with the
next generation
*/
public static char[][] generateNextBoard(char[][] board)
{
char newBoard[][] = new char[25][25];
for(int r = 0; r < board.length; r++)
for(int c = 0; c < board[r].length; c++)
newBoard[r][c] = getNextGenCell(board, r, c);
return newBoard;
}
//Generate a test "ten cell board"
public static void tenCellRow(char[][] board)
{
for(int i = 8; i < 18; i++)
setCell(board, 12, i, 'X');
}
public static void main(String[] args)
{
char[][] board;
board = createNewBoard(25,25);
tenCellRow(board);
printBoard(board);
Scanner in = new Scanner(System.in);
while(true)
{
System.out.println("Press enter to continue. Q to quit.");
String keyPress = in.nextLine();
if(keyPress.equals("Q") || keyPress.equals("q"))
break;
board = generateNextBoard(board);
printBoard(board);
}
}
}//End Class
|
package com.Home.Test.tests;
import com.Home.Test.modul.Goal;
import org.testng.annotations.Test;
public class GoalCreationTest extends TestBase{
@Test
public void creationGoalTest(){
app.goToGoalsPage();
app.ButtonSetGoal();
app.goalTitle(new Goal("Go to Amsterdam"));
app.choosingDate("15/06/2018", "02/06/2018");
app.closeGoal();
}
}
|
package com.example.park4me;
import java.util.List;
public class Regiao {
String nome;
double latitude;
double longitude;
List<Estacionamento> estacionamentos;
public Regiao(String nome, double latitude, double longitude, List<Estacionamento> estacionamentos) {
this.nome = nome;
this.latitude = latitude;
this.longitude = longitude;
this.estacionamentos = estacionamentos;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public List<Estacionamento> getEstacionamentos() {
return estacionamentos;
}
public void setEstacionamentos(List<Estacionamento> estacionamentos) {
this.estacionamentos = estacionamentos;
}
}
|
/*
* 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 com.ufc.poo.sorveteria.services.impl;
import com.ufc.poo.sorveteria.model.Produto;
import com.ufc.poo.sorveteria.repository.ProdutoRepository;
import com.ufc.poo.sorveteria.services.ProdutoService;
import com.ufc.poo.sorveteria.exceptions.NotFoundException;
import java.util.NoSuchElementException;
import javax.management.BadAttributeValueExpException;
/**
*
* @author cristiano
*/
public class ProdutoServiceImpl implements ProdutoService{
private ProdutoRepository produtoRepository;
public ProdutoServiceImpl() {
produtoRepository = new ProdutoRepository();
}
@Override
public Produto cadastrar(Produto produto) throws NotFoundException, BadAttributeValueExpException {
try {
produtoRepository.save(produto);
System.out.println("Produto salvo com sucesso.\n");
return produto;
} catch (NotFoundException e) {
throw new NotFoundException(e.getMessage());
} catch ( BadAttributeValueExpException e){
throw new BadAttributeValueExpException(e);
}
}
@Override
public void remover(Integer id) throws NotFoundException {
try {
produtoRepository.remove(id);
System.out.println("Produto removido com sucesso.\n");
} catch (NotFoundException e) {
throw new NotFoundException(e.getMessage());
}
}
@Override
public Produto editar(Produto produto) throws NotFoundException, BadAttributeValueExpException {
try {
produtoRepository.edit(produto);
System.out.println("Produto editado com sucesso.\n");
return produto;
} catch (NotFoundException e) {
throw new NotFoundException(e.getMessage());
} catch (BadAttributeValueExpException e){
throw new BadAttributeValueExpException(e);
}
}
@Override
public Produto buscar(Integer id) {
try {
return produtoRepository.findById(id);
} catch (NoSuchElementException e) {
throw new NoSuchElementException("Nenhum produto encontrado com o id '" + id + "'");
}
}
}
|
package xyz.hinyari.bmcplugin.command;
import org.bukkit.Location;
import xyz.hinyari.bmcplugin.BMCPlayer;
import xyz.hinyari.bmcplugin.BMCPlugin;
/**
* Created by Hinyari_Gohan on 2017/06/02.
*/
public class PlayerInfoCommand extends SubCommandAbst
{
private final static String COMMAND_NAME = "player";
@Override
public String getCommandName()
{
return COMMAND_NAME;
}
@Override
public boolean runCommand(BMCPlayer player, String label, String[] args)
{
if (!player.hasPermission("bmc.playerinfo"))
{
return player.noperm();
}
if (args.length <= 1)
{
return player.errmsg("引数が不足しています");
}
BMCPlayer target = player.getPlugin().getBMCPlayer(args[1]);
if (target == null)
{
return player.errmsg("そのプレイヤーは存在しません!");
}
StringBuilder locationB = new StringBuilder();
Location tarLoc = target.getPlayer().getLocation();
locationB.append("(").append(tarLoc.getWorld().getName()).append(", ")
.append(tarLoc.getBlockX()).append(", ").append(tarLoc.getBlockY()).append(", ")
.append(tarLoc.getBlockZ()).append(")");
player.msg("&a=== &r" + target.getName() + " &rさんの情報 &a===");
player.msg("プレイヤー名 : " + target.getName());
player.msg("UUID : " + target.getUUID().toString());
player.msg("場所 : " + locationB.toString());
player.msg("ゲームモード : " + target.getPlayer().getGameMode().toString());
player.msg("フライ状態 : " + (target.getPlayer().isFlying() ? "有効" : "無効"));
player.msg("IPアドレス : " + target.getPlayer().getAddress().getAddress().toString());
player.msg("導入MOD : " + target.getPlayer().getListeningPluginChannels().toString());
return false;
}
}
|
/**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.eval;
import java.io.File;
import com.rcwang.seal.rank.Ranker.Feature;
import com.rcwang.seal.util.Helper;
public class EvalResult {
public int trialID = 0;
public int numGoldEntity = 0;
public int numGoldSynonym = 0;
public double numCorrectSynonym = 0;
public double numCorrectEntity = 0;
public double numResultsAboveThreshold = 0;
public double maxF1Precision = 0;
public double maxF1Recall = 0;
public double maxF1Threshold = 0;
public double precision = 0;
public double recall = 0;
public double threshold = 0;
public double meanAvgPrecision = 0;
public File goldFile = null;
public String seeds = "";
public Feature method = null;
private StringBuffer buf = new StringBuffer();
public double getF1() { return Evaluator.computeF1(precision, recall); }
public double getMaxF1() { return Evaluator.computeF1(maxF1Precision, maxF1Recall); }
public String toString() {
buf.setLength(0);
buf.append("===================================================\n");
if (goldFile != null && method != null)
buf.append("Results of \"" + goldFile.getName() + "\" using method: " + method + "\n");
if (seeds != null && seeds.trim().length() > 0)
buf.append("Seeds: " + seeds + "\n");
buf.append("Avg. number of results above threshold: " + Helper.formatNumber(numResultsAboveThreshold, 3) + "\n");
buf.append("Avg. number of correct synonyms: " + Helper.formatNumber(numCorrectSynonym, 3) + " out of " + numGoldSynonym + "\n");
buf.append("Avg. number of correct entities: " + Helper.formatNumber(numCorrectEntity, 3) + " out of " + numGoldEntity + "\n");
buf.append("Max. Possible F1: " + Helper.formatNumber(getMaxF1(), 3));
buf.append(" (Precision: " + Helper.formatNumber(maxF1Precision, 3));
buf.append(", Recall: " + Helper.formatNumber(maxF1Recall, 3) + ")");
buf.append(" at threshold: " + Helper.formatNumber(maxF1Threshold, 3) + "\n");
buf.append("F1: " + Helper.formatNumber(getF1(), 3));
buf.append(" (Precision: " + Helper.formatNumber(precision, 3));
buf.append(", Recall: " + Helper.formatNumber(recall, 3) + ")");
buf.append(" at threshold: " + Helper.formatNumber(threshold, 3) + "\n");
buf.append("Mean Avg. Precision: " + Helper.formatNumber(meanAvgPrecision, 3));
return buf.toString();
}
public String toTabSeperated() {
buf.setLength(0);
buf.append(Evaluator.getDataName(goldFile)).append("\t");
buf.append(method).append("\t");
buf.append(getMaxF1()).append("\t");
buf.append(maxF1Precision).append("\t");
buf.append(maxF1Recall).append("\t");
buf.append(maxF1Threshold).append("\t");
buf.append(getF1()).append("\t");
buf.append(precision).append("\t");
buf.append(recall).append("\t");
buf.append(threshold).append("\t");
buf.append(meanAvgPrecision).append("\n");
return buf.toString();
}
}
|
package com.tencent.mm.by;
import com.tencent.mm.kernel.j;
import com.tencent.mm.sdk.platformtools.x;
public final class b {
private final byte[] dol = new byte[1];
private long uZL = -1;
public final void cDY() {
synchronized (this.dol) {
if (this.dol[0] == (byte) 0) {
this.dol[0] = (byte) 1;
this.uZL = Thread.currentThread().getId();
j.i("MicroMsg.WxConsumedLock", "lock %s", this);
} else {
try {
if (this.uZL != Thread.currentThread().getId()) {
j.i("MicroMsg.WxConsumedLock", "lock waiting %s", this);
this.dol.wait();
j.d("MicroMsg.WxConsumedLock", "unlock waiting %s", this);
} else {
j.d("MicroMsg.WxConsumedLock", "reenter lock not need waiting %s", this);
}
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.WxConsumedLock", e, "", new Object[0]);
}
}
}
}
public final void done() {
synchronized (this.dol) {
if (this.dol[0] != (byte) 0) {
this.dol[0] = (byte) 0;
this.uZL = -1;
this.dol.notifyAll();
j.i("MicroMsg.WxConsumedLock", "notify done %s", this);
}
}
}
}
|
package com.cg.javafillstack.collection.set;
import java.util.Iterator;
import java.util.LinkedHashSet;
public class TestD {
public static void main(String[] args) {
LinkedHashSet<Double> lhs=new LinkedHashSet<Double>();
lhs.add(2.44);
lhs.add(23.1);
lhs.add(1.4);
lhs.add(87.2);
System.out.println("Using Iterator");
Iterator<Double> it=lhs.iterator();
while(it.hasNext())
{
Double d=it.next();
System.out.println(d);
}
System.out.println("using foreach loop");
for(Double d : lhs)
{
System.out.println(d);
}
}
}
|
package com.bloomberg.server.arithmeticservice.businesslogic.exceptions;
public class ExpressionSolverException extends Exception {
public ExpressionSolverException(Exception e){
super(e);
}
}
|
package com.vilio.fms.fileLoad.service.impl;
import com.vilio.fms.common.service.CommonService;
import com.vilio.fms.commonMapper.dao.FmsFileLoadMapper;
import com.vilio.fms.commonMapper.pojo.FmsFileLoad;
import com.vilio.fms.fileLoad.service.FileDownloadService;
import com.vilio.fms.fileLoad.service.FileUploadService;
import com.vilio.fms.fileLoad.service.OssFileService;
import com.vilio.fms.fileLoad.util.Consts;
import com.vilio.fms.util.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by dell on 2017/5/17.
*/
@Service("fileUploadService")
public class FileUploadServiceImpl implements FileUploadService {
private static Logger logger = Logger.getLogger(FileUploadServiceImpl.class);
private static final String zipTempFile = "./zipTempFile/";
@Resource
private CommonService commonService;
@Resource
OssFileService ossFileService;
@Resource
FmsFileLoadMapper fmsFileLoadMapper;
@Resource
ConfigInfo configInfo;
@Resource
FileDownloadService fileDownloadService;
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.READ_COMMITTED,
rollbackFor = Exception.class)
public Map uploadFile(Map map) throws Exception {
return myUpload(map);
}
public Map zipAndUploadFile(Map map) throws Exception {
MultipartFile[] files = (MultipartFile[]) map.get("files");
String applyFilePath = (String) map.get("filePath");
if (StringUtils.isBlank(applyFilePath)) {
applyFilePath = Constants.APPLY_FILE_PATH;
}
String fileNameSer = CommonUtil.getCurrentTimeStr("F", "X");
//压缩
InputStream in = ZipUtil.writeZip(files, fileNameSer);
String interfaceType = Consts.UPLOAD_INTERFACE_TYPE;
if (StringUtils.isBlank(interfaceType)) {
interfaceType = Consts.UPLOAD_INTERFACE_TYPE_DEFAULT;
}
Map body = new HashMap();
List<Map> fileMaps = new ArrayList();
String serialNo = commonService.getUUID();
String fileSuffix = "zip";
String fileName;
fileName = fileNameSer + "." + fileSuffix;
//保存本地
FmsFileLoad fmsFileLoad = new FmsFileLoad();
fmsFileLoad.setInterfaceType(interfaceType);
fmsFileLoad.setFileName(fileName);
fmsFileLoad.setFilePath(applyFilePath);
fmsFileLoad.setFileSuffix(fileSuffix);
fmsFileLoad.setSerialNo(serialNo);
fmsFileLoad.setOriginalFileName(fileName);
fmsFileLoadMapper.saveFileLoad(fmsFileLoad);
String url = null;
if (Consts.UPLOAD_INTERFACE_TYPE_Oss.equals(interfaceType)) {
Map returnMap = ossFileService.uploadFile2(in, applyFilePath, fileName);
String md5key = (String) returnMap.get("md5key");
url = "/fileLoad/getFile" + "?serialNo=" + serialNo;
fmsFileLoad.setUrl(url);
fmsFileLoadMapper.modifyFileLoadUrl(fmsFileLoad);
}
//上传后删除本地生成文件
boolean flag = ZipUtil.deleteZipFile(fileNameSer, in);
Map fileMap = new HashMap();
fileMap.put("serialNo", fmsFileLoad.getSerialNo());
fileMap.put("fileName", fileName);
fileMap.put("url", url);
fileMaps.add(fileMap);
body.put("fileMaps", fileMaps);
body.put("returnCode", ReturnCode.SUCCESS_CODE);
body.put("returnMessage", "完成上传");
Map result = new HashMap();
result.put("body", body);
return result;
}
/**
* 个性化定制接口,仅供生成外发压缩材料
*
* @param map
* @return
* @throws Exception
*/
@Override
public Map zipAndUploadFileSerialNoList(Map map) throws Exception {
String applyFilePath = (String) map.get("filePath");
String originalFileName = (String) map.get("fileName");
if (StringUtils.isBlank(applyFilePath)) {
applyFilePath = Constants.APPLY_FILE_PATH;
}
List<Map> serialNoList = (List) map.get("serialNoList");
if (null == serialNoList) {
return null;
}
String[] fileTypeArray = {"身份证", "户口本", "婚姻证明", "征信报告", "抵押房产证", "产调", "评估单", "银行流水", "看房照片", "备用房产证", "企业材料", "风险信息查询", "借款申请书及外访调查报告", "放款银行卡", "其他"};
int dirIndex = 1;
String zipDirName = zipTempFile + CommonUtil.getCurrentTimeStr("tempzip_", "");
String realZipDirName = zipDirName + File.separator + originalFileName;
File zipDirFile = new File(zipDirName);//用以区别唯一性
File realZipDirFile = new File(realZipDirName);//用以打包zip
if(!realZipDirFile.exists()){
realZipDirFile.mkdirs();
}
for (String dirType : fileTypeArray) {
boolean needPlus = false;
for (Map serialNoMap : serialNoList) {
boolean haveMatch = false;
String finalFileName = "";
InputStream in = null;
//若文件有类型,则按照不同的类型分类放入到对应的文件夹里
if (dirType.equals(serialNoMap.get(Fields.PARAM_FILE_TYPE))) {
haveMatch = true;
needPlus = true;
Map requestMap = new HashMap();
requestMap.put("serialNo", serialNoMap.get("serialNo"));
Map resonMap = fileDownloadService.getFile(requestMap);
Map body = (Map) resonMap.get("body");
in = (InputStream) resonMap.get("is");
String typeFileName = String.format("%02d", dirIndex);
String typeDir = realZipDirName + File.separator + typeFileName + dirType;
finalFileName = typeDir + File.separator + body.get("fileName");
//分类的文件夹
File typeFile = new File(typeDir);
if (!typeFile.exists()) {
typeFile.mkdirs();
}
}
//没有类型的文件,则直接放在根目录下即可(只需首轮添加这种无类型文件)
if(dirIndex == 1) {
if (serialNoMap.get(Fields.PARAM_FILE_TYPE) == null || "".equals(serialNoMap.get(Fields.PARAM_FILE_TYPE))) {
haveMatch = true;
Map requestMap = new HashMap();
requestMap.put("serialNo", serialNoMap.get("serialNo"));
Map resonMap = fileDownloadService.getFile(requestMap);
Map body = (Map) resonMap.get("body");
in = (InputStream) resonMap.get("is");
finalFileName = realZipDirName + File.separator + body.get("fileName");
}
}
if(haveMatch) {
File finalFile = new File(finalFileName);
if (!(finalFile.exists())) {
finalFile.createNewFile();
}
//写入文件
FileOutputStream fos = new FileOutputStream(finalFileName);
byte[] b = new byte[8192];
int len = 0;
while ((len = in.read(b)) != -1) {
fos.write(b, 0, len);
}
in.close();
fos.close();
}
}
if(needPlus){
dirIndex++;
}
}
String fileNameSer = CommonUtil.getCurrentTimeStr("TEMPZIP_", ".zip");
ZipUtil.createZip(realZipDirFile.getAbsolutePath(), zipDirFile.getParent() + File.separator + originalFileName + ".zip");
//压缩
InputStream in = new FileInputStream(zipDirFile.getParent() + File.separator + originalFileName + ".zip");
String interfaceType = Consts.UPLOAD_INTERFACE_TYPE;
if (StringUtils.isBlank(interfaceType)) {
interfaceType = Consts.UPLOAD_INTERFACE_TYPE_DEFAULT;
}
Map body = new HashMap();
String serialNo = commonService.getUUID();
String fileSuffix = "zip";
//保存本地
FmsFileLoad fmsFileLoad = new FmsFileLoad();
fmsFileLoad.setInterfaceType(interfaceType);
fmsFileLoad.setFileName(fileNameSer);
fmsFileLoad.setFilePath(applyFilePath);
fmsFileLoad.setFileSuffix(fileSuffix);
fmsFileLoad.setSerialNo(serialNo);
fmsFileLoad.setOriginalFileName(null == originalFileName ? fileNameSer : (originalFileName + ".zip"));
fmsFileLoadMapper.saveFileLoad(fmsFileLoad);
String url = null;
if (Consts.UPLOAD_INTERFACE_TYPE_Oss.equals(interfaceType)) {
Map returnMap = ossFileService.uploadFile2(in, applyFilePath, fileNameSer);
String md5key = (String) returnMap.get("md5key");
url = "/fileLoad/getFile" + "?serialNo=" + serialNo;
fmsFileLoad.setUrl(url);
fmsFileLoadMapper.modifyFileLoadUrl(fmsFileLoad);
}
//上传后删除本地生成文件
ZipUtil.deleteDir(zipDirFile);
boolean flag = ZipUtil.deleteZipFile(originalFileName + ".zip", in);
body.put("serialNo", fmsFileLoad.getSerialNo());
body.put("fileName", null == (originalFileName + ".zip") ? fileNameSer : (originalFileName + ".zip"));
body.put("url", url);
body.put("returnCode", ReturnCode.SUCCESS_CODE);
body.put("returnMessage", "完成上传");
Map result = new HashMap();
result.put("body", body);
return result;
}
private synchronized Map myUpload(Map map) throws Exception {
MultipartFile[] files = (MultipartFile[]) map.get("files");
String applyFilePath = (String) map.get("filePath");
if (StringUtils.isBlank(applyFilePath)) {
applyFilePath = Constants.APPLY_FILE_PATH;
}
String interfaceType = Consts.UPLOAD_INTERFACE_TYPE;
if (StringUtils.isBlank(interfaceType)) {
interfaceType = Consts.UPLOAD_INTERFACE_TYPE_DEFAULT;
}
Map body = new HashMap();
List<Map> fileMaps = new ArrayList();
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
String fileName = "";
if (file instanceof CommonsMultipartFile) {
fileName = ((CommonsMultipartFile) file).getFileItem().getName();
} else {
fileName = file.getName();
}
String sysFileName = commonService.getUUID();
String serialNo = commonService.getUUID();
String fileSuffix = "";
if (fileName.lastIndexOf(".") >= 0) {
sysFileName = sysFileName + fileName.substring(fileName.lastIndexOf("."));
fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
}
//保存本地
FmsFileLoad fmsFileLoad = new FmsFileLoad();
fmsFileLoad.setInterfaceType(interfaceType);
fmsFileLoad.setFileName(sysFileName);
fmsFileLoad.setFilePath(applyFilePath);
fmsFileLoad.setFileSuffix(fileSuffix);
fmsFileLoad.setSerialNo(serialNo);
fmsFileLoad.setOriginalFileName(fileName);
fmsFileLoadMapper.saveFileLoad(fmsFileLoad);
String url = null;
if (Consts.UPLOAD_INTERFACE_TYPE_Oss.equals(interfaceType)) {
Map returnMap = ossFileService.uploadFile2(file.getInputStream(), applyFilePath, sysFileName);
String md5key = (String) returnMap.get("md5key");
url = "/fileLoad/getFile" + "?serialNo=" + serialNo;
fmsFileLoad.setUrl(url);
fmsFileLoadMapper.modifyFileLoadUrl(fmsFileLoad);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Map fileMap = new HashMap();
fileMap.put("serialNo", fmsFileLoad.getSerialNo());
fileMap.put("fileName", fileName);
fileMap.put("url", url);
fileMap.put("uploadTime", sdf.format(new Date()));
fileMaps.add(fileMap);
}
body.put("fileMaps", fileMaps);
body.put("returnCode", ReturnCode.SUCCESS_CODE);
body.put("returnMessage", "完成上传");
Map result = new HashMap();
result.put("body", body);
return result;
}
}
|
package example.payrollNoOptional;
public class Employer {
}
|
package com.zenaufa.popularmovie.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import com.zenaufa.popularmovie.DetailActivity;
import com.zenaufa.popularmovie.R;
import com.zenaufa.popularmovie.model.Results;
import java.util.ArrayList;
import java.util.List;
public class ContactAdapter extends
RecyclerView.Adapter<ContactAdapter.ViewHolder>{
private Context context;
private List<Results> movies;
GestureDetector mGestureDetector;
public ContactAdapter(Context context, List<Results> movies){
super();
this.context = context;
this.movies = new ArrayList<>();
if (movies != null)
this.movies.addAll(movies);
}
@Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.row_poster, parent, false);
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Results results = movies.get(position);
final int pos = position;
String url = "http://image.tmdb.org/t/p/w185/" + results.getPosterPath();
Picasso.with(context)
.load(url)
.error(R.mipmap.ic_launcher)
.into(holder.imageView);
holder.imageView.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("movieDesc", movies.get(pos).getOverview());
intent.putExtra("movieTitle", movies.get(pos).getTitle());
intent.putExtra("movieId", movies.get(pos).getId());
intent.putExtra("movieImg", movies.get(pos).getPosterPath());
intent.putExtra("movieRelease", movies.get(pos).getReleaseDate());
intent.putExtra("movieRating", movies.get(pos).getVoteAverage());
intent.putExtra("movieReview", movies.get(pos).getContent());
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return movies.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image_view);
}
}
}
|
package com.tencent.mm.ui.chatting.b;
import com.tencent.mm.ac.e$a$b;
import com.tencent.mm.ac.e.a;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
class c$12 implements a {
final /* synthetic */ c tOm;
c$12(c cVar) {
this.tOm = cVar;
}
public final void a(e$a$b e_a_b) {
if (e_a_b != null && e_a_b.dMb == a.a.dLZ && e_a_b.dKF != null && e_a_b.dKF.equals(this.tOm.bAG.getTalkerUserName())) {
au.HU();
ab Yg = c.FR().Yg(e_a_b.dKF);
if (Yg == null || ((int) Yg.dhP) == 0) {
x.i("MicroMsg.ChattingUI.BizComponent", "Get contact from db return null.(username : %s)", new Object[]{e_a_b.dKF});
return;
}
ah.A(new 1(this, e_a_b, Yg));
}
}
}
|
/*
* 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 employeeapp;
/**
*
* @author x17448556
*/
public class EmployeeApp {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
EmployeeGUI myGUI = new EmployeeGUI();
myGUI.setVisible(true);
/*FloorStaff f1 = new FloorStaff(15.50, 20, "Joe", "5555", "12/06/1987");
System.out.println(f1.printDetails());
Manager m2 = new Manager(20000.20, "Tom. T", "45654", "20/05/1986");
System.out.println(m2.printDetails());
m2.computeWPay();
System.out.println("Weekly pay: " +m2.getwPay());*/
}
}
|
package org.alienideology.jcord.handle.builders;
import org.alienideology.jcord.handle.Icon;
import org.alienideology.jcord.handle.client.app.IApplication;
import org.alienideology.jcord.internal.object.client.app.Application;
/**
* ApplicationBuilder - A builder for creating an {@link IApplication}. Used by {@link org.alienideology.jcord.handle.managers.IClientManager}.
*
* @author AlienIdeology
* @since 0.1.4
*/
public final class ApplicationBuilder implements Buildable<ApplicationBuilder, IApplication> {
private String name;
private Icon icon;
private String description;
public ApplicationBuilder() {
clear();
}
/**
* Build an application.
*
* @return The application built, used in {@link org.alienideology.jcord.handle.managers.IClientManager#createApplication(IApplication)}.
*/
@Override
public IApplication build() {
return new Application(null, null)
.setName(name)
.setIcon(icon == null || icon == Icon.DEFAULT_ICON ? null : (String) icon.getData())
.setDescription(description);
}
@Override
public ApplicationBuilder clear() {
name = null;
icon = null;
description = null;
return this;
}
/**
* Set the name of this application.
*
* @exception IllegalArgumentException
* If the name is not valid. See {@link IApplication#isValidName(String)}.
*
* @param name The string name.
* @return ApplicationBuilder for chaining.
*/
public ApplicationBuilder setName(String name) {
if (!IApplication.isValidName(name)) {
throw new IllegalArgumentException("Invalid application name!");
}
this.name = name;
return this;
}
/**
* Set the icon of this application.
*
* @param icon The image file.
* @return ApplicationBuilder for chaining.
*/
public ApplicationBuilder setIcon(Icon icon) {
this.icon = icon;
return this;
}
/**
* Set the description of this application.
*
* @exception IllegalArgumentException
* If the description is not valid. See {@link IApplication#isValidDescription(String)}.
*
* @param description The description.
* @return ApplicationBuilder for chaining.
*/
public ApplicationBuilder setDescription(String description) {
if (!IApplication.isValidDescription(description)) {
throw new IllegalArgumentException("Invalid application description!");
}
this.description = description;
return this;
}
}
|
/*
* 방만들기 화면2-2 - 정기 모임일 때 시간 선택
*/
package com.example.test;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.ArrayList;
import java.util.Calendar;
public class newgroup2 extends Activity {
String ID,roomname;
ArrayList<String> memberlist=new ArrayList<String>();//방멤버 리스트
int daycheck;
String day;
int starttime;
int dayreturnvalue;
private TextView mDateDisplay;
private TextView mTimeDisplay;
private Button mPickDate;
private Button mPickTime;
private int mYear;
private int mMonth;
private int mDay;
private int mHour;
private int mMinute;
static final int DATE_DIALOG_ID = 1;
static final int TIME_DIALOG_ID = 0;
RadioButton rb1,rb2,rb3,rb4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newgroup2);
MainActivity ma=new MainActivity();
Typeface mTypeface=Typeface.createFromAsset(getAssets(), "fonts/hun.ttf");
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
ma.setGlobalFont(root,mTypeface);
Intent intent_01 = getIntent();
ID = intent_01.getStringExtra("아이디");
roomname = intent_01.getStringExtra("방이름");
memberlist=intent_01.getStringArrayListExtra("멤버리스트");
daycheck=intent_01.getIntExtra("daycheck", -1);
// capture our View elements
mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
mTimeDisplay = (TextView) findViewById(R.id.new2cEntry);
mPickDate = (Button) findViewById(R.id.pickDate);
mPickTime = (Button) findViewById(R.id.makemeetgo);
rb1=(RadioButton)findViewById(R.id.radio01);
rb2=(RadioButton)findViewById(R.id.radio02);
rb3=(RadioButton)findViewById(R.id.radio03);
rb4=(RadioButton)findViewById(R.id.radio04);
rb3.setChecked(true);//기본선택
// add a click listener to the button
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
mPickTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get (Calendar.MINUTE);
// display the current date (this method is below)
updateDisplay();
updateDisplay2();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, mHour, mMinute, false);
}
return null;
}
// updates the date we display in the TextView
private void updateDisplay() {
mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mYear).append("년 ")
.append(mMonth+1).append("월 ")
.append(mDay).append("일")
);
String newm=pad(mMonth+1);
String newd=pad(mDay);
day=mYear+"-"+newm+"-"+newd;//2015-06-02 형식으로 바꿔서 넣기
}
private void updateDisplay2() {
mTimeDisplay.setText(
new StringBuilder()
.append(mHour).append("시 ")//.append(mMinute).append("분")
);
starttime=mHour;
}
// the callback received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
updateDisplay2();
}
};
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
public void newnext(View v){
if(rb1.isChecked()){
dayreturnvalue=1;
}
else if(rb2.isChecked()){
dayreturnvalue=2;
}
else if(rb3.isChecked()){
dayreturnvalue=3;
}
else if(rb4.isChecked()){
dayreturnvalue=4;
}
Intent intent=new Intent(getApplicationContext(), newgroup4.class);
intent.putExtra("daycheck", daycheck);
intent.putExtra("아이디", ID);
intent.putExtra("방이름", roomname);
intent.putExtra("멤버리스트", memberlist);
intent.putExtra("day", day);
intent.putExtra("starttime",starttime);
intent.putExtra("dayreturnvalue",dayreturnvalue);
startActivity(intent);
}
public void home(View v)
{
Intent intent=new Intent(getApplicationContext(), Mainselect.class);
intent.putExtra("아이디", ID);
startActivity(intent);
}
public void setting(View v)
{
Intent intent=new Intent(getApplicationContext(), Settingmain.class);
intent.putExtra("아이디", ID);
startActivity(intent);
}
}
|
package io.github.fluentbuilder.api.impl;
import io.github.fluentbuilder.api.BuilderFactory;
import io.github.fluentbuilder.internal.BuilderModel;
import io.github.fluentbuilder.internal.BuilderStackFrame;
import io.github.fluentbuilder.internal.ServiceCartrige;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Stack;
public class ReflectionBuilderFactory implements BuilderFactory {
public Object newBuilder(BuilderModel model, ServiceCartrige serviceCartrige, Stack<BuilderStackFrame> stack) {
ClassLoader classLoader = getClass().getClassLoader();
InvocationHandler h = new BuilderInvocationHandler(model, this, serviceCartrige, stack);
return Proxy.newProxyInstance(classLoader, new Class<?>[] { model.getBuilderClass() }, h);
}
}
|
import java.util.Scanner;
public class BMICalculator {
public static void main( String[] args ) {
Scanner keyboard = new Scanner(System.in);
double m, kg, bmi, lb, in, totalinches;
int feet;
System.out.print( "Your height (feet only): " );
feet = keyboard.nextInt();
System.out.print( "Your remaining height in inches: " );
in = keyboard.nextDouble();
totalinches = (feet*12) + in;
System.out.print ( "Your weight in kg: " );
lb = keyboard.nextDouble();
m = totalinches * 0.0254;
kg = lb * 0.453592;
bmi = kg / (m*m);
System.out.println( "Your BMI is " + bmi );
}
}
|
package com.hs.example.base._7extends;
/**
* 必须实现标记接口 Cloneable 否则会抛出CloneNotSupportedException异常
*/
public class AnObject implements Cloneable{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "AnObject{" +
"name='" + name + '\'' +
'}';
}
public void test() throws CloneNotSupportedException {
super.clone();
}
protected Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
|
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
String html = Jsoup.connect("https://www.pashabank.az/").get().html();
Document doc = Jsoup.parse(html, "utf-8");
Elements hrefs = doc.getElementsByTag("a");
Set<String> set = hrefs.stream()
.map(href -> href.attr("href"))
.filter(href -> href.startsWith("https://www.pashabank.az"))
.collect(Collectors.toSet());
System.out.println(rec(set, set, set.size()).size());
}
public static Set<String> rec(Set<String> allset, Set<String> checkSet, int count) throws IOException {
if (count == 0) {
return allset;
}
int incount = 0;
int a = count;
Set<String> inset;
Set<String> returnset = new HashSet<>();
for (String href : checkSet) {
try {
String inhtml = Jsoup.connect(href).get().html();
Document indoc = Jsoup.parse(inhtml, "utf-8");
Elements inhrefs = indoc.getElementsByTag("a");
inset = inhrefs.stream()
.map(inhref -> inhref.attr("href"))
.filter(inhref -> inhref.startsWith("https://www.pashabank.az"))
.collect(Collectors.toSet());
for (String h : inset) {
if (!allset.contains(h) && !returnset.contains(h)) {
returnset.add(h);
System.out.println(a + " " + h);
a++;
incount++;
}
}
} catch (Exception e) {
}
}
allset.addAll(returnset);
System.out.println(allset.size());
return rec(allset, returnset, incount);
}
}
|
package com.cz.android.sample.listview.list1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.cz.android.sample.R;
import java.util.ArrayList;
import java.util.List;
public class SampleAdapter extends SimpleListView.Adapter {
private static final String TAG="SampleAdapter";
public final List<String> itemList=new ArrayList<>();
public SampleAdapter(List<String> itemList) {
if(null!=itemList){
this.itemList.addAll(itemList);
}
}
@Override
public int getItemCount() {
return itemList.size();
}
@Override
public View onCreateView(ViewGroup parent, int position) {
Context context = parent.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
return layoutInflater.inflate(R.layout.simple_text_item,parent,false);
}
@Override
public void onBindView(View view, final int position) {
String item = itemList.get(position);
TextView textView=view.findViewById(android.R.id.text1);
textView.setText(item);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"Click:"+position,Toast.LENGTH_SHORT).show();
}
});
}
}
|
package creditcard.ui;
import framework.commands.Command;
import framework.commands.CommandManager;
import framework.commands.DepositComand;
import framework.ui.DepositDialog;
import framework.util.ValidatorUtil;
import creditcard.services.AccountServiceImp;
public class JDialog_Deposit extends DepositDialog {
public JDialog_Deposit(String aaccnr) {
super(aaccnr);
}
@Override
public void JButtonOK_actionPerformed(java.awt.event.ActionEvent event) {
if (!ValidatorUtil.isNumeric(JTextField_Deposit.getText())) {
isNewDeposit = false;
dispose();
return;
}
Command command = new DepositComand(AccountServiceImp.getInstance(), accnr, Double.parseDouble(JTextField_Deposit.getText()));
CommandManager manager = CommandManager.getInstance();
manager.setCommand(command);
try {
manager.invokeCommand();
} catch (RuntimeException e) {
e.printStackTrace();
}
dispose();
}
}
|
package com.mohit.chatappminor;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
public class ForgotPassword extends AppCompatActivity {
private EditText edtEmail;
private Button btnResetPassword;
private Button btnBack;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password);
edtEmail = (EditText) findViewById(R.id.email);
btnResetPassword = (Button) findViewById(R.id.btn_reset_password);
btnBack = (Button) findViewById(R.id.btn_back);
mAuth = FirebaseAuth.getInstance();
btnResetPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = edtEmail.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter your email!", Toast.LENGTH_SHORT).show();
}
mAuth.sendPasswordResetEmail(email)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ForgotPassword.this, "Check email to reset your password!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ForgotPassword.this, "Fail to send reset password email!", Toast.LENGTH_SHORT).show();
}
}
});
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent viewIntent = new Intent(ForgotPassword.this, Main2Activity.class);
startActivity(viewIntent);
}
});
}
@Override
public void onBackPressed() {
Intent viewIntent = new Intent(ForgotPassword.this, Main2Activity.class);
startActivity(viewIntent);
ForgotPassword.this.finish();
}
}
|
package symcryptolab1;
import symcryptolab1.alphabet.*;
import java.util.*;
public class CaesarCryptanalysis {
private static Map<Character, Double> countProbabilities(String cipherText, Alphabet alphabet) {
Map<Character, Double> probs = new HashMap<>();
Map<String, Integer> freqs = FrequencyCounter.count(cipherText, 1, true);
for (Map.Entry<String, Integer> entry : freqs.entrySet()) {
probs.put(entry.getKey().charAt(0), entry.getValue() / (double) cipherText.length());
}
//если какие-то символы не встретились в шифртексте,
//то добавляем их в карту с нулевыми вероятностями
if (probs.size() != alphabet.size()) {
for (int i = 0; i < alphabet.size(); i++) {
char character = alphabet.getCharacter(i);
if (!probs.containsKey(character)) {
probs.put(character, 0.0);
}
}
}
return probs;
}
private static List<Character> sortCharsByPopularity(final Map<Character, Double> probs) {
List<Character> chars = new ArrayList<>(probs.keySet());
//сортируем по частотам, в обратном порядке
Collections.sort(chars, new Comparator<Character>() {
public int compare(Character c1, Character c2) {
return Double.compare(probs.get(c2), probs.get(c1));
}
});
return chars;
}
public static char mostProbableKey(String cipherText, Alphabet alphabet) {
AlphabetStatistics stat = AlphabetStatistics.getStatistics(alphabet);
List<Character> textTopChars
= sortCharsByPopularity(countProbabilities(cipherText, alphabet))
.subList(0, stat.getTopLettersOfText());
List<Character> alphabetTopChars
= sortCharsByPopularity(stat.getCharactersDistribution())
.subList(0, stat.getTopLettersOfAlphabet());
//Теперь попытаемся найти такой сдвиг, при котором
//все топ-буквы алфавита перейдут в некоторые из
//топ букв шифртекста.
//Будем по очереди совмещать первую топ-букву алфавита
//с каждой из топ-букв шифртекста, проверяя, переходят
//ли при этом остальные топ-буквы алфавита в какие-либо
//из топ-букв текста. Если переходят, то есть все
//основания предполагать что мы нашли подходящий ключ.
char key = 0;
boolean contains = false;
char alphaTop = alphabetTopChars.get(0);
//продолжаем поиск пока не исчерпаем все символы или пока
//не будет обнаружено соответствие
for (int i = 0; i < textTopChars.size() && !contains; i++) {
char textChar = textTopChars.get(i);
key = alphabet.sub(textChar, alphaTop);
contains = true;
//продолжаем сопоставление до тех пор, пока обнаруживаются совпадения
for (int j = 1; j < alphabetTopChars.size() && contains; j++) {
char alphaChar = alphabetTopChars.get(j);
char alphaCharImage = alphabet.add(alphaChar, key);
contains = textTopChars.contains(alphaCharImage);
}
//если флаг сохранил свое состояние, значит всем символам нашлось
//соответствие, можем прекратить дальнейший поиск, что и произойдет
//при проверке условия продолжения цикла !contains
}
if (contains) {
return key;
}
//Если так ничего и не нашли, то просто вычисляем ключ
//по самой популярной букве алфавита и открытого текста.
System.out.println(alphabetTopChars);
System.out.println(textTopChars);
key = alphabet.sub(textTopChars.get(0), alphabetTopChars.get(0));
System.out.println(key);
return key;
}
}
|
package eu.dons.struggle.doctor.bprot.jaxb;
public class BProtLeistungGesamtbedarfPersonenZelle {
private String persNr;
private Integer summe;
private Integer summeFiktiv;
public String getPersNr() {
return persNr;
}
public void setPersNr(String persNr) {
this.persNr = persNr;
}
public Integer getSumme() {
return summe;
}
public void setSumme(Integer summe) {
this.summe = summe;
}
public Integer getSummeFiktiv() {
return summeFiktiv;
}
public void setSummeFiktiv(Integer summeFiktiv) {
this.summeFiktiv = summeFiktiv;
}
}
|
package update;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;
public class exer1 {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
Scanner scan = new Scanner(System.in);
System.out.println("请输入用户名:");
String name = scan.next();
System.out.println("请输入邮箱:");
String email = scan.next();
System.out.println("请输入生日:");
String birthday = scan.next();
update(name,email,birthday);
select(email);
}
public static void update(String name, String email, String birthday) throws IOException, SQLException, ClassNotFoundException {
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
Class.forName(driverClass);
Connection conn = DriverManager.getConnection(url, user, password);
String sql = "insert into customers(name,email,birth) values(?,?,?) ";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1,name);
ps.setObject(2,email);
ps.setObject(3,birthday);
//执行操作
ps.execute();
conn.close();
ps.close();
}
public static void select(String email) throws IOException, ClassNotFoundException, SQLException {
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
Class.forName(driverClass);
Connection conn = DriverManager.getConnection(url, user, password);
String sql = "select name from customers where email = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1,email);
ResultSet resultSet = ps.executeQuery();
if (resultSet.next()){
System.out.println("插入成功");
}else {
System.out.println("插入失败");
}
ps.close();
conn.close();
resultSet.close();
}
}
|
package semantics;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
import semantics.KnowBase;
import semantics.model.Concept;
import semantics.model.Individual;
import semantics.model.Role;
import static org.junit.Assert.*;
import static semantics.Util.*;
public class UtilTest {
private static KnowBase kb;
private static Individual beatles;
private static Individual hendrix;
@BeforeClass
public static void setUpClass() {
kb = KnowBase.of("music.rdf");
beatles = new Individual("music.rdf", "http://example.org/music#beatles");
hendrix = new Individual("music.rdf", "http://example.org/music#hendrix");
}
@Test
public void testConcept() {
assertEquals(new Concept(":Wine"), concept(":Wine"));
}
@Test
public void testRole() {
assertEquals(new Role(":hasColor"), role(":hasColor"));
}
@Test
public void testIris() {
Set<Individual> artists = kb.query(concept(":MusicArtist"));
Set<String> expectedSet = new HashSet<>();
expectedSet.add("http://example.org/music#beatles");
expectedSet.add("http://example.org/music#hendrix");
assertEquals(expectedSet, iris(artists));
List<String> list = sorted(iris(new ArrayList<Individual>(artists)));
assertEquals(2, list.size());
assertEquals("http://example.org/music#beatles", list.get(0));
assertEquals("http://example.org/music#hendrix", list.get(1));
}
@Test
public void testNames() {
Set<Individual> artists = kb.query(concept(":MusicArtist"));
Set<String> expectedSet = new HashSet<>();
expectedSet.add("beatles");
expectedSet.add("hendrix");
assertEquals(expectedSet, names(artists));
List<String> list = sorted(names(new ArrayList<Individual>(artists)));
assertEquals(2, list.size());
assertEquals("beatles", list.get(0));
assertEquals("hendrix", list.get(1));
}
@Test
public void testSorted() {
List<Individual> artists = sorted(kb.query(concept(":MusicArtist")));
assertEquals(2, artists.size());
assertEquals(beatles, artists.get(0));
assertEquals(hendrix, artists.get(1));
}
@Test
public void testHead() {
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
assertEquals(null, head(list));
assertEquals(null, head(set));
assertEquals(null, head(list, null));
assertEquals(null, head(set, null));
assertEquals("dummy", head(list, "dummy"));
assertEquals("dummy", head(set, "dummy"));
list.add("hello");
list.add("world");
set .add("hello");
assertEquals("hello", head(list));
assertEquals("hello", head(set));
assertEquals("hello", head(list, null));
assertEquals("hello", head(set, null));
assertEquals("hello", head(list, "dummy"));
assertEquals("hello", head(set, "dummy"));
list.remove(0);
assertEquals("world", head(list));
assertEquals("world", head(list, null));
assertEquals("world", head(list, "dummy"));
list.add(0, null);
assertEquals(null, head(list));
assertEquals(null, head(list, null));
assertEquals(null, head(list, "dummy"));
}
}
|
package edu.view.ui.student;
import edu.curd.dto.ClassDTO;
import edu.curd.dto.StudentDTO;
import edu.curd.operation.JDBCDataObject;
import edu.data.service.ManageAttendenceService;
import edu.data.service.ManageClassService;
import edu.data.service.ManageStudentService;
import edu.data.service.impl.ManageAttendenceServiceImpl;
import edu.data.service.impl.ManageClassImpl;
import edu.data.service.impl.ManageStudentServiceImpl;
import edu.view.ui.MainForm;
import edu.view.ui.WelcomeFrame;
import edu.view.ui.classes.attendence.MarkAttendence;
import edu.view.ui.util.GenericComboItem;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
public class ManageStudentAttendance extends JDialog {
ManageStudentService manageStudentService = new ManageStudentServiceImpl();
ManageClassService manageClassService = new ManageClassImpl();
ManageAttendenceService manageAttendenceService = new ManageAttendenceServiceImpl();
private static String DATE_PATTERN = "dd-MM-yyyy h:m";
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ManageStudentAttendance.DATE_PATTERN);
public ManageStudentAttendance(MainForm parent) {
super(parent);
initComponent();
}
private void initComponent() {
uName_label1 = new javax.swing.JLabel();
header = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
content = new javax.swing.JPanel();
uName_label = new javax.swing.JLabel();
cmbClasses = new javax.swing.JComboBox<>();
jScrollPane1 = new javax.swing.JScrollPane();
studentTable = new javax.swing.JTable();
uName_label2 = new javax.swing.JLabel();
lblDatetTime = new javax.swing.JLabel();
cancle = new javax.swing.JButton();
save = new javax.swing.JButton();
uName_label1.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
uName_label1.setForeground(new java.awt.Color(204, 204, 204));
uName_label1.setText("Class ID:");
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
header.setBackground(new java.awt.Color(30, 130, 76));
header.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel1.setBackground(new java.awt.Color(102, 102, 102));
jLabel1.setFont(new java.awt.Font("Arial", 1, 48)); // NOI18N
jLabel1.setText("Class Attendance");
javax.swing.GroupLayout headerLayout = new javax.swing.GroupLayout(header);
header.setLayout(headerLayout);
headerLayout.setHorizontalGroup(
headerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, headerLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 488, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(24, 24, 24))
);
headerLayout.setVerticalGroup(
headerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(headerLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
content.setBackground(new java.awt.Color(51, 51, 51));
uName_label.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
uName_label.setForeground(new java.awt.Color(204, 204, 204));
uName_label.setText("Class ID:");
cmbClasses.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmbClassesActionPerformed(evt);
}
});
studentTable.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jScrollPane1.setViewportView(studentTable);
uName_label2.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
uName_label2.setForeground(new java.awt.Color(204, 204, 204));
uName_label2.setText("Date:");
lblDatetTime.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
lblDatetTime.setForeground(new java.awt.Color(204, 204, 204));
lblDatetTime.setText("XXXX-XX-XX");
cancle.setText("Cancel");
cancle.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancleActionPerformed(evt);
}
});
save.setText("Save");
save.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveActionPerformed(evt);
}
});
javax.swing.GroupLayout contentLayout = new javax.swing.GroupLayout(content);
content.setLayout(contentLayout);
contentLayout.setHorizontalGroup(
contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(contentLayout.createSequentialGroup()
.addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(contentLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1)
.addGroup(contentLayout.createSequentialGroup()
.addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(uName_label)
.addComponent(uName_label2))
.addGap(122, 122, 122)
.addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cmbClasses, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblDatetTime, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(contentLayout.createSequentialGroup()
.addGap(149, 149, 149)
.addComponent(cancle)
.addGap(79, 79, 79)
.addComponent(save)))
.addContainerGap(27, Short.MAX_VALUE))
);
contentLayout.setVerticalGroup(
contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(contentLayout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(uName_label)
.addComponent(cmbClasses, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(uName_label2)
.addComponent(lblDatetTime))
.addGap(31, 31, 31)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 331, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
.addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(save)
.addComponent(cancle))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(content, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(header, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(header, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(content, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
initDataTable();
loadClassDetails();
lblDatetTime.setText(simpleDateFormat.format(new Date()));
}
});
}
public static void main(String arg[]) {
}
private void cmbClassesActionPerformed(ActionEvent evt) {
List<StudentDTO> studentsList = manageClassService.viewEnrolledStuents(getSelectedClassId());
if (studentsList == null || studentsList.isEmpty()) {
JOptionPane.showMessageDialog(this, "No Students are enrolled for this subject!");
tableModel.setRowCount(0);
return;
}
tableModel.setRowCount(0);
for (int index = 0; index < studentsList.size(); index++) {
tableModel.addRow(new Object[0]);
tableModel.setValueAt(false, index, 0);
tableModel.setValueAt(studentsList.get(index).getStudentId(), index, 1);
tableModel.setValueAt(studentsList.get(index).getFirstName() + " " + studentsList.get(index).getLastName(), index, 2);
tableModel.setValueAt(studentsList.get(index).getEnrollmentId(), index, 3);
}
}
private int getSelectedClassId() {
try {
String selectedClass = (String) cmbClasses.getSelectedItem();
int selectedClassId = Integer.valueOf(selectedClass.split(" - ")[0]);
return selectedClassId;
} catch (Exception e) {
// JOptionPane.showMessageDialog(this, "No Classes were selected!");
}
return 0;
}
private javax.swing.JPanel header;
private DefaultTableModel tableModel = new DefaultTableModel() {
public Class<?> getColumnClass(int column) {
switch (column) {
case 0:
return Boolean.class;
case 1:
return String.class;
case 2:
return String.class;
case 3:
return String.class;
default:
return String.class;
}
}
};
private void initDataTable() {
studentTable.setModel(tableModel);
tableModel.addColumn("Student Present");
tableModel.addColumn("Student ID");
tableModel.addColumn("Student Name");
tableModel.addColumn("Enrollment ID");
}
private void loadClassDetails() {
tableModel.setRowCount(0);
List<JDBCDataObject> classObjLis = manageClassService.viewAllClasses();
if (classObjLis != null && !classObjLis.isEmpty()) {
classObjLis.forEach((classRow) -> {
ClassDTO classObject = (ClassDTO) classRow;
cmbClasses.addItem(new GenericComboItem(classObject.getClassId(), classObject.getTopic()).toString());
});
} else {
// JOptionPane.showMessageDialog(this, "No Classes to display!");
}
}
private void saveActionPerformed(ActionEvent evt) {
Map<String, String> markedStuendts = obtainAttendence();
if (markedStuendts.isEmpty()) {
JOptionPane.showMessageDialog(this, "No Students were marked, please select the students!");
} else {
if (manageAttendenceService.saveAttendence(getSelectedClassId(), markedStuendts)) {
JOptionPane.showMessageDialog(this, "Students : " + markedStuendts.toString() + " \n marked present.");
} else {
JOptionPane.showMessageDialog(this, "Error while saving attendence.");
}
}
}
private Map<String, String> obtainAttendence() {
Map<String, String> studentIds = new HashMap<>();
for (int index = 0; index < studentTable.getRowCount(); index++) {
Boolean checked = Boolean.valueOf(studentTable.getValueAt(index, 0).toString());
String studentId = studentTable.getValueAt(index, 1).toString();
String enrollId = studentTable.getValueAt(index, 3).toString();
if (checked) {
studentIds.put(studentId, enrollId);
}
}
return studentIds;
}
private void cancleActionPerformed(ActionEvent evt) {
this.setVisible(false);
}
private javax.swing.JButton cancle;
private javax.swing.JComboBox<String> cmbClasses;
private javax.swing.JPanel content;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblDatetTime;
private javax.swing.JButton save;
private javax.swing.JTable studentTable;
private javax.swing.JLabel uName_label;
private javax.swing.JLabel uName_label1;
private javax.swing.JLabel uName_label2;
}
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package org.usfirst.frc.team1165.robot;
import org.usfirst.frc.team1165.robot.commands.auto.CrossAutoLineCenter;
import org.usfirst.frc.team1165.robot.commands.auto.CrossAutoLineSide;
import org.usfirst.frc.team1165.robot.commands.auto.DriveStraightDistance;
import org.usfirst.frc.team1165.robot.commands.auto.RotateToRelHeading;
import org.usfirst.frc.team1165.robot.subsystems.Claw;
import org.usfirst.frc.team1165.robot.subsystems.Climber;
import org.usfirst.frc.team1165.robot.subsystems.DriveTrain;
import org.usfirst.frc.team1165.robot.subsystems.LinearLift;
import org.usfirst.frc.team1165.robot.subsystems.RotaryLift;
import org.usfirst.frc.team1165.robot.subsystems.Shooter;
import org.usfirst.frc.team1165.robot.subsystems.Wings;
import org.usfirst.frc.team1165.robot.subsystems.pid.DriveStraightPID;
import org.usfirst.frc.team1165.robot.subsystems.pid.DriveRotatePID;
import org.usfirst.frc.team1165.robot.util.drivers.NavX;
import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the TimedRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the build.properties file in the
* project.
*/
public class Robot extends TimedRobot
{
public static final DriveTrain mDriveTrain = new DriveTrain();
public static final DriveStraightPID mDriveStraightPID = new DriveStraightPID();
public static final DriveRotatePID mRotatePID = new DriveRotatePID();
public static final Shooter mShooter = new Shooter();
public static final RotaryLift mRotaryLift = new RotaryLift();
// public static final RotaryLiftPID mRotaryLiftPID = new RotaryLiftPID();
public static final LinearLift mLinearLift = new LinearLift();
public static final Claw mClaw = new Claw();
public static final Climber mClimber = new Climber();
public static final Wings mWings = new Wings();
private Command mAuto;
private SendableChooser<Command> mAutoChooser = new SendableChooser<>();
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
@Override
public void robotInit()
{
// mWings.init();
mAutoChooser.addDefault("Center Auto", new CrossAutoLineCenter());
mAutoChooser.addObject("Side Auto", new CrossAutoLineSide());
mAutoChooser.addObject("Drive Straight (60)", new DriveStraightDistance(60));
mAutoChooser.addObject("Rotate (90)", new RotateToRelHeading(90));
SmartDashboard.putData("Auto mode", mAutoChooser);
}
@Override
public void robotPeriodic()
{
mDriveTrain.report();
mDriveStraightPID.report();
mRotatePID.report();
// mShooter.report();
// mRotaryLift.report();
// mRotaryLiftPID.report();
// mLinearLift.report();
// mClaw.report();
// mClimber.report();
// mWings.report();
NavX.report();
}
/**
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
@Override
public void disabledInit()
{
}
@Override
public void disabledPeriodic()
{
Scheduler.getInstance().run();
}
/**
* This autonomous (along with the chooser code above) shows how to select
* between different autonomous modes using the dashboard. The sendable
* chooser code works with the Java SmartDashboard. If you prefer the
* LabVIEW Dashboard, remove all of the chooser code and uncomment the
* getString code to get the auto name from the text box below the Gyro
*
* <p>
* You can add additional auto modes by adding additional commands to the
* chooser code above (like the commented example) or additional comparisons
* to the switch structure below with additional strings & commands.
*/
@Override
public void autonomousInit()
{
mAuto = mAutoChooser.getSelected();
if (mAuto != null)
{
mAuto.start();
}
}
/**
* This function is called periodically during autonomous.
*/
@Override
public void autonomousPeriodic()
{
Scheduler.getInstance().run();
}
@Override
public void teleopInit()
{
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (mAuto != null)
{
mAuto.cancel();
}
}
/**
* This function is called periodically during operator control.
*/
@Override
public void teleopPeriodic()
{
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode.
*/
@Override
public void testPeriodic()
{
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.miniprogram_navigator;
import com.tencent.mm.plugin.appbrand.MiniProgramNavigationBackResult;
import com.tencent.mm.plugin.appbrand.g;
import com.tencent.mm.plugin.appbrand.g.6;
import com.tencent.mm.plugin.appbrand.jsapi.a;
import org.json.JSONObject;
public final class c extends a {
public static final int CTRL_INDEX = 252;
public static final String NAME = "navigateBackMiniProgram";
public final void a(com.tencent.mm.plugin.appbrand.jsapi.c cVar, JSONObject jSONObject, int i) {
JSONObject optJSONObject = jSONObject.optJSONObject("extraData");
JSONObject optJSONObject2 = jSONObject.optJSONObject("privateExtraData");
g runtime = cVar.getRuntime();
runtime.fcq.runOnUiThread(new 6(runtime, MiniProgramNavigationBackResult.a(optJSONObject, optJSONObject2)));
}
}
|
/**
*
*/
package com.cnk.travelogix.mdmbackoffice.interceptor;
import de.hybris.platform.core.model.user.EmployeeModel;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.InterceptorException;
import de.hybris.platform.servicelayer.interceptor.PrepareInterceptor;
/**
* This PrepareIntersepter used for setting the Employee name with combination of firstName+middleName+lastName
*
* @author C5244543
*
*/
public class EmployeePrepareIntercepter implements PrepareInterceptor<EmployeeModel>
{
/*
* (non-Javadoc)
*
* @see de.hybris.platform.servicelayer.interceptor.PrepareInterceptor#onPrepare(java.lang.Object,
* de.hybris.platform.servicelayer.interceptor.InterceptorContext)
*/
@Override
public void onPrepare(final EmployeeModel employee, final InterceptorContext arg1) throws InterceptorException
{
final StringBuffer displayName = new StringBuffer();
displayName.append(employee.getFirstName());
displayName.append(
employee.getMiddleName() != null && !employee.getMiddleName().isEmpty() ? " " + employee.getMiddleName() : "");
displayName.append(employee.getLastName() != null && !employee.getLastName().isEmpty() ? " " + employee.getLastName() : "");
employee.setName(displayName.toString());
}
}
|
package twilight.bgfx.tests;
/**
*
* @author tmccrary
*
*/
public class Base {
public Base() {
}
}
|
package com.smxknife.mybatis._comm.mapper;
import com.smxknife.mybatis._comm.po.Blog;
/**
* @author smxknife
* 2021/6/18
*/
public interface BlogMapper {
Blog selectBlog(int id);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.